django - 无法从表单创建对象
问题描述
在更改模型中用作主键的字段后,我现在在尝试从表单创建对象时收到错误消息。
我已经删除了 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"})
解决方案
推荐阅读
- javascript - JavaScript:调用外部函数时调用Array.reduce,并且外部函数有参数
- python - 管道输入到 ipython
- python - Python列表不添加,只替换
- ios - 不在活动视图控制器上时如何在“幕后”执行转场?
- java - 无法在编译错误的主方法中引用我的方法
- android - firebase - kotlin - Hashmap 类型推断失败
- python - 如何使用 python 在 Sqlite 数据库中存储带有混合引号的字符串?
- php - 如何按天对数据库表数据进行分组并创建带有 html 表的日历?
- angular - Angular Material 电子邮件验证不适用于模板驱动的表单
- android - 创建“不断增长的涟漪”加载动画 - OutOfMemoryException