Django-空表单无法保存在数据库中 [英] Django - empty form cannot be saved in database

查看:70
本文介绍了Django-空表单无法保存在数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,用户在其中指定 lawyer-spec 并将数据保存到数据库。但是我收到一个错误,

I have a form in which, user specifies lawyer-spec and save the data to the database. However I get an error that

**null value in column "lawyer_spec" violates not-null constraint**

因此,表单中的数据未正确处理。

So the data from the form is not processed properly.

编辑:

mthod form_invalid 打印空行,然后打印两个数字( pk和 lawyer_id)

mthod form_invalid prints empty line, and then two numbers ('pk' and 'lawyer_id')

forms.py

class MakeAppointmentForm(forms.ModelForm):
    first_name = forms.CharField(required=True)

    class Meta:
        model = CalendarAppointmentsReserved
        fields = ['case']

    def __init__(self, *args, lawyer_id, pk, **kwargs):
        super().__init__(*args, **kwargs)
        lawyer_id_from_kwargs = lawyer_id
        lawyer_specs = LawyersSpec.objects.filter(lawyer=lawyer_id_from_kwargs)

        choices = [(spec.lawyer_spec, dict(CASES)[spec.lawyer_spec]) for spec in lawyer_specs]

        self.fields['case'].choices = choices

views.py

@method_decorator(user_required, name='dispatch')
class MakingAppointmentView(CreateView):
    template_name = "make_appointment.html"
    form_class = TestPy.forms.MakeAppointmentForm
    model = TestPy.models.CalendarAppointmentsReserved

    def get_form_kwargs(self):
        pk = self.kwargs.get('pk')
        self.kwargs = super().get_form_kwargs()

        self.kwargs = {'lawyer_id': self.request.session['lawyer_id'], 'pk': pk}

        self.kwargs.update(self.kwargs)  # self.kwargs contains all url conf params
        return self.kwargs


    def form_invalid(self, form):
        print(form.errors)
        print(self.kwargs.get('pk'))
        print(self.kwargs.get('lawyer_id'))
        return redirect('home')


    def form_valid(self, form):
        calendar_model = TestPy.models.CalendarFreeSlot.objects.get(pk=self.kwargs.get('pk'))
        calendar_model.is_available = False
        calendar_model.save()

        self.object = form.save(commit=False)
        self.object.users_id = self.request.user
        self.object.calendar_free_id = calendar_model
        self.request.session['free_calendar_id'] = calendar_model.pk
        self.request.session['lawyer_id'] = calendar_model.lawyer_id.pk

        self.object.save()
        return redirect('home')

models.py

class LawyersSpec(models.Model):
    lawyer = models.ForeignKey('MyUser', on_delete=models.PROTECT)
    lawyer_spec = models.SmallIntegerField(choices=CASES)

class CalendarAppointmentsReserved(models.Model):
    calendar_free_id = models.ForeignKey('CalendarFreeSlot', on_delete=models.PROTECT) 
    users_id = models.ForeignKey('MyUser', on_delete=models.PROTECT) 
    case = models.SmallIntegerField(choices=CASES)

如何正确处理数据并保存在数据库中?

How can I process the data properly and save in the database?

推荐答案

您在这里犯了一个关键错误:

You're making a crucial mistake here:


  • 您的 CreateView 用于 CalendarAppointmentsReserved 模型

  • 您的表单用于 LayerersSpec 模型

  • Your CreateView is for a CalendarAppointmentsReserved model
  • Your form is for a LawyersSpec model

这是不可能的,因为为模型<$ c $创建视图c> A 期望同一模型 A ModelForm

That's not possible, because the create view for model A is expecting a ModelForm for the same model A.

将表单更改为此:

class MakeAppointmentForm(forms.ModelForm):
    first_name = forms.CharField(required=True)

    class Meta:
        model = CalendarAppointmentsReserved
        fields = ['case']

    def __init__(self, *args, lawyer_id, pk, **kwargs):
        super().__init__(*args, **kwargs)
        lawyer_specs = LawyersSpec.objects.filter(lawyer=lawyer_id)
        choices = [(spec.lawyer_spec, dict(CASES)[spec.lawyer_spec]) for spec in lawyer_specs]
        self.fields['case'].choices = choices

现在,您无需分配 self.object.case

Now in your view you don't need to assign self.object.case anymore.

您还将在 self.kwargs 通过直接为其指定字典的> get_form_kwargs()方法。然后 self.kwargs.update(self.kwargs)不执行任何操作,您将自己更新一个字典。因此,您在此处丢失了所有POST数据。正确的方法是这样的:

You're also resetting self.kwargs in your get_form_kwargs() method by assigning it a dictionary directly. And then self.kwargs.update(self.kwargs) does nothing, you're updating a dict with itself. So you loose all the POST data here. The proper way to do it is like this:

def get_form_kwargs(self):
    form_kwargs = super().get_form_kwargs()  # don't mess up self.kwargs
    pk = self.kwargs.get('pk')
    form_kwargs.update({'lawyer_id': self.request.session['lawyer_id'], 'pk': pk})
    return form_kwargs

这篇关于Django-空表单无法保存在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