Changing a form field's 'required' property with save_model in Django admin












0















I have tried all the different examples and methods I could find on Stack Overflow for this, and for whatever reason, can't get this to work properly.



So in my admin.py I have a UserForm and and UserAdmin. Based on the condition where a boolean is checked within the form, I want to change the 'required' attribute on a few different form fields to 'false' so I can effectively save. I've used a few different print statements to ascertain that the 'required' is in fact getting changed to false when the condition is met, however, when I try and save, it won't let me as the fields highlight and say they're still required.



It is almost like the save_model doesn't care how I edit the form, that the old form and its 'required' attributes are overriding my changes. Thanks for any help!



admin.py



class UserForm(forms.ModelForm):
state = forms.CharField(min_length=2, widget=forms.TextInput(attrs={'placeholder':'CA'}))
zipcode = forms.CharField(max_length=5, min_length=5,)

class Meta:
model = User
fields = '__all__'


class UserAdmin(admin.ModelAdmin):
model = Order
form = UserForm

def save_model(self, request, obj, form, change):
if obj.pickup_only == 1:
form.fields['address'].required = False
form.fields['city'].required = False
form.fields['state'].required = False
form.fields['zipcode'].required = False
return super(UserAdmin, self).save_model(request, obj, form, change)




revised code for UserForm:



def clean(self):
cleaned_data = super(UserForm, self).clean()
address = cleaned_data.get('address')
state = cleaned_data.get('state')
city = cleaned_data.get('city')
zipcode = cleaned_data.get('zipcode')
pickup_only = cleaned_data.get('pickup_only')

if pickup_only == True:
# I STUCK IN ADDRESS TO EMPHASIZE THE ERROR IN SCREENSHOT
self.fields_required(['first_name', 'last_name', 'dob', 'phone', 'email', 'address'])
else:
self.cleaned_data['address', 'city', 'state', 'zip code'] = ''
return self.cleaned_data

def fields_required(self, fields):
for field in fields:
print(field)
# RETURNS: first_name, last_name, dob, phone, email, address
if not self.cleaned_data.get(field, ''):
msg = forms.ValidationError("This field is required. Custom.")
self.add_error(field, msg)


When I save I get this:



enter image description here










share|improve this question

























  • can you add UserForm?

    – JPG
    Nov 21 '18 at 2:42











  • Yes sir, will do..

    – Dev
    Nov 21 '18 at 2:43











  • Apart from that, in your UserAdmin class you'd defined model = Order and in your UserForm its model = User. Will that is a problem?

    – JPG
    Nov 21 '18 at 2:53











  • I have model = order in my UserAdmin as it's referencing the model class that I have for an inline display. As that's not an argument being passed in the save_model function, I figured it wouldn't be relevant. At any rate, I commented it out to see if would have any bearing on the code not working, and it unfortunately did not.

    – Dev
    Nov 21 '18 at 3:00













  • What I think would be better is, define those fields in model as blank=True and handle the validation manually in clean() method of form

    – JPG
    Nov 21 '18 at 3:08
















0















I have tried all the different examples and methods I could find on Stack Overflow for this, and for whatever reason, can't get this to work properly.



So in my admin.py I have a UserForm and and UserAdmin. Based on the condition where a boolean is checked within the form, I want to change the 'required' attribute on a few different form fields to 'false' so I can effectively save. I've used a few different print statements to ascertain that the 'required' is in fact getting changed to false when the condition is met, however, when I try and save, it won't let me as the fields highlight and say they're still required.



It is almost like the save_model doesn't care how I edit the form, that the old form and its 'required' attributes are overriding my changes. Thanks for any help!



admin.py



class UserForm(forms.ModelForm):
state = forms.CharField(min_length=2, widget=forms.TextInput(attrs={'placeholder':'CA'}))
zipcode = forms.CharField(max_length=5, min_length=5,)

class Meta:
model = User
fields = '__all__'


class UserAdmin(admin.ModelAdmin):
model = Order
form = UserForm

def save_model(self, request, obj, form, change):
if obj.pickup_only == 1:
form.fields['address'].required = False
form.fields['city'].required = False
form.fields['state'].required = False
form.fields['zipcode'].required = False
return super(UserAdmin, self).save_model(request, obj, form, change)




revised code for UserForm:



