Using Django's 'get_absolute_url' (return the user to the same page after form submission)

1.9k views Asked by At

I am learning Django and have one question.

I have done a feedback form and I need to redirect the user to the same page after the feedback form confirmation. Below is the code:

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>

How can I fix this?

3

There are 3 answers

0
cezar On BEST ANSWER

If you want to override the get_absolute_url for your model, the following code can help you:

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')

The absolute URL for any Feedback object will be the view FeedbackSendForm. That is specified by passing the view name feedback to reverse.

0
Emil George James On

Example 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.

More information: class CreateView

0
krishan kansal On

If we define get_absolute_url in the model class then, while posting the form, we can leave the action tag as empty like this:

<form action="" method="post">

In this case, it now searches for the get_absolute_url in our model class defined as below:

def get_absolute_url(self):
    return reverse("post_detail", kwargs={"pk": self.pk})

After updating or adding data in the model, our page is redirected to the URL named as post_detail.