Henry George
Henry George

Reputation: 514

Allow Django Admin to change whether a field is required

I'd like to be able to change whether the email field is required or not, depending on whether I'm showing a friend or a customer, without having to push to git every time and redeploy.

I have set up a Configuration model for other settings in Django which is configurable from the admin, but unfortunately I'm not able to use any of these settings in other Models or Model Fields, as it causes database errors on migration.

This is my code (it fails because of the migration issue)

class UserForm(forms.ModelForm):
    stake = StakeField()
    email = forms.EmailField(required=getConfig(ConfigData.USER_EMAIL_REQUIRED))

    class Meta:
        model = User
        fields = '__all__'

Is there another way to set the required/blank setting in either the model, modelform or form which won't cause this issue?

Edit for clarity:

I already have the Configuration AdminModel, but I'm struggling to use this value (True/False) in a ModelForm field without database errors, for a user facing form.

Upvotes: 2

Views: 4278

Answers (1)

CoffeeBasedLifeform
CoffeeBasedLifeform

Reputation: 2921

What's wrong with just editing the formfield's required attribute?

class UserForm(forms.ModelForm):
    stake = StakeField()
    email = forms.EmailField(required=False)

    def clean_email(self, value):
        # In case your database schema does not allow an empty value, otherwise, you can ignore this
        if not self.fields['email'].required and not value:
            # 'A friend' has used the form and the email field was not required
            value = 'whatever default/placeholder value you like'
        return value
    

class MyModelAdmin(admin.ModelAdmin):
    form = UserForm
    
    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        if not is_my_friend(request.user):
            form.base_fields['email'].required = True
        return form

Upvotes: 3

Related Questions