[Fixed]-How to render Form instance in Django CreateView & UpdateView?

1👍

You shouldn’t be doing any of that there. The view is already taking care of calling the validation methods and redisplaying the form if validation fails; form_valid is only called if the form is already valid. Your user check should go into the form itself:

class ProductCreateForm(forms.ModelForm):
    ...
    def clean_user_email(self):
        user = User.objects.filter(username=self.cleaned_data['user_email']).first()
        if user is None:
            raise forms.ValidationError("Invalid user email specified")
        return user

For the second part, redirecting to the update view, you can do that by defining the get_success_url method; what it returns depends on the URL you have defined for the ProductUpdate view, but assuming that URL takes an id argument it would be something like this:

class ProductCreate(CreateView):
    def get_success_url(self):
        return reverse('product_update', kwargs={'id': self.instance.pk})

That leaves your form_valid method only needing to set the message on success, and you don’t even need to do that if you use the SuccessMessageMixin from contrib.messages.

Leave a comment