2017-09-13 152 views
1

學習django。我有一個問題。 我已經完成了反饋表單,我需要在反饋表單確認後將用戶重定向到同一頁面。下面是代碼:Django get_absolute_url(將表單提交後返回到同一頁面)

models.py

class Feedback(models.Model): 
     title = models.CharField(max_length=255) 
     text = models.TextField(max_length=5000) 
     user_name = models.CharField(max_length=255) 
     user_lastname = models.CharField(max_length=255) 
     email = models.EmailField(max_length=255) 
     send_time = models.DateTimeField(auto_now_add=True) 
     update_time = models.DateTimeField(auto_now=True) 

     def get_absolute_url(self): 
      return 

urls.py

url(r'^feedback$',views.FeedbackSendForm.as_view(), name='feedback'), 

views.py

class FeedbackSendForm(CreateView): 
     model = Feedback 
     fields = [ 
      'title', 
      'text', 
      'user_name', 
      'user_lastname', 
      'email', 
      ] 
     template_name = 'feedback.html' 

個feedback.html

<form method="post"> 
    {% csrf_token %} 
    {% for field in form %} 
     <span class="text-danger">{{ field.errors }}</span> 
     <div> 
      <label class="control-label">{{ field.label }}</label> 
      {{ field }} 
     </div> 
    {% endfor %} 
    <button type="submit">Submit</button> 
</form> 

任何想法?請幫忙。 預先感謝您

+0

運行時出現錯誤?如果是,可以發佈Traceback? –

+1

請修復您的代碼縮進。 –

+0

沒有錯誤。我只是不知道該「迴歸」 – Aziz

回答

0

如果你想覆蓋get_absolute_url您的機型,下面的代碼可以幫助你:

from django.urls import reverse 


class Feedback(models.Model): 
    # the model fields 

    def get_absolute_url(self): 
     # reverse expects the view name 
     return reverse('feedback') 

任何Feedback對象的絕對URL將是視圖FeedbackSendForm。這通過將視圖名稱feedback傳遞到reverse來指定。

這就是你需要的嗎?

+0

謝謝兄弟! – Aziz

0

例CreateView的:

views.py

class FeedbackSendForm(CreateView): 
     model = Feedback 
     fields = ['title','text','user_name','user_lastname','email',] 
     template_name = 'feedback.html' 
     form_class = form_name 

     def form_valid(self, form): 
      """ 
      If the form is valid, redirect to the supplied URL. 
      """ 
      return HttpResponseRedirect(self.get_success_url()) 
      """ 
      define `get_success_url' to your model or use `get_absolute_url` instead. 

希望這有助於。

更多信息:https://ccbv.co.uk/projects/Django/1.5/django.views.generic.edit/CreateView/

相關問題