Home > Blockchain >  Django DetailView form dont save data
Django DetailView form dont save data

Time:12-26

I have a DetailView, and need add a form to user contact.

views.py

class ProductView(FormView, DetailView):
    model = Product
    template_name = 'product_detail.html'
    form_class = NotificationForm
    success_url = '/products/'

    def post(self, request, *args, **kwargs):
        return FormView.post(self, request, *args, **kwargs)

forms.py

class NotificationForm(ModelForm):
    ..."""some fields"""
    class Meta:
        model = Notification
        fields = [
            'usernameclient',
            'emailclient',
            'emailclient_confirmation',
            'phoneclient',
            'messageclient',
            ]

The model Notification is where is stored the data from that form

models.py

class Notification(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    ..."""some fields"""

I dont understand yet how django workflow with forms. After the submition is correct rediretc to success_url, but nothing is save in db... What is missing?

CodePudding user response:

A FormView does not save the form, a CreateView does. You can save the form with:

class ProductView(FormView, DetailView):
    model = Product
    template_name = 'product_detail.html'
    form_class = NotificationForm
    success_url = '/products/'

    def form_valid(self, form):
        form.save()
        return super().form_valid(form)
  • Related