Could anyone explain to me similarities and differences of Django's forms.Form & forms.ModelForm?
Forms created from forms.Form are manually configured by you. You're better off using these for forms that do not directly interact with models. For example a contact form, or a newsletter subscription form, where you might not necessarily be interacting with the database.
Where as a form created from forms.ModelForm will be automatically created and then can later be tweaked by you. The best examples really are from the superb documentation provided on the Django website.
forms.Form:
Documentation: Form objects
Example of a normal form created with forms.Form:
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
forms.ModelForm:
Documentation: Creating forms from models
Straight from the docs:
If your form is going to be used to
directly add or edit a Django model,
you can use a ModelForm to avoid
duplicating your model description.
Example of a model form created with forms.Modelform:
from django.forms import ModelForm
from . import models
# Create the form class.
class ArticleForm(ModelForm):
class Meta:
model = models.Article
This form automatically has all the same field types as the Article model it was created from.
The similarities are that they both generate sets of form inputs using widgets, and both validate data sent by the browser. The differences are that ModelForm gets its field definition from a specified model class, and also has methods that deal with saving of the underlying model to the database.
Here's how I'm extending the builtin UserCreationForm myapp/forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm
class RegisterForm(UserCreationForm):
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
email = forms.CharField(max_length=75)
class Meta(UserCreationForm.Meta):
fields = ('username','first_name','last_name', 'email')
The difference is simple, ModelForm serves to create the form of a Model.
meaning that Model is designed to create kind of schema of your table where you will save data from form submission and ModelForm simply creates a form of the model (from the schema of the table)
# This creates a form from model Article
class ArticleForm(ModelForm):
class Meta:
model = Article
fields = ['pub_date', 'headline', 'content', 'reporter']
Form is a common form that is unrelated to your database (model ).
# A simple form to display Subject and Message field
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea)
To say in other words,
If you have a model in your app and you want to create a Form to enter data in that model (and by it to a db) use forms.ModelForm
If you simple want to create a form using django use form.Form
But you can also use this together:
from django import forms
# A simple form to display Subject and Message field
class ContactForm(forms.ModelForm):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea)
class Meta:
model = Contact #when you have this model
fields = [
'subject',
'message',
]
Related
Could anyone explain to me similarities and differences of Django's forms.Form & forms.ModelForm?
Forms created from forms.Form are manually configured by you. You're better off using these for forms that do not directly interact with models. For example a contact form, or a newsletter subscription form, where you might not necessarily be interacting with the database.
Where as a form created from forms.ModelForm will be automatically created and then can later be tweaked by you. The best examples really are from the superb documentation provided on the Django website.
forms.Form:
Documentation: Form objects
Example of a normal form created with forms.Form:
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
forms.ModelForm:
Documentation: Creating forms from models
Straight from the docs:
If your form is going to be used to
directly add or edit a Django model,
you can use a ModelForm to avoid
duplicating your model description.
Example of a model form created with forms.Modelform:
from django.forms import ModelForm
from . import models
# Create the form class.
class ArticleForm(ModelForm):
class Meta:
model = models.Article
This form automatically has all the same field types as the Article model it was created from.
The similarities are that they both generate sets of form inputs using widgets, and both validate data sent by the browser. The differences are that ModelForm gets its field definition from a specified model class, and also has methods that deal with saving of the underlying model to the database.
Here's how I'm extending the builtin UserCreationForm myapp/forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm
class RegisterForm(UserCreationForm):
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
email = forms.CharField(max_length=75)
class Meta(UserCreationForm.Meta):
fields = ('username','first_name','last_name', 'email')
The difference is simple, ModelForm serves to create the form of a Model.
meaning that Model is designed to create kind of schema of your table where you will save data from form submission and ModelForm simply creates a form of the model (from the schema of the table)
# This creates a form from model Article
class ArticleForm(ModelForm):
class Meta:
model = Article
fields = ['pub_date', 'headline', 'content', 'reporter']
Form is a common form that is unrelated to your database (model ).
# A simple form to display Subject and Message field
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea)
To say in other words,
If you have a model in your app and you want to create a Form to enter data in that model (and by it to a db) use forms.ModelForm
If you simple want to create a form using django use form.Form
But you can also use this together:
from django import forms
# A simple form to display Subject and Message field
class ContactForm(forms.ModelForm):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea)
class Meta:
model = Contact #when you have this model
fields = [
'subject',
'message',
]
I have two objects that are connected together by a ForeignKey.
class Question(models.Model):
text = models.Charfield()
class AnswerOption(models.Model):
text = models.Charfield()
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="options")
When Question is created in the admin interface I'm using a Inline form for AnswerOptions so that they can be created at the same time. I'd like to perform some validation on the Question and it needs access to the new AnswerOptions to make the decision.
I've added a clean method to Question but the options property is empty.
What is the correct way to validate Question?
[EDIT]
Made it clear that Question needs access to the AnswerOptions to be able to validate everything.
[EDIT]
Added explicit reference to using an InlineForm for AnswerOptions in the admin interface.
I'd do this through a Django form, which have a more robust interface for
validation. The clean method on your form is the place for this type
of validation.
# forms.py
from django import forms
from .models import Question
class QuestionForm(forms.Form):
text = models.Charfield()
class Meta:
model = Question
def clean(self):
options = self.cleaned_data['options']
if not option.are_ok:
raise forms.ValidationError
# admin.py
from django import admin
from .forms import QuestionForm
class QuestionAdmin(admin.ModelAdmin):
form = QuestionForm
...
From the docs:
The form subclass’s clean() method can perform validation that requires access to multiple form fields. This is where you might put in checks such as “if field A is supplied, field B must contain a valid email address”. This method can return a completely different dictionary if it wishes, which will be used as the cleaned_data.
This is what I've discovered:
When creating Inline forms in the admin interface Django creates a Formset to handle the multiple forms. (The example here is the same as my use case)
Formsets have a clean() method like other forms and they have a forms property to access the child forms.
Just like normal forms they have an instance property that refers to the 'base' class and the individual forms have an instance property that gets you a instance of the newly submitted data.
Putting it all together:
# models.py
class Question(models.Model):
text = models.Charfield()
class AnswerOption(models.Model):
text = models.Charfield()
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="options")
# admin.py
from django.contrib import admin
from django.forms.models import BaseInlineFormSet
class AnswerOptionFormset(BaseInlineFormset):
def clean(self):
super().clean() # See note in docs about calling this to check unique constraints
#self.instance -> Question, with all the newly submitted, and validated, data.
#self.forms -> iterator over all the submitted AnswerOption forms
#for f in self.forms:
# f.instance -> instance of AnswerOption containing the new validated data
#Note: self.instance.options will refer to the previous AnswerOptions
#raise ValidationError for anything that is wrong.
#It is also possible to modify the data in self.instance or form.instance instead.
class AnswerOptionInline(admin.TabularInline):
formset = AnswerOptionFormset # note formset on AnswerOption NOT QuestionAdmin
class QuestionAdmin(admin.ModelAdmin):
inlines = [AnswerOptionInline]
I'd like to create a formView(based on Django build-in CreateView class) to allow creating new user records, which are from two different models.
Both models sounds like one is user model and another is user profile model.
I wish one form with one submit button to approach it, but I found only one form_class could be assigned in one createView class in Django.
So I wonder is that possible to use CreateView to approach it? if not, any solution recommended? Appreciated if any assistance from you.
So you have two models for user and user_profile. One user one profile
so:
Try this:
#models.py
class User_profile(models.Model):
User= models.Foreignkey('User')
#add more user data
#forms.py
class UserProfileForm(ModelForm):
model = User_profile
fields = ['User']
#views.py
class SomeView(CreateView):
form_class = UserProfileForm()
Actually, I find the solution: use the User model and add profile's field in the same form as below
class userCreateForm:
email = forms.EmailField(label=_("E-mail"))
contact_number = forms.CharField(label=_("Contact"))
contact_address = forms.CharField(label=_("Address"))
class Meta:
model = User
fields = (UsernameField(), "email", "contact_number", "contact_address")
I am working through how to use Django's forms (https://docs.djangoproject.com/en/1.11/topics/forms/#more-on-fields) and I can't see a way to generate a form structure that is based on a defined Model. In Symfony, I remember I was able to get my form to automatically include all parameters of myModel (for example) even if any new attributes were later added to the model.
For example:
class myModel(models.Model):
name = models.CharField(max_length=50)
created=models.DateTimeField(null=False)
modified=models.DateTimeField(null=True)
myParameter= models.IntegerField(default=None)
// ... plus many more parameters
Rather than having to manually type corresponding rows into my class myModelForm(forms.Form):, I'm looking/hoping for a 'catch all'.
from django.forms import ModelForm
class myModelForm(ModelForm):
class Meta:
model = myModel
fields = '__all__'
More details selecting-the-fields-to-use
Could anyone explain to me similarities and differences of Django's forms.Form & forms.ModelForm?
Forms created from forms.Form are manually configured by you. You're better off using these for forms that do not directly interact with models. For example a contact form, or a newsletter subscription form, where you might not necessarily be interacting with the database.
Where as a form created from forms.ModelForm will be automatically created and then can later be tweaked by you. The best examples really are from the superb documentation provided on the Django website.
forms.Form:
Documentation: Form objects
Example of a normal form created with forms.Form:
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
forms.ModelForm:
Documentation: Creating forms from models
Straight from the docs:
If your form is going to be used to
directly add or edit a Django model,
you can use a ModelForm to avoid
duplicating your model description.
Example of a model form created with forms.Modelform:
from django.forms import ModelForm
from . import models
# Create the form class.
class ArticleForm(ModelForm):
class Meta:
model = models.Article
This form automatically has all the same field types as the Article model it was created from.
The similarities are that they both generate sets of form inputs using widgets, and both validate data sent by the browser. The differences are that ModelForm gets its field definition from a specified model class, and also has methods that deal with saving of the underlying model to the database.
Here's how I'm extending the builtin UserCreationForm myapp/forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm
class RegisterForm(UserCreationForm):
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
email = forms.CharField(max_length=75)
class Meta(UserCreationForm.Meta):
fields = ('username','first_name','last_name', 'email')
The difference is simple, ModelForm serves to create the form of a Model.
meaning that Model is designed to create kind of schema of your table where you will save data from form submission and ModelForm simply creates a form of the model (from the schema of the table)
# This creates a form from model Article
class ArticleForm(ModelForm):
class Meta:
model = Article
fields = ['pub_date', 'headline', 'content', 'reporter']
Form is a common form that is unrelated to your database (model ).
# A simple form to display Subject and Message field
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea)
To say in other words,
If you have a model in your app and you want to create a Form to enter data in that model (and by it to a db) use forms.ModelForm
If you simple want to create a form using django use form.Form
But you can also use this together:
from django import forms
# A simple form to display Subject and Message field
class ContactForm(forms.ModelForm):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea)
class Meta:
model = Contact #when you have this model
fields = [
'subject',
'message',
]