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


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

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

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

class FeedbackSendForm(CreateView):
      model = Feedback
      fields = [
      template_name = 'feedback.html'


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

Any ideas? Please help.
Thank you in advance

Asked By: Dustin



Example Createview :

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.

Hope this helps.

more info :

Answered By: Emil George James

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.

Is that what you need?

Answered By: cezar

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

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

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

After Updating or Adding data in model our page is redirected to the url named as "post_detail".

Answered By: krishan kansal
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.