更新:解决方案可以作为单独的答案找到
我正在制作一个 Django 表单以允许用户将电视节目添加到我的数据库中。为此,我有一个Tvshow
模型,TvshowModelForm
并且我使用基于类的通用视图CreateTvshowView
/UpdateTvshowView
来生成表单。
现在我的问题来了:假设一个用户想要在数据库中添加一个节目,例如权力的游戏。如果该标题的节目已经存在,我想提示用户确认这确实是与数据库中的节目不同的节目,如果不存在类似的节目,我想将其提交给数据库。我如何最好地处理此确认?
我的一些实验显示在下面的代码中,但也许我做错了。我的解决方案的基础是包含一个隐藏字段force
,如果用户收到提示是否确定要提交此数据,则应将其设置为 1,以便我可以读出此事物是否为 1 以决定用户是否再次单击提交,从而告诉我他想要存储它。
我很想听听你们对如何解决这个问题的看法。
视图.py
class TvshowModelForm(forms.ModelForm):
force = forms.CharField(required=False, initial=0)
def __init__(self, *args, **kwargs):
super(TvshowModelForm, self).__init__(*args, **kwargs)
class Meta:
model = Tvshow
exclude = ('user')
class UpdateTvshowView(UpdateView):
form_class = TvshowModelForm
model = Tvshow
template_name = "tvshow_form.html"
#Only the user who added it should be allowed to edit
def form_valid(self, form):
self.object = form.save(commit=False)
#Check for duplicates and similar results, raise an error/warning if one is found
dup_list = get_object_duplicates(Tvshow, title = self.object.title)
if dup_list:
messages.add_message(self.request, messages.WARNING,
'A tv show with this name already exists. Are you sure this is not the same one? Click submit again once you\'re sure this is new content'
)
# Experiment 1, I don't know why this doesn't work
# form.fields['force'] = forms.CharField(required=False, initial=1)
# Experiment 2, does not work: cleaned_data is not used to generate the new form
# if form.is_valid():
# form.cleaned_data['force'] = 1
# Experiment 3, does not work: querydict is immutable
# form.data['force'] = u'1'
if self.object.user != self.request.user:
messages.add_message(self.request, messages.ERROR, 'Only the user who added this content is allowed to edit it.')
if not messages.get_messages(self.request):
return super(UpdateTvshowView, self).form_valid(form)
else:
return super(UpdateTvshowView, self).form_invalid(form)