Skip to content Skip to sidebar Skip to footer

Django : Html Form Action Directing To View (or Url?) With 2 Arguments

Started learning django about a week ago and ran into a wall. Would really appreciate any enlightenment... models.py class data(models.Model): course = models.CharField(max_len

Solution 1:

You are trying to use the reverse resolution of urls in Django.

In your html file correct form action url to the following and method should be POST:

<formaction={%url 'process' %}  method="POST">

In case you are trying to pass parameters along then use this:

<formaction={%url 'process' request.user.id4 %}  method="POST">

Reference: https://docs.djangoproject.com/en/1.10/topics/http/urls/

Solution 2:

Yes i'm late but it can help others for better understanding how Django processes the request.

Django 3.0 pattern

How Django processes the request

Basic :

  1. First Django check the matching URL.
  2. If URL is matched then calling the defined view to process the request. (Success)
  3. If URL not matched/found the Django invokes error Page Not Found

In detail reading :

Official Django Documentations How Django processes a request


These are your URL patterns :

urlpatterns = [ path('profile/edit/<int:pk>/',views.editprofile, name='editprofile'),]

Third argument in urlpatterns is for if you want to change the url pattern from current to this :

urlpatterns = [ url('profile/edit/user/id/<int:pk>',views.editprofile, name = 'editprofile'),]

You don't need to redefine url pattern in all Templates where you using url name.

For Example :

This is my template profile.html where i used the url name instead of hard coded url.

<aclass="item"href="{% url 'editprofile' user.id %}" >Edit profile </a>

Solution of your problem :

.html

Only use url name instead of hard coded url in your templates and pass arguments.

<formaction={%processno_of_arguments  %}  method="POST">

views.py

Here you can process your request

defprocess(request,no_of_arguments):

Become good django developer

You can also use Django ModelForms for your model. Using model forms or simple form you can do multiple things

  • Modular approach
  • Write server side validation in related form instead of doing in views.py
  • Readable code - Clean code

Post a Comment for "Django : Html Form Action Directing To View (or Url?) With 2 Arguments"