无法从表单创建对象

时间:2019-01-21 20:11:43

标签: django django-models django-forms

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

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

作为Django的新手,我怀疑我缺少一些基本知识,但无法完全确定是什么。

views.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})`

models.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)

forms.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"})

0 个答案:

没有答案