Django design patterns - Forms for Create and Update a Model - django

Suppose I want to create and update a model. What fields are displayed and the type of validation depends on the action (create or update). But they still share a lot of the same validation and functality. Is there a clean way to have a ModelForm handle this (besides just if instance exists everywhere) or should I just create two different model forms?

Two possibilities spring to mind. You could set an attribute in the form's __init__ method, either based on a parameter you explicitly pass in, or based on whether self.instance exists and has a non-None pk:
class MyModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
# either:
self.edit = kwargs.pop('edit', False)
# or:
self.edit = hasattr(self, instance) and self.instance.pk is not None
super(MyModelForm, self).__init__(*args, **kwargs)
# now modify self.fields dependent on the value of self.edit
The other option is to subclass your modelform - keep the joint functionality in the base class, then the specific create or update functionality in the subclasses.

Related

How to use the serializer in part

I have several viewsets, several endpoints in them use one serializer. One endpoint does not even have a Meta class,
It performs a certain action and uses the same serializer in the method to_representation. In this serializer I use the methodfield like this:
some_field = serializers.SerializerMethodField()
def get_some_field(self, obj):
return bool(obj.something_attr)
something_attr I get in viewset in
queryset =MyModel.objects.annotate(something_attr=(...))
In others viewsets there is no such field, so they use other queriesets. Can I work around this problem without creating a bunch of additional serializers. My thanks!
As per my understanding you're trying to use a single serializer class with different views - but each view need different fields, right?
class DynamicFieldSerializerMixin:
def __init__(self, *args, **kwargs):
fields = kwargs.pop('fields', None)
super().__init__(*args, **kwargs)
if fields is not None:
# Drop any fields that are not specified in the `fields` argument.
allowed = set(fields)
existing = set(self.fields)
for field_name in existing - allowed:
self.fields.pop(field_name)
You can use this mixin to define fields dynamically for each view for a single serializer class. Just pass fields=[] keyword argument with list of field names.

Setting attributes in constructor for Django model

I have an abstract BaseModel from which many models will inherit the behavior to initialize attributes values from the constructor:
class BaseModel(models.Model):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for key in kwargs:
setattr(self, key, kwargs[key])
class Meta:
abstract = True
Then, I try to initialize one of its specializations like this:
BaseModelSon(attr1=val1, attr2=val2, ...)
Is this a good practice? Do you know any other way to achieve this dynamic initialization for Django models?
You can already create regular Django model instances with
MyModel(field1='value1', field2='value2')
so I don't think your __init__ method is necessary.
Also you'll probably find useful Model.objects.create() method for new Django models instances creation:
instance = MyModel.objects.create(field1='value1', field2='value2'...)
If there are some auto-generated fields (for example, id or some date with auto_now_add=True option) — you'll get their values in instance if you have used Model.objects.create().

Using dynamic Choice Field in Django

I have a choiceField in order to create a select field with some options. Something like this:
forms.py
class NewForm(forms.Form):
title = forms.CharField(max_length=69)
parent = forms.ChoiceField(choices = CHOICE)
But I want to be able to create the options without having a predefined tuple (which is required by ChoiceField). Basically, I need to have access to request.user to fill some options tags according to each user, but I don't know if there is any way to use request in classes of forms.Form.
An alternative would be to prepopulate the instance of NewForm via:
views.py
form = NewForm(initial={'choices': my_actual_choices})
but I have to add a dummy CHOICE to create NewForm and my_actual_choices doesn't seem to work anyway.
I think a third way to solve this is to create a subclass of ChoiceField and redefined save() but I'm not sure how to go about doing this.
You can populate them dynamically by overriding the init, basically the code will look like:
class NewForm(forms.Form):
def __init__(self, choices, *args, **kwargs):
super(NewForm, self).__init__(*args, **kwargs)
self.fields["choices"] = forms.ChoiceField(choices=choices)
NewForm(my_actual_choices) or NewForm(my_actual_choices, request.POST, request.FILES) etc.

When subclassing a model field, __init__'s arguments are not processed

