berkeebal
berkeebal

Reputation: 493

Redirect a form to same URL in Django

this is my first question so if i had made any mistakes excuse me. I have a template like below :enter image description here

I have and Object model and for that model i am making queries and returning to template. What i am trying to is when user select one of the objects and submits, I would like to redirect to the same page so based on the object that has been choosen i will have different result for the queries because this Object model related with different models. I am trying to do this in TemplateView. So far I have override the get_context_data() method and return all the Object records for select form and I can return queries results but for just one record which I specify in view. But I couldn't find a way to submit the form and depending on that record return the queries and redirect it to the same url. I am not sure the TemplateView is the best way to do it.

Because of the privacy policy of my company i can not share any files for code. I just need a guidance or a clue about my view.

Any help will be so appreciated.

Upvotes: 0

Views: 464

Answers (1)

Beikeni
Beikeni

Reputation: 900

<form method="GET">

Use the GET method on your form and any information saved in the form will appear as URL parameters http://url.com?object_id=1&color=blue

Then in your view overwrite your get method, and get the parameters off the URL:

class MyView(TemplateView):
    template_name = 'my_template.html'
    
    def get(self,request):
        context = {}
        if request.GET.get('object_id'):  # Always make sure it exists
            context['object_id'] = request.GET.get('object_id')  # Add to context
        return render(request, self.template_name, context)

I think you can access the request from the get_context_data method as well, by simply writing self.request.GET.get('object_id')

Just in case you didn't know you can access the POST data in the same way : request.POST.get('field_name')

A couple things to note when making this type of page

  1. The parameters and their content will be visible on the url bar
  2. To leave the page you will have to add an additional link that leads the user to a different page without sending any request. This is because if it sends a GET request it'll end up in the same page always. And you cannot (as far as i know) determine what type of request the form is going to send based on which button is pushed by the user. The request type is decided on the form html markup.

Upvotes: 1

Related Questions