def clean(self):
cleaned_data = super(UserForm, self).clean()
address = cleaned_data.get('address')
state = cleaned_data.get('state')
city = cleaned_data.get('city')
zipcode = cleaned_data.get('zipcode')
pickup_only = cleaned_data.get('pickup_only')

if pickup_only == True:
# I STUCK IN ADDRESS TO EMPHASIZE THE ERROR IN SCREENSHOT
self.fields_required(['first_name', 'last_name', 'dob', 'phone', 'email', 'address'])
else:
self.cleaned_data['address', 'city', 'state', 'zip code'] = ''
return self.cleaned_data

def fields_required(self, fields):
for field in fields:
print(field)
# RETURNS: first_name, last_name, dob, phone, email, address
if not self.cleaned_data.get(field, ''):
msg = forms.ValidationError("This field is required. Custom.")
self.add_error(field, msg)


When I save I get this:



enter image description here










share|improve this question

























  • can you add UserForm?

    – JPG
    Nov 21 '18 at 2:42











  • Yes sir, will do..

    – Dev
    Nov 21 '18 at 2:43











  • Apart from that, in your UserAdmin class you'd defined model = Order and in your UserForm its model = User. Will that is a problem?

    – JPG
    Nov 21 '18 at 2:53











  • I have model = order in my UserAdmin as it's referencing the model class that I have for an inline display. As that's not an argument being passed in the save_model function, I figured it wouldn't be relevant. At any rate, I commented it out to see if would have any bearing on the code not working, and it unfortunately did not.

    – Dev
    Nov 21 '18 at 3:00













  • What I think would be better is, define those fields in model as blank=True and handle the validation manually in clean() method of form

    – JPG
    Nov 21 '18 at 3:08














0












0








0








I have tried all the different examples and methods I could find on Stack Overflow for this, and for whatever reason, can't get this to work properly.



So in my admin.py I have a UserForm and and UserAdmin. Based on the condition where a boolean is checked within the form, I want to change the 'required' attribute on a few different form fields to 'false' so I can effectively save. I've used a few different print statements to ascertain that the 'required' is in fact getting changed to false when the condition is met, however, when I try and save, it won't let me as the fields highlight and say they're still required.



It is almost like the save_model doesn't care how I edit the form, that the old form and its 'required' attributes are overriding my changes. Thanks for any help!



admin.py



class UserForm(forms.ModelForm):
state = forms.CharField(min_length=2, widget=forms.TextInput(attrs={'placeholder':'CA'}))
zipcode = forms.CharField(max_length=5, min_length=5,)

class Meta:
model = User
fields = '__all__'


class UserAdmin(admin.ModelAdmin):
model = Order
form = UserForm

def save_model(self, request, obj, form, change):
if obj.pickup_only == 1:
form.fields['address'].required = False
form.fields['city'].required = False
form.fields['state'].required = False
form.fields['zipcode'].required = False
return super(UserAdmin, self).save_model(request, obj, form, change)




revised code for UserForm:



def clean(self):
cleaned_data = super(UserForm, self).clean()
address = cleaned_data.get('address')
state = cleaned_data.get('state')
city = cleaned_data.get('city')
zipcode = cleaned_data.get('zipcode')
pickup_only = cleaned_data.get('pickup_only')

if pickup_only == True:
# I STUCK IN ADDRESS TO EMPHASIZE THE ERROR IN SCREENSHOT
self.fields_required(['first_name', 'last_name', 'dob', 'phone', 'email', 'address'])
else:
self.cleaned_data['address', 'city', 'state', 'zip code'] = ''
return self.cleaned_data

def fields_required(self, fields):
for field in fields:
print(field)
# RETURNS: first_name, last_name, dob, phone, email, address
if not self.cleaned_data.get(field, ''):
msg = forms.ValidationError("This field is required. Custom.")
self.add_error(field, msg)


When I save I get this:



enter image description here










share|improve this question
















I have tried all the different examples and methods I could find on Stack Overflow for this, and for whatever reason, can't get this to work properly.



So in my admin.py I have a UserForm and and UserAdmin. Based on the condition where a boolean is checked within the form, I want to change the 'required' attribute on a few different form fields to 'false' so I can effectively save. I've used a few different print statements to ascertain that the 'required' is in fact getting changed to false when the condition is met, however, when I try and save, it won't let me as the fields highlight and say they're still required.



