簡體   English   中英

Django UpdateView表單驗證錯誤未顯示在模板中

[英]Django updateview form validation error not displaying in templates

我在views.py中有一個更新視圖

class UserProfileUpdateView(LoginRequiredMixin, UpdateView):
    model = UserProfile
    template_name = 'my-account/my_profile_update.html'
    form_class = UserProfileUpdateForm

    def get_context_data(self, **kwargs):

        context = super(UserProfileUpdateView, self).get_context_data(**kwargs)
        context['form'] = UserProfileUpdateForm(instance=UserProfile.objects.get(user=self.request.user))
        return context

    def get_object(self):
        return get_object_or_404(UserProfile, user=self.request.user)

forms.py中

class UserProfileUpdateForm(forms.ModelForm):

    username = forms.CharField(label='Username')
    video = forms.URLField(required=False, label='Profile Video')

    def clean_username(self):
        username = self.cleaned_data['username']
        if UserProfile.objects.filter(username=username).exists():
            print "This print is working"
            raise forms.ValidationError('Username already exists.')
        return username 

    class Meta:     
        model = UserProfile

但是在模板形式錯誤不顯示

在模板home.html中

{{ form.username.errors }}

輸入現有用戶時,驗證並引發錯誤,但不顯示在form.username.errors中。 我嘗試打印表格,但是在表格上沒有發現錯誤。 這是updateview的問題嗎?

提前致謝..

更新視圖已經在上下文中包含該表單。 但是,在您的get_context_data方法中,您將表單替換為

    context['form'] = UserProfileUpdateForm(instance=UserProfile.objects.get(user=self.request.user))

此表單不限制發布數據,因此它永遠不會有任何錯誤。

您不需要包括此行。 您的get_object方法應足以確保您的視圖使用正確的用戶。

就您而言, UserProfileUpdateForm已與UserProfile綁定,因此您無需更改context數據。

但是,在嘗試通過遵循doc給表單提供一些初始值時,我面臨着完全相同的問題。 所以在get_context_data ,我有

context['form'] = self.form_class(instance=self.post, initial={"tags":",".join([tag.name for tag in self.post.tags.all()])})

這將用與逗號分隔的帖子相關的標簽列表預填充form.tags

在深入研究UpdateView源代碼后,我設法解決了該問題。 在第81行,

def form_invalid(self, form):
    """
    If the form is invalid, re-render the context data with the
    data-filled form and errors.
    """
    return self.render_to_response(self.get_context_data(form=form))

如果表單無效並且包含錯​​誤,它將使用綁定的表單調用get_context_data 我必須將此表單傳遞給模板,而不是我在get_context_data方法中指定的表單。 為了實現這一點,我們需要對get_context_data進行一些更改。

def get_context_data(self, **kwargs):
    context = super(PostUpdate, self).get_context_data(**kwargs)
    if 'form' in kwargs and kwargs['form'].errors:
        return context
    else:
        context['form'] = self.form_class(instance=self.post, initial={"tags":",".join([tag.name for tag in self.post.tags.all()])})
        return context

如果存在包含錯誤的表單,它將直接將其傳遞給模板。 否則,請使用我們提供的服務。

我相信還有其他解決方案。 如果有的話請發表。 它將幫助其他人學習Django。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM