"如何在Django表单初始化期间提高表单验证"

2024-06-25 22:51:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个项目,其中包括不同的会议和不同的会谈与他们有关。 我想做的是检查一个条件,如果会议结束日期超过/超过当前日期/今天,则用户不能修改表单字段的标题,但可以编辑其他字段。为了检查它,我在update\u 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

Tags: thetextformdatatitletypehelpsection