It is almost like the save_model doesn't care how I edit the form, that the old form and its 'required' attributes are overriding my changes. Thanks for any help!



admin.py



class UserForm(forms.ModelForm):
state = forms.CharField(min_length=2, widget=forms.TextInput(attrs={'placeholder':'CA'}))
zipcode = forms.CharField(max_length=5, min_length=5,)

class Meta:
model = User
fields = '__all__'


class UserAdmin(admin.ModelAdmin):
model = Order
form = UserForm

def save_model(self, request, obj, form, change):
if obj.pickup_only == 1:
form.fields['address'].required = False
form.fields['city'].required = False
form.fields['state'].required = False
form.fields['zipcode'].required = False
return super(UserAdmin, self).save_model(request, obj, form, change)




revised code for UserForm:



def clean(self):
cleaned_data = super(UserForm, self).clean()
address = cleaned_data.get('address')
state = cleaned_data.get('state')
city = cleaned_data.get('city')
zipcode = cleaned_data.get('zipcode')
pickup_only = cleaned_data.get('pickup_only')

if pickup_only == True:
# I STUCK IN ADDRESS TO EMPHASIZE THE ERROR IN SCREENSHOT
self.fields_required(['first_name', 'last_name', 'dob', 'phone', 'email', 'address'])
else:
self.cleaned_data['address', 'city', 'state', 'zip code'] = ''
return self.cleaned_data

def fields_required(self, fields):
for field in fields:
print(field)
# RETURNS: first_name, last_name, dob, phone, email, address
if not self.cleaned_data.get(field, ''):
msg = forms.ValidationError("This field is required. Custom.")
self.add_error(field, msg)


When I save I get this:



enter image description here







django django-models django-forms django-rest-framework django-admin






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 6:48







Dev

















asked Nov 21 '18 at 2:39









DevDev

387




387













  • can you add UserForm?

    – JPG
    Nov 21 '18 at 2:42











  • Yes sir, will do..

    – Dev
    Nov 21 '18 at 2:43











  • Apart from that, in your UserAdmin class you'd defined model = Order and in your UserForm its model = User. Will that is a problem?

    – JPG
    Nov 21 '18 at 2:53











  • I have model = order in my UserAdmin as it's referencing the model class that I have for an inline display. As that's not an argument being passed in the save_model function, I figured it wouldn't be relevant. At any rate, I commented it out to see if would have any bearing on the code not working, and it unfortunately did not.

    – Dev
    Nov 21 '18 at 3:00













  • What I think would be better is, define those fields in model as blank=True and handle the validation manually in clean() method of form

    – JPG
    Nov 21 '18 at 3:08



















  • can you add UserForm?

    – JPG
    Nov 21 '18 at 2:42











  • Yes sir, will do..

    – Dev
    Nov 21 '18 at 2:43











  • Apart from that, in your UserAdmin class you'd defined model = Order and in your UserForm its model = User. Will that is a problem?

    – JPG
    Nov 21 '18 at 2:53











  • I have model = order in my UserAdmin as it's referencing the model class that I have for an inline display. As that's not an argument being passed in the save_model function, I figured it wouldn't be relevant. At any rate, I commented it out to see if would have any bearing on the code not working, and it unfortunately did not.

    – Dev
    Nov 21 '18 at 3:00













  • What I think would be better is, define those fields in model as blank=True and handle the validation manually in clean() method of form

    – JPG
    Nov 21 '18 at 3:08

















can you add UserForm?

– JPG
Nov 21 '18 at 2:42





can you add UserForm?

– JPG
Nov 21 '18 at 2:42













Yes sir, will do..

– Dev
Nov 21 '18 at 2:43





Yes sir, will do..

– Dev
Nov 21 '18 at 2:43













Apart from that, in your UserAdmin class you'd defined model = Order and in your UserForm its model = User. Will that is a problem?

– JPG
Nov 21 '18 at 2:53





Apart from that, in your UserAdmin class you'd defined model = Order and in your UserForm its model = User. Will that is a problem?

– JPG
Nov 21 '18 at 2:53













I have model = order in my UserAdmin as it's referencing the model class that I have for an inline display. As that's not an argument being passed in the save_model function, I figured it wouldn't be relevant. At any rate, I commented it out to see if would have any bearing on the code not working, and it unfortunately did not.

