我需要在表单中排除'user'字段,因为'user'是将添加模型的登录用户。阅读完所有Django表单文档并在此处参考答案Django's ModelForm unique_together validation
我的django views.py仍会报告“用户”是注册用户的错误
Request Method: POST
Request URL: http://localhost:8080/flavor/add_flavor/
Django Version: 1.8
Exception Type: KeyError
Exception Value: 'user'
有人可以指出我的代码中的错误吗?
models.py
class Flavor(models.Model):
user = models.ForeignKey(UserProfile, related_name='flavors', verbose_name=_('user'))
# Attributes
name = models.CharField(max_length=100, verbose_name=_('name'), help_text=_('Enter the flavor name'))
date_created = models.DateField(_("date created"), default=datetime.date.today)
class Meta:
verbose_name = _('Flavor')
verbose_name_plural = _('Flavors')
ordering = ('name', 'user')
unique_together = ('user', 'name')
forms.py
class FlavorForm(forms.ModelForm):
class Meta:
model = Flavor
# Never use exclude keyword which involves Massive Assignment Risk
fields = ('name', 'date_created')
def __init__(self, *args, **kwargs):
# set the user as an attribute of the form which is more robust
# Always pop user from kwargs before calling super()
self.user = kwargs.pop('user')
super(FlavorForm, self).__init__(*args, **kwargs)
def clean(self):
'''
To verify the uniqueness by the unique_together fields
'''
cleaned_data = super(FlavorForm, self).clean()
if Flavor.objects.filter(name=cleaned_data.get('name',''), user=self.user).exists():
raise ValidationError(_('You have already added a flavor with this name'), code='invalid')
# Always return cleaned data
return cleaned_data
views.py
class FlavorCreateView(LoginRequiredMixin, CreateView):
model = Flavor
form_class = FlavorForm
template_name = 'flavor/add_flavor.html'
view_name = 'add_flavor'
success_url = reverse_lazy(view_name)
def get_form_kwargs(self):
'''
This injects form with keyword arguments.
'''
kwargs = super(FlavorCreateView, self).get_form_kwargs()
#Update the kwargs with the user_id
kwargs['user'] = self.request.user
return kwargs
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
form.save()
# process cleaned data
return HttpResponseRedirect(success_url)
return render(request, self.template_name, {'form': form})
答案 0 :(得分:0)
您已仔细定义get_form_kwargs
以向用户提供kwarg。但由于某种原因,你已经超越了post
;你的版本直接实例化表单,忽略了辅助方法。
很少有理由在CBV中覆盖post
,当然不是在你的情况下。删除整个方法。
(注意,这与检查唯一性无关。)
答案 1 :(得分:0)
我删除了post方法并覆盖FlavorForm中的clean方法以保证唯一性。