[Answered ]-Django poplulate html form

2πŸ‘

βœ…

If you do not wish to use django.forms, but get data from a model and display it into a html form, you could do something like this:

views.py

from django.shortcuts import render_to_response, redirect 
from myApp.models import MyModel

def editForm(request, model_pk):
    model = MyModel.objects.get(pk=model_pk)
    return render_to_response('formUpdate.html',{ 'model' : model })

def updateForm(request, model_pk):
    model = MyModel.objects.get(pk=model_pk)
    model.firstname = request.POST['firstname']
    model.lastname = request.POST['lastname']
    model.save()
    return redirect('home', message='your name has been updated')

template – formUpdate.html

{% extends "base.html" %}

{% block content %}
<form action="/updateForm/{{ model.id }}/" method="post">
First name: <input type="text" name="firstname" value="{{ model.firstname }}" /><br />
Last name: <input type="text" name="lastname" value="{{ model.lastname }}" /><br />
<input type="submit" value="submit" />
</form>
{% end block %}

models.py

from django.db import models

class MyModel(models.Model):
    firstname = models.CharField(max_length=20)
    lastname = models.CharField(max_length=20)

urls.py

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^$', 'views.home', name="home"),
    (r'^editForm/(?P<model_pk>\d+)/$', 'views.editForm'),
    (r'^updateForm/(?P<model_pk>\d+)/$', 'views.updateForm'),
)

This is very similar to how forms are processed in PHP or similar, the model is passed into the template where the existing values are rendered. The id or pk (primary key) of the model is passed to the view via the URL and then updated values then returned to the storing view in the POST data where they can be retrieved and the updated values stored in the database.

One of the beauties of Django is how it balances speed of development with plugability – pretty much any of it’s parts can be replaced or altered.

Having said this, is there a reason why you don’t want to use django.forms? To my understanding a form simply performs most of the hard work in the example above for you, this is what django.forms are for. They also have other features, to help prevent malicious access of your web app, for example, OOTB. It is fairly easy to create ajax helper methods to retrieve and update them also.

0πŸ‘

You can do that as you would create a normal form in html. Just be careful to place the {% csrf_token %}. And the name of the input in the form, as they will be used in the view.

Eg:

<form method="post" action="#the url for the view">
{% csrf_token %}
...
...
<!-- fields that you want Eg: -->
<label for="username">User name:</label>
<input type="text" name="username" id="username" />
...
...
<input type="submit" value="Submit" />
</form>

Hope this helped.

πŸ‘€Aamu

Leave a comment