It seems no matter what I do I cannot get the parent field to not be required. I'm using DRF version 3.2.3 and Django 1.8.4.
Model definition of field:
parent = models.ForeignKey(
"self", verbose_name=_("Parent"), blank=True, null=True,
default=None, related_name='children')
The model also has a unique_together:
unique_together = (('owner', 'parent', 'name',),)
Serializer definition of field:
parent = serializers.HyperlinkedRelatedField(
view_name='category-detail', queryset=Category.objects.all(),
required=False)
I'm writing unittests and the response code is 400 with a text response of:
{'parent': [u'This field is required.']}
The parent field is a ForeignKey back to another row in the same table.
Gals/Guys any ideas how to fix this?
Sometimes a field can be implicitly made required by some other piece of code. One case I encountered is the model-level unique_together constraint, that makes all included fields required on the serializer level. From the doc:
Note: The UniqueTogetherValidation class always imposes an implicit constraint that all the fields it applies to are always
treated as required. Fields with default values are an exception to
this as they always supply a value even when omitted from user input.
I think you will just have to override the serializer save or viewset create/update to set the value to what you want at this point. Another option is to try to remove the UniqueTogetherValidator from the serializer's validators in its __init__. On the other hand I think it is added for a reason.
It is worth mentioning that in admin and anywhere else ModelForm is used, these fields won't be required because ModelForm is another thing entirely and it handles the validation in its own way.
Related
I am experimenting with moving our project over to UUID field primary keys. I've created a branch, deleted all the migrations and the database, and am trying to makemigrations when I hit new errors.
Per the docs, I made id an explicit field in our site Abstract Base Class of Model:
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
I was surprised that this results in a new error for ModelForms where 'id' is included in the fields property. The error says:
```django.core.exceptions.FieldError: 'id' cannot be specified for Statement model form as it is a non-editable field```
I removed 'id' from one Form, but for others it seems pretty essential to the function of the form / formsets that the primary key be returned with POST data. The Django implicit 'id' integer autofield is not editable, yet we did not get this error before, and we still don't where fields = '__all__' is set.
First you need to remove the non-editable field from your class form list of fields if relevant.
Then update your model admin to make your id as read_only:
class YourModelAdmin(admin.ModelAdmin):
readonly_fields=('id',)
form = YourModelModelForm # if relevant, otherwise keep the readonly_fields
Currently, if a field is required, this can be enforced via the blank = False argument, such as:
models.py
address1 = models.CharField(max_length=255,null=False,blank=False)
However, the validation is performed prior to the POST action, yielding something like this when trying to submit the form containing an empty field:
I would prefer the validation to be done during the post step, like this:
models.py
address1 = models.CharField(max_length=255,null=False,blank=true)
forms.py
class AddressForm(forms.ModelForm):
def __init__(self,*args,**kwargs):
super(AddressForm,self).__init__(*args,**kwargs)
self.fields['address1'].required = True
And this yields the following result when trying to submit the form containing an empty field:
But the problem with this, (as far as I can tell) is that I need to explicitly state the required attribute for each field on a case-by-case basis.
Is there any way that I can associate blank=False as being representative of the required=True attribute, suppressing the first form validation (above), in favour of the second?
ModelForm runs form validation, then model validation:
There are two main steps involved in validating a ModelForm:
Validating the form
Validating the model instance
So you have to manually add the extra form validation that you want before the inherited model validations.
However, default ModelForm field for blank field is already required:
If the model field has blank=True, then required is set to False on
the form field. Otherwise, required=True
You can change the error message. If you use this additional validations a lot, you can use a Mixin:
class BlankToRequiredMixin(object):
def set_required(self):
model = self._meta.model
for field_name,form_field in self.fields.iteritems():
if not model._meta.get_field(field_name).blank:
form_field.error_messages={'required': 'This field is required'} # to make it required in addtion to non-blank set .required=True
Then, to set required=True for all fields that are non-blank in the model:
class AddressForm(forms.ModelForm,BlankToRequiredMixin):
def __init__(self,*args,**kwargs):
super(AddressForm,self).__init__(*args,**kwargs)
self.set_required()
In a similar way you can add other validations to the form fields, based on the model validation attributes. For the appearance, change the widget and set the field widget in the mixin.
I may want these fields to be required at another point on a form, but for now how can I set all fields from my model to not required for the admin? Id prefer not required to be default if that is possible. To elaborate...I go to enter data into the django admin form, but it does not save it because it says that the other fields are required. Is there a way for me to fix this for just the admin? Thank you in advance for your help!
First: If your Model has such fields as blank=False or null=False (depending on the field), two things will happen:
Yoy MUST create a custom ModelForm having each same field declared, each with required=False
Such model will make boom when trying to save it to database (because null values cannot be passed to null=False columns).
So, in first place, you must have all your fields in your model as null=True and blank=True. Consequently, and by-default, ModelForm classes will be created with fields with the same restrictions - in this case, having required=False. So it will be open by default, and you can safely use a ModelAdmin as always. BUT this implies you must declare an explicit ModelForm class for customers/guests, with explicit same-fields but having required=True (edited. by default the fields would be created with required=False, since the database had blank=False in the example I gave).
ModelAdmin does not have a way to freely-open form fields by itself - not even Forms have ways to say "Do you remember this field declared in the parent? well: I want to have it but without the required in True".
The only way that seems to be possible is to write your own models fields that would have required=False and blank=True by default. Otherwise you would be breaking database.
This is how my models look:
class QuestionTagM2M(models.Model):
tag = models.ForeignKey('Tag')
question = models.ForeignKey('Question')
date_added = models.DateTimeField(auto_now_add=True)
class Tag(models.Model):
description = models.CharField(max_length=100, unique=True)
class Question(models.Model):
tags = models.ManyToManyField(Tag, through=QuestionTagM2M, related_name='questions')
All I really wanted to do was add a timestamp when a given manytomany relationship was created. It makes sense, but it also adds a bit of complexity. Apart from removing the .add() functionality [despite the fact that the only field I'm really adding is auto-created so it technically shouldn't interfere with this anymore]. But I can live with that, as I don't mind doing the extra QuestionTagM2M.objects.create(question=,tag=) instead if it means gaining the additional timestamp functionality.
My issue is I really would love to be able to preserve my filter_horizontal javascript widget in the admin. I know the docs say I can use an inline instead, but this is just too unwieldy because there are no additional fields that would actually be in the inline apart from the foreign key to the Tag anyway.
Also, in the larger scheme of my database schema, my Question objects are already displayed as an inline on my admin page, and since Django doesn't support nested inlines in the admin [yet], I have no way of selecting tags for a given question.
Is there any way to override formfield_for_manytomany(self, db_field, request=None, **kwargs) or something similar to allow for my usage of the nifty filter_horizontal widget and the auto creation of the date_added column to the database?
This seems like something that django should be able to do natively as long as you specify that all columns in the intermediate are automatically created (other than the foreign keys) perhaps with auto_created=True? or something of the like
There are ways to do this
As provided by #obsoleter in the comment below : set QuestionTagM2M._meta.auto_created = True and deal w/ syncdb matters.
Dynamically add date_added field to the M2M model of Question model in models.py
class Question(models.Model):
# use auto-created M2M model
tags = models.ManyToMany(Tag, related_name='questions')
# add date_added field to the M2M model
models.DateTimeField(auto_now_add=True).contribute_to_class(
Question.tags.through, 'date_added')
Then you could use it in admin as normal ManyToManyField.
In Python shell, use Question.tags.through to refer the M2M model.
Note, If you don't use South, then syncdb is enough; If you do, South does not like
this way and will not freeze date_added field, you need to manually write migration to add/remove the corresponding column.
Customize ModelAdmin:
Don't define fields inside customized ModelAdmin, only define filter_horizontal. This will bypass the field validation mentioned in Irfan's answer.
Customize formfield_for_dbfield() or formfield_for_manytomany() to make Django admin to use widgets.FilteredSelectMultiple for the tags field.
Customize save_related() method inside your ModelAdmin class, like
def save_related(self, request, form, *args, **kwargs):
tags = form.cleaned_data.pop('tags', ())
question = form.instance
for tag in tags:
QuestionTagM2M.objects.create(tag=tag, question=question)
super(QuestionAdmin, self).save_related(request, form, *args, **kwargs)
Also, you could patch __set__() of the ReverseManyRelatedObjectsDescriptor field descriptor of ManyToManyField for date_added to save M2M instance w/o raise exception.
From https://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models
When you specify an intermediary model using the through argument to a ManyToManyField, the admin will not display a widget by default. This is because each instance of that intermediary model requires more information than could be displayed in a single widget, and the layout required for multiple widgets will vary depending on the intermediate model.
However, you can try including the tags field explicitly by using fields = ('tags',) in admin. This will cause this validation exception
'QuestionAdmin.fields' can't include the ManyToManyField field 'tags' because 'tags' manually specifies a 'through' model.
This validation is implemented in https://github.com/django/django/blob/master/django/contrib/admin/validation.py#L256
if isinstance(f, models.ManyToManyField) and not f.rel.through._meta.auto_created:
raise ImproperlyConfigured("'%s.%s' "
"can't include the ManyToManyField field '%s' because "
"'%s' manually specifies a 'through' model." % (
cls.__name__, label, field, field))
I don't think that you can bypass this validation unless you implement your own custom field to be used as ManyToManyField.
The docs may have changed since the previous answers were posted. I took a look at the django docs link that #Irfan mentioned and it seems to be a more straight forward then it used to be.
Add an inline class to your admin.py and set the model to your M2M model
class QuestionTagM2MInline(admin.TabularInline):
model = QuestionTagM2M
extra = 1
set inlines in your admin class to contain the Inline you just defined
class QuestionAdmin(admin.ModelAdmin):
#...other stuff here
inlines = (QuestionTagM2MInline,)
Don't forget to register this admin class
admin.site.register(Question, QuestionAdmin)
After doing the above when I click on a question I have the form to do all the normal edits on it and below that are a list of the elements in my m2m relationship where I can add entries or edit existing ones.
Following regular manytomany queryset logic gives me errors. I guess since its related to self, I might need to do some extra magic, but i can't figure out what magic.
model:
class Entry(models.Model):
title = models.CharField(max_length=100, verbose_name='title')
related = models.ManyToManyField('self', related_name='related_entries', blank=True)
queryset:
entry = Entry.objects.get(pk=1)
related = entry.related_entries.all()
error: 'Entry' object has no attribute 'related_entries'
Look at the documentation for the symmetrical argument to ManyToManyField:
When Django processes this model, it identifies that it has a ManyToManyField on itself, and as a result, it doesn't add a person_set attribute to the Person class. Instead, the ManyToManyField is assumed to be symmetrical -- that is, if I am your friend, then you are my friend.
If you do not want symmetry in many-to-many relationships with self, set symmetrical to False. This will force Django to add the descriptor for the reverse relationship, allowing ManyToManyField relationships to be non-symmetrical.
So, in order to use the related_name, set symmetrical=False.