gpt4 book ai didi

Django 表单 : ask for confirmation before committing to db

转载 作者:行者123 更新时间:2023-12-04 15:01:56 24 4
gpt4 key购买 nike

更新:该解决方案可以作为单独的答案找到

我正在制作一个 Django 表单,以允许用户将电视节目添加到我的数据库中。为此,我有一个 Tvshow模型,一个 TvshowModelForm我使用通用的基于类的 View CreateTvshowView/UpdateTvshowView来生成表格。

现在来了我的问题:假设用户想要向数据库添加节目,例如权力的游戏。如果这个标题的节目已经存在,我想提示用户确认这确实是一个与数据库中的节目不同的节目,如果不存在类似的节目,我想将它提交给数据库。我如何最好地处理这个确认?

我的一些实验显示在下面的代码中,但也许我的做法是错误的。我的解决方案的基础是包含一个隐藏字段 force ,如果用户确定他要提交这个数据,那么应该设置为1,这样我就可以读出这个东西是否为1来决定用户是否再次点击提交,从而告诉我他想提交存储它。

我很想听听你们对如何解决这个问题的看法。

View .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)

最佳答案

解决方案

在此处作为答案发布的想法的帮助下解决了这个问题,特别是 Alexander Larikov 和 Chris Lawlor 的想法,我想发布我的最终解决方案,以便其他人可以从中受益。

事实证明,使用 CBV 可以做到这一点,我更喜欢它。 (因为我喜欢保留所有 OOP)我还使表单尽可能通用。

首先,我制作了以下表格:

class BaseConfirmModelForm(BaseModelForm):
force = forms.BooleanField(required=False, initial=0)

def clean_force(self):
data = self.cleaned_data['force']
if data:
return data
else:
raise forms.ValidationError('Please confirm that this {} is unique.'.format(ContentType.objects.get_for_model(self.Meta.model)))

class TvshowModelForm(BaseModelForm):
class Meta(BaseModelForm.Meta):
model = Tvshow
exclude = ('user')

"""
To ask for user confirmation in case of duplicate title
"""
class ConfirmTvshowModelForm(TvshowModelForm, BaseConfirmModelForm):
pass

现在制作合适的 View 。这里的关键是发现 get_form_class 而不是使用 form_class 变量。
class EditTvshowView(FormView):       
def dispatch(self, request, *args, **kwargs):
try:
dup_list = get_object_duplicates(self.model, title = request.POST['title'])
if dup_list:
self.duplicate = True
messages.add_message(request, messages.ERROR, 'Please confirm that this show is unique.')
else:
self.duplicate = False
except KeyError:
self.duplicate = False
return super(EditTvshowView, self).dispatch(request, *args, **kwargs)

def get_form_class(self):
return ConfirmTvshowModelForm if self.duplicate else TvshowModelForm

"""
Classes to create and update tvshow objects.
"""
class CreateTvshowView(CreateView, EditTvshowView):
pass

class UpdateTvshowView(EditTvshowView, UpdateObjectView):
model = Tvshow

我希望这将使其他有类似问题的人受益。

关于Django 表单 : ask for confirmation before committing to db,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11728227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com