user3489820
user3489820

Reputation: 1519

Django - guidance needed

I am developing a web-site using Django/Python. I am quite new to this technology and I want to do the web-site in a right way. So here is my problem:

Imagine, that there is a Product entity and product view to display the Product info. I use (product_view in my views.py ).

There is also Message entity and the Product might have multiple of them. In Product view page ( I use "product_view" action in my views.py ) I also query for the messages and display them.

Now, there should be a form to submit a new message ( in product view page ).

Question #1: what action name should form have ( Django way, I do understand I might assign whatever action I want )?

Option #1: it might be the same action "product_view". In product_view logic I might check for the HTTP method ( get or post ) and handle form submit or just get request. But it feels a bit controversial for me to submit a message to the "product_view" action.

Option #2: create an action named "product_view_message_save". ( I don't want to create just "message_save", because there might be multiple ways to submit a message ). So I handle the logic there and then I make a redirect to product_view. Now the fun part is: if the form is invalid, I try to put this form to the session, make the redirect to the "product_view", get the form there and display an error near the message field. However, the form in Django is not serializable. I can find a workaround, but it just doesn't feel right again.

What would you say? Any help/advice would be highly appreciated!

Best Regards, Maksim

Upvotes: 0

Views: 40

Answers (1)

cgonchar
cgonchar

Reputation: 21

You could use either option.

Option #1: In the post method (if using Class-based-views, otherwise check for "post" as the request type), just instantiate the form with MessageForm(request.POST), and then check the form's is_valid() method. If the form is valid, save the Message object and redirect back to the same view using HttpResponseRedirect within the if form.is_valid(): code block.

If you're checking for the related Messages objects in your template, the newly created message should be there.

Option #2: Very similar to Option #1, except if the form is not valid, re-render the same template that is used for the product_view with the non-valid form instance included in the template context.

Upvotes: 1

Related Questions