Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I associate input to a Form with a Model in Django?
    text
    copied!<p>In Django, how do I associate a Form with a Model so that data entered into the form are inserted into the database table associated with the Model? How do I save that user input to that database table?</p> <p>For example:</p> <pre><code>class PhoneNumber(models.Model): FirstName = models.CharField(max_length=30) LastName = models.CharField(max_length=30) PhoneNumber = models.CharField(max_length=20) class PhoneNumber(forms.Form): FirstName = forms.CharField(max_length=30) LastName = forms.CharField(max_length=30) PhoneNumber = forms.CharField(max_length=20) </code></pre> <p>I know there is a class for creating a form from the the model, but even there I'm unclear on how the data actually gets to the database. And I'd like to understand the inner workings before I move on to the time-savers. If there is a simple example of how this works in the docs, I've missed it.</p> <p>Thanks.</p> <p>UPDATED: To be clear -- I do know about the ModelForm tool, I'm trying to figure out how to do this without that -- in part so I can better understand what it's doing in the first place.</p> <p>ANSWERED:</p> <p>With the help of the anwers, I arrived at this solution:</p> <p>Form definition:</p> <pre><code>class ThisForm(forms.Form) [various Field assignments] model = ThisModel() </code></pre> <p>Code in views to save entered data to database:</p> <pre><code>if request_method == 'POST': form = ThisForm(request.POST) if form.is_valid(): for key, value in form.cleaned_data.items(): setattr(form.model, key, value) form.model.save(form.model) </code></pre> <p>After this the data entered in the browser form was in the database table.</p> <p>Note that the call of the model's save() method required passage of the model itself as an argument. I have no idea why.</p> <p>CAVEAT: I'm a newbie. This succeeded in getting data from a browser to a database table, but God only knows what I've neglected or missed or outright broken along the way. ModelForm definitely seems like a much cleaner solution.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload