我一直在使用Django中的ModelForm编写注册表单。我想创建两个选择字段,一个与第一个字段链接,并由ajax刷新。使用stackoverflow中的多个示例和问题我已经构建了一个解决方案,但仍然存在一个问题。
当表单加载时,我希望第二个选择字段为空。所以我使用了一个指向none的查询集。
self.fields['company_address'].queryset = Company_address.objects.none()
当用户选择公司时,我会填充此选项字段。 ajax请求正常工作。但是当我提交表格时,我收到了一个错误:
选择有效的选择。这个选择不是可用的选择之一。
如果我不覆盖公司地址选择字段的内容,则表单验证可以正常工作。我认为问题来自表格的定义,但我找不到答案。
提前感谢您的帮助!
views.py:
def register(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/entreprises/')
else:
context = RequestContext(request)
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
print request.POST
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
registered = True
else:
print user_form.errors, profile_form.errors
else:
user_form = UserForm()
profile_form = UserProfileForm()
return render_to_response(
'entreprises/register.html',
{'user_form': user_form, 'profile_form': profile_form, 'registered': registered},
context)
forms.py:
class UserProfileForm(forms.ModelForm):
company = forms.ModelChoiceField(queryset=Company.objects.all(), required=True)
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
self.fields['company_address'].required = True
self.fields['company_address'].queryset = Company_address.objects.none()
self.fields['accepted_eula'].required = True
class Meta:
model = UserProfile
fields = ('company','company_address','accepted_eula')
widgets = {
'company_address': forms.Select(attrs={'name': 'company_address'}),
}
models.py:
class Company(models.Model):
name = models.CharField(max_length=100, verbose_name='Nom')
def __unicode__(self):
return self.name
class Meta:
verbose_name_plural = 'Entreprises'
class Company_address(models.Model):
company = models.ForeignKey(Company, verbose_name='Entreprise')
country = models.CharField(max_length=100, verbose_name='Pays')
def __unicode__(self):
return unicode(self.country)
class Meta:
verbose_name_plural = 'Adresses d\'entreprise'
class UserProfile(models.Model):
# This field is required.
user = models.OneToOneField(User, related_name='UserProfile_entreprises')
# Other fields here
company_address = models.ForeignKey(Company_address, verbose_name='Adresses d\'entreprise')
accepted_eula = models.BooleanField(default=False)
ajax.js:
$(document).ready(function(){
$('select[name=company]').change(function(){
//$('select[name=company]').children('option:first').remove();
$('select[name=company_address]').empty();
$.ajax({
type: 'POST',
url: '../get_register_company_address/',
data: {
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
company_id: $(this).val(),
},
dataType: 'json',
success: function(data){
console.log(data);
alert(data);
$.each(data, function(key, value){
$('select[name=company_address]').append('<option value="' + key + '">' + value +'</option>');
});
}
//return false;
})
})
});