Django FormView Not Saving

╄→гoц情女王★ 提交于 2019-12-03 15:19:27

I'm new to view classes too and I had almost the same problem with Django 1.6.

You should add

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

method overriding to your RedeemReward class. This worked for me.

If you look to Django source code, you will see that there is no form saving in FormView class inheritance chain.

I am not sure if this will help or not, but I had issues finding code showing how to save the data from a FormView model. This is what I came up with. I hope it helps and you can apply it to your code.

forms.py

class JobCreateForm(forms.Form):
    title = forms.CharField(label='Job Title', max_length=500)
    number = forms.IntegerField(label='Job Number: ')
    comps = forms.ModelMultipleChoiceField(label='Comparable Sales',      
    required=False, queryset=m.ComparableSale.objects.all())
    details = forms.CharField(label='Job Details:', max_length=200,     
    required=False, widget=forms.Textarea(attrs={'rows':6, 'cols':20}))

Views.py

class JobCreateView(generic.FormView):
    template_name = 'form_templates/createjob_form.html'
    form_class = f.JobCreateForm
    model = models.Job
    success_url = '/'

    def form_valid(self, form):
        comps = form.cleaned_data['comps']
        title = form.cleaned_data['title']
        number = form.cleaned_data['number']
        details = form.cleaned_data['details']
        job = models.Job(title=title, number=number, details=details)
        job.save()
        print(comps)
        if comps != []:
            job.comps.add(*comps)
        return super(JobCreateView, self).form_valid(form)

You can write your own ModelFormView using the mixins provided by Django (specifically, the ModelFormMixin). Then your form will be saved on a successful post.

from django.views.generic.base import TemplateResponseMixin
from django.views.generic.edit import ModelFormMixin, ProcessFormView


class BaseModelFormView(ModelFormMixin, ProcessFormView):
    pass


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