– Dev
Nov 21 '18 at 3:00







I have model = order in my UserAdmin as it's referencing the model class that I have for an inline display. As that's not an argument being passed in the save_model function, I figured it wouldn't be relevant. At any rate, I commented it out to see if would have any bearing on the code not working, and it unfortunately did not.

– Dev
Nov 21 '18 at 3:00















What I think would be better is, define those fields in model as blank=True and handle the validation manually in clean() method of form

– JPG
Nov 21 '18 at 3:08





What I think would be better is, define those fields in model as blank=True and handle the validation manually in clean() method of form

– JPG
Nov 21 '18 at 3:08












1 Answer
1






active

oldest

votes


















1














You might have to tweak it a little bit to fit your needs, but you could try something like this in your clean method:



def clean(self):
cleaned_data = super(UserForm, self).clean()
state = cleaned_data.get('state')
zipcode = cleaned_data.get('zipcode')
pickup_only = cleaned_data.get('pickup_only')

if pickup_only == True:
self.fields_required(['any_fields_required',])
else:
self.cleaned_data['state', 'zip code'] = ''
return self.cleaned_data

def fields_required(self, fields):
for field in fields:
if not self.cleaned_data.get(field, ''):
msg = forms.ValidationError("This field is required.")
self.add_error(field, msg)


Also, as one of the commenters mentioned, you should not specify your model=Order in the UserAdmin. Your UserAdmin is for the User model. That isn't the proper way to add inlines. See below:



# You can also use (admin.TabularInline) depending on your needs.
class OrderInline(admin.StackedInline):
model = Order
list_display = ('order_fields',)
fieldsets = (
((''), {'fields': ('order_fields',)}),
)

class UserAdmin(admin.ModelAdmin):
model = User
inlines = [OrderInline,]


Add an init method to your form:



class UserForm(forms.ModelForm):
state = forms.CharField(min_length=2, widget=forms.TextInput(attrs={'placeholder':'CA'}))
zipcode = forms.CharField(max_length=5, min_length=5,)

class Meta:
model = User
fields = '__all__'

def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
self.fields['address'].required = False
self.fields['city'].required = False
self.fields['state'].required = False
self.fields['zipcode'].required = False

def clean(self):
cleaned_data = super(UserForm, self).clean()
address = cleaned_data.get('address')
state = cleaned_data.get('state')
city = cleaned_data.get('city')
zipcode = cleaned_data.get('zipcode')
pickup_only = cleaned_data.get('pickup_only')

if pickup_only == True:
self.fields_required(['first_name', 'last_name', 'dob', 'phone', 'email', 'address'])
else:
self.cleaned_data['address', 'city', 'state', 'zip code'] = ''
return self.cleaned_data

def fields_required(self, fields):
for field in fields:
if not self.cleaned_data.get(field, ''):
msg = forms.ValidationError("This field is required. Custom.")
self.add_error(field, msg)


Try this. If it works then I don't think you have to override the save method in your UserAdmin. I would avoid that anyway unless absolutely necessary.






share|improve this answer


























  • Thank you for the response! I tried the above code to fit the fields I needed for it and it didn't seem to work. It doesn't seem the fields_required method is being called correctly. I tried printing from within the method to debug, but couldn't get any output when I tried saving. Am I doing something wrong?

    – Dev
    Nov 21 '18 at 5:39













  • @Dev - what error are you getting if any? What is going on in the form? Is the model saving?

    – Whodini
    Nov 21 '18 at 6:23











  • I'm not getting back any error, however, I've been messing around with the code to better understand what's going on. So far I have: if pickup_only is true, self.fields_required(['first_name', 'last_name', 'dob', 'phone', 'email',]) --> these are the fields I want required. Then for the ELSE, I have the address fields (city, state, zip). For the fields_required method, when I print the fields it prints everything but the address fields. I tried adding 'address' to self.fields_required array and the error message spit out, but I'm obviously doing something wrong or have things mixed up.

    – Dev
    Nov 21 '18 at 6:33








  • 1





    @Dev - try just if pickup_only:

    – Whodini
    Nov 21 '18 at 7:12






  • 1





    @Dev - ah I think I know the problem. It was my mistake. See the answer again for the change. Move the fields_required method outside the clean method.

    – Whodini
    Nov 21 '18 at 7:17











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53404568%2fchanging-a-form-fields-required-property-with-save-model-in-django-admin%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














