这是Model类
class Album(models.Model):
name = models.CharField(max_length=256)
public = models.BooleanField(default=False)
user = models.ForeignKey(get_user_model())
class Meta:
unique_together = (("name", "user"),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('photos:index')
这是视图
class Create(CreateView):
model = Album
fields = ['name', 'public']
form_class = AlbumCreateForm
def form_valid(self, form):
form.instance.user = self.request.user
return super(Create, self).form_valid(form)
这是表格
class AlbumCreateForm(ModelForm):
class Meta:
model = Album
fields = ['name', 'public']
labels = {'name': '', 'public': 'Public'}
def __init__(self,*args, **kwargs):
super(AlbumCreateForm, self).__init__(*args, **kwargs)
self.fields['name'].widget = forms.TextInput(
attrs={'placeholder': 'name'})
我可以很好地制作相册,但我想做的是防止为特定用户创建重复的相册。例如,如果user1已经创建了album1,则他应该无法创建另一个名为album1的专辑。
我能做到的地方是AlbumCreateForm。但是AlbumCreateForm对当前用户没有任何了解。知道如何实现它吗?
答案 0 :(得分:2)
将用户传递给表单 - 通过添加此方法将其添加到表单kwargs中以查看:
def get_form_kwargs(self, *args, **kwargs):
kwargs = super(Create, self).get_form_kwargs(*args, **kwargs)
kwargs['user'] = self.request.user
return kwargs
让用户填写表单并检查:
def __init__(self,*args, **kwargs):
self.user = kwargs.pop('user') # this line added
super(AlbumCreateForm, self).__init__(*args, **kwargs)
self.fields['name'].widget = forms.TextInput(
attrs={'placeholder': 'name'})
def clean(self):
if Album.objects.filter(user=self.user).exists():
raise forms.ValidationError('Error description')