我已覆盖Django Registration app
并在注册表单中添加了一些自定义字段。
我添加了一个功能,在选择特定值时,必填字段将隐藏。我现在成功了,我想删除required
我的特定字段。
我在下面尝试了许多其他方法,但是从下拉列表中选择了值,必填字段隐藏但是点击了signup
按钮我得到了
我的代码:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$('#id_type').change(function(){
var type = $(this).val();
if(type === "dealer"){
$('#id_dealership_name').show();
$("label[for='id_dealership_name']").show();
}
else{
$("#id_dealership_name").removeAttr("required")
$('#id_dealership_name').hide();
$("label[for='id_dealership_name']").hide();
}
});
</script>
编辑1
form.py
class DealerForm(forms.ModelForm):
class Meta:
model = Dealer
exclude = ('user', 'site')
def __init__(self, *args, **kwargs):
super(DealerForm, self).__init__(*args, **kwargs)
self.fields['dealership_name'].required = False
编辑2
views.py
class DealerRegistrationView(RegistrationView):
def __init__(self, **kwargs):
super(DealerRegistrationView, self).__init__(**kwargs)
RegistrationForm.base_fields.update(DealerForm.base_fields)
form_class = RegistrationForm
def register(self, form):
new_user = super(DealerRegistrationView, self).register(form)
if Site._meta.installed:
site = Site.objects.get_current()
if form.cleaned_data['type'] == "dealer":
new_dealer = Dealer(
user=new_user,
site_id=site.id,
whatsapp=form.cleaned_data['username'],
dealership_name=form.cleaned_data['dealership_name'],
).save()
答案 0 :(得分:0)
I resolved it by making changes in forms.py and then applied JavaScript
and it worked for me.
from django import forms
from registration.forms import RegistrationForm, RegistrationFormUniqueEmail
class DealerForm(RegistrationFormUniqueEmail):
type = forms.ChoiceField(required=True, choices=(
('dealer', 'Dealer'),
('marketing_agent', 'Marketing Agent'),
('private_seller', 'Private Seller'),
('virtual_dealer', 'Virtual Dealer')
))
dealership_name = forms.CharField(required=False, max_length=50)
subdomain_name = forms.CharField(required=False, max_length=50)
banner_image = forms.ImageField(required=False)
logo_image = forms.ImageField(required=False)