You might have to tweak it a little bit to fit your needs, but you could try something like this in your clean method:



def clean(self):
cleaned_data = super(UserForm, self).clean()
state = cleaned_data.get('state')
zipcode = cleaned_data.get('zipcode')
pickup_only = cleaned_data.get('pickup_only')

if pickup_only == True:
self.fields_required(['any_fields_required',])
else:
self.cleaned_data['state', 'zip code'] = ''
return self.cleaned_data

def fields_required(self, fields):
for field in fields:
if not self.cleaned_data.get(field, ''):
msg = forms.ValidationError("This field is required.")
self.add_error(field, msg)


Also, as one of the commenters mentioned, you should not specify your model=Order in the UserAdmin. Your UserAdmin is for the User model. That isn't the proper way to add inlines. See below:



# You can also use (admin.TabularInline) depending on your needs.
class OrderInline(admin.StackedInline):
model = Order
list_display = ('order_fields',)
fieldsets = (
((''), {'fields': ('order_fields',)}),
)

class UserAdmin(admin.ModelAdmin):
model = User
inlines = [OrderInline,]


Add an init method to your form:



class UserForm(forms.ModelForm):
state = forms.CharField(min_length=2, widget=forms.TextInput(attrs={'placeholder':'CA'}))
zipcode = forms.CharField(max_length=5, min_length=5,)

class Meta:
model = User
fields = '__all__'

def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
self.fields['address'].required = False
self.fields['city'].required = False
self.fields['state'].required = False
self.fields['zipcode'].required = False

def clean(self):
cleaned_data = super(UserForm, self).clean()
address = cleaned_data.get('address')
state = cleaned_data.get('state')
city = cleaned_data.get('city')
zipcode = cleaned_data.get('zipcode')
pickup_only = cleaned_data.get('pickup_only')

if pickup_only == True:
self.fields_required(['first_name', 'last_name', 'dob', 'phone', 'email', 'address'])
else:
self.cleaned_data['address', 'city', 'state', 'zip code'] = ''
return self.cleaned_data

def fields_required(self, fields):
for field in fields:
if not self.cleaned_data.get(field, ''):
msg = forms.ValidationError("This field is required. Custom.")
self.add_error(field, msg)


Try this. If it works then I don't think you have to override the save method in your UserAdmin. I would avoid that anyway unless absolutely necessary.






share|improve this answer


























  • Thank you for the response! I tried the above code to fit the fields I needed for it and it didn't seem to work. It doesn't seem the fields_required method is being called correctly. I tried printing from within the method to debug, but couldn't get any output when I tried saving. Am I doing something wrong?

    – Dev
    Nov 21 '18 at 5:39













  • @Dev - what error are you getting if any? What is going on in the form? Is the model saving?

    – Whodini
    Nov 21 '18 at 6:23











  • I'm not getting back any error, however, I've been messing around with the code to better understand what's going on. So far I have: if pickup_only is true, self.fields_required(['first_name', 'last_name', 'dob', 'phone', 'email',]) --> these are the fields I want required. Then for the ELSE, I have the address fields (city, state, zip). For the fields_required method, when I print the fields it prints everything but the address fields. I tried adding 'address' to self.fields_required array and the error message spit out, but I'm obviously doing something wrong or have things mixed up.

    – Dev
    Nov 21 '18 at 6:33








  • 1





    @Dev - try just if pickup_only:

    – Whodini
    Nov 21 '18 at 7:12






  • 1





    @Dev - ah I think I know the problem. It was my mistake. See the answer again for the change. Move the fields_required method outside the clean method.

    – Whodini
    Nov 21 '18 at 7:17
















1














You might have to tweak it a little bit to fit your needs, but you could try something like this in your clean method:



def clean(self):
cleaned_data = super(UserForm, self).clean()
state = cleaned_data.get('state')
zipcode = cleaned_data.get('zipcode')
pickup_only = cleaned_data.get('pickup_only')

if pickup_only == True:
self.fields_required(['any_fields_required',])
else:
self.cleaned_data['state', 'zip code'] = ''
return self.cleaned_data

def fields_required(self, fields):
for field in fields:
if not self.cleaned_data.get(field, ''):
msg = forms.ValidationError("This field is required.")
self.add_error(field, msg)


Also, as one of the commenters mentioned, you should not specify your model=Order in the UserAdmin. Your UserAdmin is for the User model. That isn't the proper way to add inlines. See below:



# You can also use (admin.TabularInline) depending on your needs.
class OrderInline(admin.StackedInline):
model = Order
list_display = ('order_fields',)
fieldsets = (
((''), {'fields': ('order_fields',)}),
)

class UserAdmin(admin.ModelAdmin):
model = User
inlines = [OrderInline,]


Add an init method to your form:



class UserForm(forms.ModelForm):
state = forms.CharField(min_length=2, widget=forms.TextInput(attrs={'placeholder':'CA'}))
zipcode = forms.CharField(max_length=5, min_length=5,)

class Meta:
model = User
fields = '__all__'

def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
self.fields['address'].required = False
self.fields['city'].required = False
self.fields['state'].required = False
self.fields['zipcode'].required = False

def clean(self):
cleaned_data = super(UserForm, self).clean()
address = cleaned_data.get('address')
state = cleaned_data.get('state')
city = cleaned_data.get('city')
zipcode = cleaned_data.get('zipcode')
pickup_only = cleaned_data.get('pickup_only')

if pickup_only == True:
self.fields_required(['first_name', 'last_name', 'dob', 'phone', 'email', 'address'])
else:
self.cleaned_data['address', 'city', 'state', 'zip code'] = ''
return self.cleaned_data

def fields_required(self, fields):
for field in fields:
if not self.cleaned_data.get(field, ''):
msg = forms.ValidationError("This field is required. Custom.")
self.add_error(field, msg)


Try this. If it works then I don't think you have to override the save method in your UserAdmin. I would avoid that anyway unless absolutely necessary.






share|improve this answer


























  • Thank you for the response! I tried the above code to fit the fields I needed for it and it didn't seem to work. It doesn't seem the fields_required method is being called correctly. I tried printing from within the method to debug, but couldn't get any output when I tried saving. Am I doing something wrong?

    – Dev
    Nov 21 '18 at 5:39













  • @Dev - what error are you getting if any? What is going on in the form? Is the model saving?

    – Whodini
    Nov 21 '18 at 6:23











  • I'm not getting back any error, however, I've been messing around with the code to better understand what's going on. So far I have: if pickup_only is true, self.fields_required(['first_name', 'last_name', 'dob', 'phone', 'email',]) --> these are the fields I want required. Then for the ELSE, I have the address fields (city, state, zip). For the fields_required method, when I print the fields it prints everything but the address fields. I tried adding 'address' to self.fields_required array and the error message spit out, but I'm obviously doing something wrong or have things mixed up.

    – Dev
    Nov 21 '18 at 6:33








  • 1





    @Dev - try just if pickup_only:

    – Whodini
    Nov 21 '18 at 7:12






  • 1





    @Dev - ah I think I know the problem. It was my mistake. See the answer again for the change. Move the fields_required method outside the clean method.

    – Whodini
    Nov 21 '18 at 7:17














1












1








1







You might have to tweak it a little bit to fit your needs, but you could try something like this in your clean method:



def clean(self):
cleaned_data = super(UserForm, self).clean()
state = cleaned_data.get('state')
zipcode = cleaned_data.get('zipcode')
pickup_only = cleaned_data.get('pickup_only')

if pickup_only == True:
self.fields_required(['any_fields_required',])
else:
self.cleaned_data['state', 'zip code'] = ''
return self.cleaned_data

def fields_required(self, fields):
for field in fields:
if not self.cleaned_data.get(field, ''):
msg = forms.ValidationError("This field is required.")
self.add_error(field, msg)


Also, as one of the commenters mentioned, you should not specify your model=Order in the UserAdmin. Your UserAdmin is for the User model. That isn't the proper way to add inlines. See below:



# You can also use (admin.TabularInline) depending on your needs.
class OrderInline(admin.StackedInline):
model = Order
list_display = ('order_fields',)
fieldsets = (
((''), {'fields': ('order_fields',)}),
)

class UserAdmin(admin.ModelAdmin):
model = User
inlines = [OrderInline,]


Add an init method to your form:



class UserForm(forms.ModelForm):
state = forms.CharField(min_length=2, widget=forms.TextInput(attrs={'placeholder':'CA'}))
zipcode = forms.CharField(max_length=5, min_length=5,)

class Meta:
model = User
fields = '__all__'

def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
self.fields['address'].required = False
self.fields['city'].required = False
self.fields['state'].required = False
self.fields['zipcode'].required = False

def clean(self):
cleaned_data = super(UserForm, self).clean()
address = cleaned_data.get('address')
state = cleaned_data.get('state')
city = cleaned_data.get('city')
zipcode = cleaned_data.get('zipcode')
pickup_only = cleaned_data.get('pickup_only')

if pickup_only == True:
self.fields_required(['first_name', 'last_name', 'dob', 'phone', 'email', 'address'])
else:
self.cleaned_data['address', 'city', 'state', 'zip code'] = ''
return self.cleaned_data

def fields_required(self, fields):
for field in fields:
if not self.cleaned_data.get(field, ''):
msg = forms.ValidationError("This field is required. Custom.")
self.add_error(field, msg)


Try this. If it works then I don't think you have to override the save method in your UserAdmin. I would avoid that anyway unless absolutely necessary.






share|improve this answer















You might have to tweak it a little bit to fit your needs, but you could try something like this in your clean method:



def clean(self):
cleaned_data = super(UserForm, self).clean()
state = cleaned_data.get('state')
zipcode = cleaned_data.get('zipcode')
pickup_only = cleaned_data.get('pickup_only')

if pickup_only == True:
self.fields_required(['any_fields_required',])
else:
self.cleaned_data['state', 'zip code'] = ''
return self.cleaned_data

def fields_required(self, fields):
for field in fields:
if not self.cleaned_data.get(field, ''):
msg = forms.ValidationError("This field is required.")
self.add_error(field, msg)


Also, as one of the commenters mentioned, you should not specify your model=Order in the UserAdmin. Your UserAdmin is for the User model. That isn't the proper way to add inlines. See below:



# You can also use (admin.TabularInline) depending on your needs.
class OrderInline(admin.StackedInline):
model = Order
list_display = ('order_fields',)
fieldsets = (
((''), {'fields': ('order_fields',)}),
)

class UserAdmin(admin.ModelAdmin):
model = User
inlines = [OrderInline,]


Add an init method to your form:



class UserForm(forms.ModelForm):
state = forms.CharField(min_length=2, widget=forms.TextInput(attrs={'placeholder':'CA'}))
zipcode = forms.CharField(max_length=5, min_length=5,)

class Meta:
model = User
fields = '__all__'

def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
self.fields['address'].required = False
self.fields['city'].required = False
self.fields['state'].required = False
self.fields['zipcode'].required = False

def clean(self):
cleaned_data = super(UserForm, self).clean()
address = cleaned_data.get('address')
state = cleaned_data.get('state')
city = cleaned_data.get('city')
zipcode = cleaned_data.get('zipcode')
pickup_only = cleaned_data.get('pickup_only')

if pickup_only == True:
self.fields_required(['first_name', 'last_name', 'dob', 'phone', 'email', 'address'])
else:
self.cleaned_data['address', 'city', 'state', 'zip code'] = ''
return self.cleaned_data

def fields_required(self, fields):
for field in fields:
if not self.cleaned_data.get(field, ''):
msg = forms.ValidationError("This field is required. Custom.")
self.add_error(field, msg)


Try this. If it works then I don't think you have to override the save method in your UserAdmin. I would avoid that anyway unless absolutely necessary.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 21 '18 at 7:16

























answered Nov 21 '18 at 3:37









WhodiniWhodini

53214




