[Answered ]-Django Faking Required Fields

2👍

You certainly can do that, and it comes in handy when there is information which would relate to the user, that you wouldn’t know yourself when needing to create objects.

So, to do so you simply create your own form and declare the field in the form as required. You can then run your validation on the form before creating the object.

For example, here’s a form I’ve got which is used by the model admin;

class EventAdminForm(forms.ModelForm):
    category = forms.ModelChoiceField(
        label=_("State/Province/Territory"),
        queryset=Category.objects.none(),
        empty_label=_("---------"),
        required=False,
    )

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(EventAdminForm, self).__init__(*args, **kwargs)

        if not self.user.is_superuser:
            self.fields['category'].required = True

    class Meta:
        model = Event
        exclude = ()

Just like any other form, you can define your fields, and whether or not they are required.

So, following the update, you need to pass the user to the form. For example;

def someview(request):
    if request.method == 'POST':
        form = EventAdminForm(request.POST, user=request.user)
        if form.is_valid():
            # Do something with the data
            pass
    else:
        form = EventAdminForm(user=request.user)

If you’ve got a form, but want to know if you’re editing an object, or creating one it’s quite simple. If you’re editing, the form will have an instance attribute which is the object you’re editing.

get_from() takes an obj argument which is likely the object, if you’re editing one, but you’d have to check that. Docs are here; https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_form

Edit

Ok, lets simplify this, and put the required logic in admin, then you don’t need to mess with the form at all;

def get_form(self, request, obj=None, **kwargs):
    form = super(StudentAdmin, self).get_form(request, obj, **kwargs)

    if request.user.is_superuser:
        form.base_fields['picture'].required = False

    return form

Leave a comment