首页 > 解决方案 > 无法从表单创建对象

问题描述

在更改模型中用作主键的字段后,我现在在尝试从表单创建对象时收到错误消息。

我已经删除了 sqlite 数据库文件,迁移目录中的所有内容,并执行了 makemigrations 和 migrate。我不认为问题出在数据库上,而是由于我没有使用自定义主键,代码中的某些内容不再具有相同的功能。

作为 Django 的新手,我怀疑我遗漏了一些基本的东西,但不能完全确定那是什么。

视图.py

@login_required
def job_create(request):
    client = request.POST.get('client')
    form = JobForm(request.POST or None)
    form.fields['client'].initial = Client.objects.get(client_name=client)
    if request.method == "POST":
        if form.is_valid():
            form.save()
            return JsonResponse({"Success": True})`

模型.py

class Client(models.Model):
    client_name = models.CharField(max_length=255, unique=True)
    def __str__(self):
        return self.client_name

class Job(models.Model):
    client = models.ForeignKey(Client, on_delete=models.CASCADE)
    job_number = models.CharField(validators=[RegexValidator(regex='^\d{4}$', message='Invalid job number', code='invalid')], max_length=4, unique=True)
    job_description = models.CharField(max_length=30)

表格.py

class JobForm(forms.ModelForm):
    class Meta:
        model = Job
        fields = ('client', 'job_number', 'job_description',)`

上述代码未能创建对象并将其保存到数据库中。下面是我尝试使用 Django shell 重新创建它:

>>> from myproject.models import Client, Job
>>> from myproject.forms import JobForm
>>> client = Client.objects.get(client_name='John')
>>> jobform = JobForm({'client': client, 'job_description':'This is a job description', 'job_number':'4321'})
>>> jobform.errors
{'client': ['Select a valid choice. That choice is not one of the available choices.']}

数据库列

sqlite> PRAGMA table_info(myproject_job);
0|id|integer|1||1
1|job_number|varchar(4)|1||0
2|job_description|varchar(30)|1||0
3|client_id|integer|0||0

暂时解决

@login_required
def job_create(request):
    if request.method == "POST":
        client = Client.objects.get(client_name=request.POST.get("client"))
        request.POST = request.POST.copy()
        request.POST["client"] = client.id
        form = JobForm(request.POST)
        if form.is_valid():
            form.save()
            return JsonResponse({"success": "true"})

标签: djangodjango-modelsdjango-forms

解决方案


推荐阅读