I have a subclass of models.ForeignKey, the only purpose of which is to use a custom widget:
from django.db import models
from .models import Images
class GAEImageField(models.ForeignKey):
def __init__(self, **kwargs):
super(GAEImageField, self).__init__(Images, **kwargs)
def formfield(self, *args, **kwargs):
field = forms.ModelChoiceField(self, widget=ImageUploadWidget, *args, **kwargs)
field.queryset = Images.objects.all()
return field
The problem is, when I try to use this field, any parameters to __init__ are ignored. For instance, if I try this model:
class SomethingWithImage(models.Model):
name = models.CharField('Awesome name', max_length=64)
image = GAEImageField(verbose_name='Awesome image', blank=True)
...despite the fact I specified verbose_name, the label on a generated form will be "Image" and trying to specify empty value will raise an error even though I use blank=True
Well, the problem is with your formfield method. If you look at the implementation used in the default ForeignKey for example, you'll see it calls super. I'd recommend something like this:
def formfield(self, **kwargs):
defaults = {
'widget': ImageUploadWidget,
}
defaults.update(kwargs)
return super(GAEImageField, self).formfield(**defaults)
The problem is, form fields don't extract any information from model fields. Form fields can be used completely independently from models, they don't have to be necessarily backed by a model field. That means all settings, like whether the field is required or not, its label etc. have to be passed as parameters to their constructors. It is the responsibility of the model field to create an appropriate instance of a form field, all settings included. The default implementation of django.db.models.fields.Field.formfield takes care of that which is why you usually want to call the parent's method.
As for the blank issue, try also setting null=True, otherwise even though the form will accept a blank value, the database will reject it. Also, note that modifying the value of null after syncdb has been run requires a database migration.

How to prevent self (recursive) selection for FK / MTM fields in the Django Admin

Given a model with ForeignKeyField (FKF) or ManyToManyField (MTMF) fields with a foreignkey to 'self' how can I prevent self (recursive) selection within the Django Admin (admin).
In short, it should be possible to prevent self (recursive) selection of a model instance in the admin. This applies when editing existing instances of a model, not creating new instances.
For example, take the following model for an article in a news app;
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField()
related_articles = models.ManyToManyField('self')
If there are 3 Article instances (title: a1-3), when editing an existing Article instance via the admin the related_articles field is represented by default by a html (multiple)select box which provides a list of ALL articles (Article.objects.all()). The user should only see and be able to select Article instances other than itself, e.g. When editing Article a1, related_articles available to select = a2, a3.
I can currently see 3 potential to ways to do this, in order of decreasing preference;
Provide a way to set the queryset providing available choices in the admin form field for the related_articles (via an exclude query filter, e.g. Article.objects.filter(~Q(id__iexact=self.id)) to exclude the current instance being edited from the list of related_articles a user can see and select from. Creation/setting of the queryset to use could occur within the constructor (__init__) of a custom Article ModelForm, or, via some kind of dynamic limit_choices_to Model option. This would require a way to grab the instance being edited to use for filtering.
Override the save_model function of the Article Model or ModelAdmin class to check for and remove itself from the related_articles before saving the instance. This still means that admin users can see and select all articles including the instance being edited (for existing articles).
Filter out self references when required for use outside the admin, e.g. templates.
The ideal solution (1) is currently possible to do via custom model forms outside of the admin as it's possible to pass in a filtered queryset variable for the instance being edited to the model form constructor. Question is, can you get at the Article instance, i.e. 'self' being edited the admin before the form is created to do the same thing.
It could be I am going about this the wrong way, but if your allowed to define a FKF / MTMF to the same model then there should be a way to have the admin - do the right thing - and prevent a user from selecting itself by excluding it in the list of available choices.
Note: Solution 2 and 3 are possible to do now and are provided to try and avoid getting these as answers, ideally i'd like to get an answer to solution 1.
Carl is correct, here's a cut and paste code sample that would go in admin.py
I find navigating the Django relationships can be tricky if you don't have a solid grasp, and a living example can be worth 1000 time more than a "go read this" (not that you don't need to understand what is happening).
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['myManyToManyField'].queryset = MyModel.objects.exclude(
id__exact=self.instance.id)
You can use a custom ModelForm in the admin (by setting the "form" attribute of your ModelAdmin subclass). So you do it the same way in the admin as you would anywhere else.
You can also override the get_form method of the ModelAdmin like so:
def get_form(self, request, obj=None, **kwargs):
"""
Modify the fields in the form that are self-referential by
removing self instance from queryset
"""
form = super().get_form(request, obj=None, **kwargs)
# obj won't exist yet for create page
if obj:
# Finds fieldnames of related fields whose model is self
rmself_fields = [f.name for f in self.model._meta.get_fields() if (
f.concrete and f.is_relation and f.related_model is self.model)]
for fieldname in rmself_fields:
form.base_fields[fieldname]._queryset =
form.base_fields[fieldname]._queryset.exclude(id=obj.id)
return form
Note that this is a on-size-fits-all solution that automatically finds self-referencing model fields and removes self from all of them :-)
I like the solution of checking at save() time:
def save(self, *args, **kwargs):
# call full_clean() that in turn will call clean()
self.full_clean()
return super().save(*args, **kwargs)
def clean(self):
obj = self
parents = set()
while obj is not None:
if obj in parents:
raise ValidationError('Loop error', code='infinite_loop')
parents.add(obj)
obj = obj.parent