Django get_absolute_url(Return 用户在提交表单后到同一页面)

Django get_absolute_url (Return user to the same page after form submission)

学习 Django。我有一个问题。 我已经完成了反馈表,我需要在确认反馈表后将用户重定向到同一页面。下面是代码:

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>

有什么想法吗?请帮忙。 提前谢谢你

示例创建视图:

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/

如果您想为您的模型覆盖 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.

来指定的

这是你需要的吗?