Would someone like to attempt a succinct explanation of what a form_factory, or a modelform_factory is in relation to a form / modelform?
Why use a factory?
Is there an official technical definition for a
factory method?
The modelform_factory method is a method that returns a ModelForm class. Here's an example of why it's useful.
If you have a simple view that uses a form for a single model, then there is no need for a factory, you can simply define the form:
class ProductForm(forms.ModelForm):
class Meta:
model = Product
def add_product_view(request):
form = ProductForm()
...
However, if your view needs to handle multiple models, then you might not want to have to define a form class for every model. The modelform_factory lets you create the form class dynamically.
apps.get_model('newapp', 'mymodel')
def add_model_view(request, model_name):
Model = apps.get_model('myapp', model_name)
Form = modelform_factory(Model)
The Django admin uses modelform_factory to generate model form classes dynamically. This means you don't need to define a model form every time you register a model in the Django admin.
Related
I found this
How to properly overwrite clean() method
and this
Can `clean` and `clean_fieldname` methods be used together in Django ModelForm?
but it seems to work differently if one is using the generic class mixins ModelFormMixin.
My class is also derived from ProcessFormView.
Is def form_valid(self, form): the only point where I can overwrite the form handling process?
You are confusing views and forms. A CreateView for example makes use of a ModelForm to create an object. But instead of letting the view construct the ModelForm, you can specify such form yourself and then pass this as form_class to the view.
For example say you have a Category model with a name field, and you wish to validate that the name of the Category is all written in lowercase, you can define a ModelForm to do that:
from django import forms
from django.core.exceptions import ValidationError
class CategoryForm(forms.ModelForm):
def clean_name(self):
data = self.cleaned_data['recipients']
if not data.islower():
raise ValidationError('The name of the category should be written in lowercase')
return data
class Meta:
model = Category
fields = ['name']
now we can plug in that ModelForm as form for our CategoryCreateView:
from django.views.generic import CreateView
class CategoryCreateView(CreateView):
model = Category
form_class = CategoryForm
The validation thus should be done in the ModelForm, and you can then use that form in your CreateView, UpdateView, etc.
my views :
from .models import Settings, SocialMediaSetting
class UpdateSocialMediaSetting(LoginRequiredMixin, UpdateView):
model = SocialMediaSetting
fields = '__all__'
template_name = "staff/settings/social-media-settings-update.html"
class UpdateSettings(LoginRequiredMixin, UpdateView):
model = Settings
fields = '__all__'
template_name = "staff/settings/settings-update.html"
two different class in models without any relation, I want show both in one html and one form both models has just one object
you'll need to ditch the UpdateView, but this way won't take long to implement
Use a TemplateView (at least you won't have to change your other mixin)
Create two ModelForms
override the get_context_data() to pass the forms to the template
when forms are submitted, override the post() method to save them yourself
mchesler613 wrote an awesome article explaining how to do this here.
(make sure to give him a star)
In DRF how can I pass for example a boolean which isn't in my model from ModelViewSet so it can be used in a overridden save method for some logic? I know with a model instance you can just assign it, but I'm unsure if this is possible from ModelViewSet or goes against the general flow of DRF.
in serializer which includes this model, add one serializer field and add inside class Meta.
bool_field = serializer.BoolField()
class Meta:
model = MyModel
fields=['bool_field','MyModel_fields1','mymodelField2']
Is there a simple way to replace a form field in Django with another form? Specifically, I have a one-to-one relationship between two models, and it would be great if I could define a field to actually be defined as another form, something like this:
class FirstModelForm(forms.ModelForm):
class Meta:
model = FirstModel
class SecondModelForm(forms.ModelForm):
second = forms.InnerForm(form=FirstModelForm)
class Meta:
model = SecondModel
Any ideas? Or should I write it myself and submit to Django codebase? ;-)
I need a model field composed of a numeric string for a Django app I'm working on and since one doesn't exist I need to roll my own. Now I understand how "get_db_prep_value" and such work, and how to extend the Model itself (the django documentation on custom model fields is an invaluable resource.), but for the life of me I can't seem to figure out how to make the admin interface error properly based on input constraints.
How do I make the associated form field in the admin error on incorrect input?
Have a look at the Form and field validation section in the Django documentation, maybe that's what you're looking for?
You would have to make a new type of form field for your custom model field.
All you need to do is define a custom modelform which uses your new field, and then tell the admin to use that form to edit your models.
class MyModelForm(forms.ModelForm):
myfield = MyCustomField()
class Meta:
model = MyModel
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm