Form errors not displaying in UpdateView

[亡魂溺海] 提交于 2019-12-24 20:32:22

问题


I have an UpdateView that will display a form to either create the user profile or update the user profile. It works well, however, for some reason I can't get it to show the form errors. There should be form errors based on the ValidationErrors I have put in the model form. I suspect my views.py to be the cause of the form not displaying the errors.

Here's my view:

class ProfileSettings(UpdateView):
    model = Profile
    template_name = 'profile/settings.html'
    form_class = ProfileForm
    success_url = reverse_lazy('profile:settings')

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST, request.FILES)

        if form.is_valid():
            bio = form.cleaned_data['bio']
            gender = form.cleaned_data['gender']
            avatar = form.cleaned_data['avatar']


            Profile.objects.update_or_create(user=self.request.user, defaults={'avatar':avatar, 'bio':bio, 'gender':gender})

        return HttpResponseRedirect(self.success_url)

In the template, I am displaying the errors like so: {{ form.avatar.errors }} where avatar should display an error if the image is too small, but it doesn't.


回答1:


Here, you are not returning the form errors to the template. I think you can approach like this(overriding form_valid instead of post method):

class ProfileSettings(UpdateView):
    model = Profile
    template_name = 'profile/settings.html'
    form_class = ProfileForm
    success_url = reverse_lazy('profile:settings')

   def form_valid(self, form):
      bio = form.cleaned_data['bio']
      gender = form.cleaned_data['gender']
      avatar = form.cleaned_data['avatar']
      Profile.objects.update_or_create(user=self.request.user, defaults={'avatar':avatar, 'bio':bio, 'gender':gender})
      return HttpResponseRedirect(self.success_url)

BTW, there are some flaws with this code as well. We are not using model form's save here. It would be best if we could use that. form_valid originally does that.

Also on another note, I think its best to use signals to create the user profile whenever the user is created. Here is a medium post on how to do that. In that way, you don't even need to override form_valid.

Update

Using FormView to pre-populate data:

class ProfileSettings(FormView):
    model = Profile
    template_name = 'profile/settings.html'
    form_class = ProfileForm
    success_url = reverse_lazy('profile:settings')

   def get_form_kwargs(self):
        kwargs = super(ProfileSettings, self).get_form_kwargs()
        kwargs['instance'] = self.request.user.profile  # Profile object
        return kwargs


来源:https://stackoverflow.com/questions/54490450/form-errors-not-displaying-in-updateview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!