Using Django Forms in Charcha

Urvi Sharma

03 Jun 2017

Using Django Forms in Charcha

In this blog, we will be going through the implementation of Django Forms. This post is inspired from the Django form usage in Charcha Discussion Forum. You can find the full code for the Charcha forum here.

While creating interactive websites, one of the widely used way to submit data to the server will be forms. For such a use case, Django provides us the form library. It helps us to design forms and also lets us decide how they look in our template. After submission, it also helps us to process it like storing data in the database. A Django Form can be defined either from scratch or you can simply create a ModelForm, which can be returned from HTTP methods, which will therein save the data in the model’s fields. Based on our requirements we can choose from either of the aforementioned ones.

Django Forms provides us with various features such as facilitating validation on the browser side and also after submitting the data, generates proper error messages and binds template objects and data models. And after submitting the form, we can directly save it to the database in the required format.

Let us assume we have a requirement to create the Django models of a discussion platform like Charcha. In this blog post, we will go through the process of designing such a model which is both conforming to our requirements as well as efficient. In this blog, we will see the process to define and use the Django forms. Let us discuss Charcha, an interactive website, in which we are using Django forms:

We are also using the Django auth user forms.

Defining forms in Django View

We first need to define the Django forms in our application. For this, we need to import the Django forms. Here, in Charcha, we are using the Django auth forms and Django forms.

from django import forms
from django.contrib.auth.forms import UserCreationForm
class SampleCommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['text']
        labels = {
            'text': 'Your Comment',
        }
        help_texts = {
            'text': 'Markdown Supported',
        }

In the above-given example, we are using the forms.ModelForm coupled with Comment model along with label as Comment and we have also provided the help text. We have added a user-friendly label to the field which will be shown in the '<label>' tag when rendered in the template. We can also define some additional things like validations, like max length and required etc. These validations put a validation in HTML '<input>' tag which will enable client-side validation in the browser. They also validate the data on the server after it’s received from the form. Form has an 'is_valid()' method which checks all the validations throughout all the fields in the form. On this method call, if all fields are verified it will return true and provide all the form’s data in the 'cleaned_data' attribute.

def clean(self):
    cleaned_data = super(SomeFormData, self).clean()
    url = cleaned_data.get("url")
    text = cleaned_data.get("text")
    if not (url or text):
        raise forms.ValidationError(
            "URL and Text are both empty. Please enter at least one of them."
        )
    return cleaned_data

Linking Views and Template

Now to link the form with the view, we will use a link sample-url in our case. We import url from Django urls and function from the view which we want to use: The urls will be in the format: url(regex, view, kwargs=None, name=None) Here regex is the url which will link the template and view. view is the Django function which is the result of as_view() for the class-based views. Using kwargs we can send some additional arguments to the view.

url(regex, view, kwargs=None, name=None)
from django.conf.urls import url
from . import views
urlpatterns = [
	url(r'^sample-url/$', views.SampleFunction.as_view(), name="sample_function"),
]

Defining HTML Template

For a template, depending on the user who is going to view, we will use the url to define which url and view we are going to use. We will be able to do this by using <form></form> tag with attributes as some-url and methods as GET or POST depending on user requirements. Here GET or POST are the HTTP verbs. We will use GET for not so safe search, like when we want to implement the web search form or the data which is not so important even when a user views it on url. As urls can easily be edited, shared or can be opened directly. On the other hand we use POST, which does not allow user to see the data in url. It can also support larger payload as compared to the GET. It also provides us CSRF (Cross Site Request Forgery) protection, provides us more control over URL and access. That makes POST method far safer than GET.

We also need to define the submit input type field for the submission of the form. Between these, we have our form fields which user needs to fill in the given form. All the form’s fields and their attributes like validations and type of field will be unbundled into HTML from {{form}} , that we are using in the template, by Django’s template.

{% csrf_token %} {{ form|bootstrap }}

 

Summary

In the above post, we learned about usage and process of using Django forms. Django provides us a great number of prebuilt tools and libraries to build a form to get input from the user and then process and respond to the input, which makes the handling of user input very easy.


Have a question?

Need Technology advice?

Connect

+1 669 253 9011

contact@hashedin.com

facebook twitter linkedIn youtube