53214













  • Thank you for the response! I tried the above code to fit the fields I needed for it and it didn't seem to work. It doesn't seem the fields_required method is being called correctly. I tried printing from within the method to debug, but couldn't get any output when I tried saving. Am I doing something wrong?

    – Dev
    Nov 21 '18 at 5:39













  • @Dev - what error are you getting if any? What is going on in the form? Is the model saving?

    – Whodini
    Nov 21 '18 at 6:23











  • I'm not getting back any error, however, I've been messing around with the code to better understand what's going on. So far I have: if pickup_only is true, self.fields_required(['first_name', 'last_name', 'dob', 'phone', 'email',]) --> these are the fields I want required. Then for the ELSE, I have the address fields (city, state, zip). For the fields_required method, when I print the fields it prints everything but the address fields. I tried adding 'address' to self.fields_required array and the error message spit out, but I'm obviously doing something wrong or have things mixed up.

    – Dev
    Nov 21 '18 at 6:33








  • 1





    @Dev - try just if pickup_only:

    – Whodini
    Nov 21 '18 at 7:12






  • 1





    @Dev - ah I think I know the problem. It was my mistake. See the answer again for the change. Move the fields_required method outside the clean method.

    – Whodini
    Nov 21 '18 at 7:17



















  • Thank you for the response! I tried the above code to fit the fields I needed for it and it didn't seem to work. It doesn't seem the fields_required method is being called correctly. I tried printing from within the method to debug, but couldn't get any output when I tried saving. Am I doing something wrong?

    – Dev
    Nov 21 '18 at 5:39













  • @Dev - what error are you getting if any? What is going on in the form? Is the model saving?

    – Whodini
    Nov 21 '18 at 6:23











  • I'm not getting back any error, however, I've been messing around with the code to better understand what's going on. So far I have: if pickup_only is true, self.fields_required(['first_name', 'last_name', 'dob', 'phone', 'email',]) --> these are the fields I want required. Then for the ELSE, I have the address fields (city, state, zip). For the fields_required method, when I print the fields it prints everything but the address fields. I tried adding 'address' to self.fields_required array and the error message spit out, but I'm obviously doing something wrong or have things mixed up.

    – Dev
    Nov 21 '18 at 6:33








  • 1





    @Dev - try just if pickup_only:

    – Whodini
    Nov 21 '18 at 7:12






  • 1





    @Dev - ah I think I know the problem. It was my mistake. See the answer again for the change. Move the fields_required method outside the clean method.

    – Whodini
    Nov 21 '18 at 7:17

















Thank you for the response! I tried the above code to fit the fields I needed for it and it didn't seem to work. It doesn't seem the fields_required method is being called correctly. I tried printing from within the method to debug, but couldn't get any output when I tried saving. Am I doing something wrong?

– Dev
Nov 21 '18 at 5:39







Thank you for the response! I tried the above code to fit the fields I needed for it and it didn't seem to work. It doesn't seem the fields_required method is being called correctly. I tried printing from within the method to debug, but couldn't get any output when I tried saving. Am I doing something wrong?

– Dev
Nov 21 '18 at 5:39















@Dev - what error are you getting if any? What is going on in the form? Is the model saving?

– Whodini
Nov 21 '18 at 6:23





@Dev - what error are you getting if any? What is going on in the form? Is the model saving?

– Whodini
Nov 21 '18 at 6:23













I'm not getting back any error, however, I've been messing around with the code to better understand what's going on. So far I have: if pickup_only is true, self.fields_required(['first_name', 'last_name', 'dob', 'phone', 'email',]) --> these are the fields I want required. Then for the ELSE, I have the address fields (city, state, zip). For the fields_required method, when I print the fields it prints everything but the address fields. I tried adding 'address' to self.fields_required array and the error message spit out, but I'm obviously doing something wrong or have things mixed up.

– Dev
Nov 21 '18 at 6:33







I'm not getting back any error, however, I've been messing around with the code to better understand what's going on. So far I have: if pickup_only is true, self.fields_required(['first_name', 'last_name', 'dob', 'phone', 'email',]) --> these are the fields I want required. Then for the ELSE, I have the address fields (city, state, zip). For the fields_required method, when I print the fields it prints everything but the address fields. I tried adding 'address' to self.fields_required array and the error message spit out, but I'm obviously doing something wrong or have things mixed up.

– Dev
Nov 21 '18 at 6:33






1




1





@Dev - try just if pickup_only:

– Whodini
Nov 21 '18 at 7:12





@Dev - try just if pickup_only:

– Whodini
Nov 21 '18 at 7:12




1




1





@Dev - ah I think I know the problem. It was my mistake. See the answer again for the change. Move the fields_required method outside the clean method.

– Whodini
Nov 21 '18 at 7:17





@Dev - ah I think I know the problem. It was my mistake. See the answer again for the change. Move the fields_required method outside the clean method.

– Whodini
Nov 21 '18 at 7:17




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53404568%2fchanging-a-form-fields-required-property-with-save-model-in-django-admin%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Guess what letter conforming each word

Port of Spain

Run scheduled task as local user group (not BUILTIN)