Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8377925
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T15:47:54+00:00 2026-06-09T15:47:54+00:00

I’m struggling to get my head round django forms.. I’ve been reading various documentation

  • 0

I’m struggling to get my head round django forms.. I’ve been reading various documentation but just can’t quite grasp the concepts. I have got to grips with models, views and templates. What I am trying to do is to create a form with various fields composing of dropdown lists and checkboxes which are populated by values in a database.

I have a working app called vms. Using the models.py I have a built a simple schema that holds size and type. Size consists of ‘small’, ‘medium’ & ‘large’. Type is ‘windows’ & ‘linux’. Using the admin site, I can add an extra size, for example ‘Extra Large’.

What I would like to do is create a form that has a drop down list of the vm sizes. If an extra size gets added via the admin site, I would like that size to appear in the drop down list.

I would submit my attempts at the code, but actually am struggling with the concepts. Can anyone help guide me in how to accomplish the above?

Thanks
Oli

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T15:47:55+00:00Added an answer on June 9, 2026 at 3:47 pm

    Forms are just a tool to simplify and speed-up (the development of) the process of fetching POST data from the request. A manual way would be to do request.POST.get('somefield') for all the fields there are in some HTML form. But Django can do better than that…

    In its essence, a Form class holds a number of Fields and performs these tasks:

    1. display HTML inputs,
    2. collect and validate data when user submits it,
    3. if fields don’t validate, return the values along with error messages to HTML,
    4. if all fields validate, provide form.cleaned_data dictionary as a convenient way to access these values in view.

    With these values, I could then manually create a new instance of a MyModel and save it. Of course, I would have to define a Field in the Form for every Field in MyModel model.

    This means that, basically, I could do something like this:
    (forgive me for not testing this code, so I can’t vouch that it’s 100% correct)

    models.py:
    
        class MyModel(models.Model):
            field1 = models.CharField(max_length=40, blank=False, null=False)
            field2 = models.CharField(max_length=60, blank=True, null=True)
    
    forms.py:
    
        class FormForMyModel(forms.Form):
            form_field1 = forms.CharField(max_length=40, required=True)
            form_field2 = forms.CharField(max_length=60, required=False)
    
    views.py:
    
        def create_a_my_model(request):
            if request.method == 'POST':
                form = FormForMyModel(request.POST)
                if form.is_valid():
                    my_model = MyModel()
                    my_model.field1 = form.cleaned_data.get('form_field1', 'default1')
                    my_model.field2 = form.cleaned_data.get('form_field2', 'default2')
                    my_model.save()
            else:        
                form = FormForMyModel()
            context_data = {'form': form}
            return HttpResponse('templtate.html', context_data)
    

    (this could be written with a few lines of code less, but it’s meant to be as clear as possible)

    Notice there are no relation between model Fields and form Fields! We have to manually assign values to MyModel instance when creating it.

    The above example outlines generic form workflow. It is often needed in complex situations, but not in such a simple one as is this example.

    For this example (and a LOT of real-world examples), Django can do better than that…

    You can notice two annoying issues in the above example:

    1. I have to define Fields on MyModel and Fields on FormForMyModel separately. However, there is a lot of similarity between those two groups (types) of Fields, so that’s kind of duplicate work. The similarity grows when adding labels, validators, etc.
    2. creating of MyModel instance is a bit silly, having to assign all those values manually.

    This is where a ModelForm comes in.

    These act basically just like a regular form (actually, they are extended from regular forms), but they can save me some of the work (the two issues I just outlined, of course 🙂 ).

    So back to the two issues:

    1. Instead of defining a form Field for each model Field, I simply define model = MyModel in the the Meta class. This instructs the Form to automatically generate form Fields from model Fields.

    2. Model forms have save method available. This can be used to create instance of model in one line in the view, instead of manually assigning field-by-field.

    So, lets make the example above with a ModelForm:

    models.py:
    
        class MyModel(models.Model):
            field1 = models.CharField(max_length=40, blank=False, null=False)
            field2 = models.CharField(max_length=60, blank=True, null=True)
    
    forms.py:
    
        class MyModelForm(forms.ModelForm):  # extending ModelForm, not Form as before
            class Meta:
                model = MyModel
    
    views.py:
    
        def create_a_my_model(request):
            if request.method == 'POST':
                form = MyModelForm(request.POST)
                if form.is_valid():
                    # save the model to database, directly from the form:
                    my_model = form.save()  # reference to my_model is often not needed at all, a simple form.save() is ok
                    # alternatively:
                    # my_model = form.save(commit=False)  # create model, but don't save to database
                    # my.model.something = whatever  # if I need to do something before saving it
                    # my.model.save()
            else:        
                form = MyModelForm()
            context_data = {'form': form}
            return HttpResponse('templtate.html', context_data)
    

    Hope this clears up the usage of Django forms a bit.

    Just one more note – it is perfectly ok to define form Fields on a ModelForm. These will not be used in form.save() but can still be access with form.cleaned_data just as in a regular Form.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a jquery bug and I've been looking for hours now, I can't
I need to clean up various Word 'smart' characters in user input, including but
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
Seemingly simple, but I cannot find anything relevant on the web. What is the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.