我正在制作一个由不同会议和与之相关的不同会谈组成的项目。 我想要做的是检查一个条件,如果会议结束日期是过去/过期而不是current_date / today,那么用户就无法修改表单字段的标题,但可以编辑其他字段。所以要检查它我在update_view函数中添加了一行,其中参数是特定提案所属的会议
if not conference.end_date < datetime.now().date():
proposal.title = form.cleaned_data['title']
以上一行是有效的约束但是它是静默完成的,他会尝试更改标题,但是如果没有得到任何错误就无法做到,我想要一些方法,比如表单验证错误方法,他/她不能改变标题。 并生成我使用的动态/自定义表单
def __init__(self, conference, action="edit", *args, **kwargs):
以上这行是针对动态表单的,所以我找不到提出表单错误的有效方法。我有可能从views.py
文件中提出表单验证错误,除了forms.py
文件。不是我应该如何通知(除了表单验证)用户他们无法更改标题。
这是我的Django views.py
@login_required
@require_http_methods(['GET', 'POST'])
def update_proposal(request, conference_slug, slug):
conference = get_object_or_404(Conference, slug=conference_slug)
proposal = get_object_or_404(Proposal, slug=slug, conference=conference)
if not permissions.is_proposal_author(
user=request.user, proposal=proposal):
raise PermissionDenied
if request.method == 'GET':
form = ProposalForm.populate_form_for_update(proposal)
return render(request, 'proposals/update.html', {'form': form,
'proposal': proposal})
# POST Workflow
form = ProposalForm(conference, data=request.POST)
if not form.is_valid():
return render(request, 'proposals/update.html',
{'form': form,
'proposal': proposal,
'errors': form.errors})
# Valid Form
if not conference.end_date < datetime.now().date():
proposal.title = form.cleaned_data['title']
proposal.description = form.cleaned_data['description']
proposal.target_audience = form.cleaned_data['target_audience']
proposal.prerequisites = form.cleaned_data['prerequisites']
proposal.content_urls = form.cleaned_data['content_urls']
proposal.speaker_info = form.cleaned_data['speaker_info']
proposal.speaker_links = form.cleaned_data['speaker_links']
proposal.status = form.cleaned_data['status']
proposal.proposal_type_id = form.cleaned_data['proposal_type']
proposal.proposal_section_id = form.cleaned_data['proposal_section']
proposal.save()
return HttpResponseRedirect(reverse('proposal-detail',
args=[conference.slug, proposal.slug]))
这是我的forms.py
:
class ProposalForm(forms.Form):
'''
Used for create/edit
'''
title = forms.CharField(min_length=10,
help_text="Title of the proposal, no buzz words!",
widget=forms.TextInput(attrs={'class': 'charfield'}))
description = forms.CharField(widget=PagedownWidget(show_preview=True),
help_text=("Describe your proposal with clear objective in simple sentence."
" Keep it short and simple."))
target_audience = forms.ChoiceField(
choices=ProposalTargetAudience.CHOICES,
widget=forms.Select(attrs={'class': 'dropdown'}))
status = forms.ChoiceField(
widget=forms.Select(attrs={'class': 'dropdown'}),
choices=ProposalStatus.CHOICES,
help_text=("If you choose DRAFT people can't the see the session in the list."
" Make the proposal PUBLIC when you're done with editing the session."))
proposal_type = forms.ChoiceField(
widget=forms.Select(attrs={'class': 'dropdown'}))
proposal_section = forms.ChoiceField(
widget=forms.Select(attrs={'class': 'dropdown'}))
# Additional Content
prerequisites = forms.CharField(
widget=PagedownWidget(show_preview=True), required=False,
help_text="What should the participants know before attending your session?")
content_urls = forms.CharField(
widget=PagedownWidget(show_preview=True), required=False,
help_text="Links to your session like GitHub repo, Blog, Slideshare etc ...")
speaker_info = forms.CharField(
widget=PagedownWidget(show_preview=True), required=False,
help_text="Say something about yourself, work etc...")
speaker_links = forms.CharField(
widget=PagedownWidget(show_preview=True), required=False,
help_text="Links to your previous work like Blog, Open Source Contributions etc ...")
def __init__(self, conference, action="edit", *args, **kwargs):
super(ProposalForm, self).__init__(*args, **kwargs)
self.fields['proposal_section'].choices = _get_proposal_section_choices(
conference, action=action)
self.fields['proposal_type'].choices = _get_proposal_type_choices(
conference, action=action)
if conference.end_date < datetime.now().date():
print("This is getting pring have to raise validation error Here")
raise forms.ValidationError("You have forgotten about Fred!")
@classmethod
def populate_form_for_update(self, proposal):
form = ProposalForm(proposal.conference,
initial={'title': proposal.title,
'description': proposal.description,
'target_audience': proposal.target_audience,
'prerequisites': proposal.prerequisites,
'content_urls': proposal.content_urls,
'speaker_info': proposal.speaker_info,
'speaker_links': proposal.speaker_links,
'status': proposal.status,
'proposal_section': proposal.proposal_section.pk,
'proposal_type': proposal.proposal_type.pk, })
return form