django - 获取用户表中注册的不同用户名并使用表单集将其保存为外键
问题描述
我正在保存一个具有如下表单集的动态表单:-
表格.py
AuthorFormset = modelformset_factory(
Author,
fields=('title','content','due_date','author' ),
extra=1,
widgets={'title': forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Author Name here'}),
'content': forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Description'}),
'due_date': forms.DateInput(attrs={
'class': 'form-control', 'placeholder': 'Date'}),
'author': forms.TextInput(attrs={
'class': 'form-control author-input',
'placeholder': 'Participants'
}),
“作者”字段之一,我使用自动完成模型从用户表中获取用户名。在我的 models.py 中,我将作者保存为 Author 表中的外键。类作者(models.Model):
title = models.CharField(max_length=100, null=True)
content = models.TextField(null=True)
due_date = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
class Meta:
db_table = 'author'
def __str__(self):
return self.author.username
但是在调试时,我发现 POST 请求中返回的 formset 对象对作者字段显示'id': 'none'。我认为“作者”输入字段只接受 userId 而不是用户名。我是 django 的新手,我不知道如何从 User 模型中保存userId中的用户名。请指出我正确的方向。
视图.py
def create_book_with_authors(request):
template_name = 'store/create_with_author.html'
if request.method == 'GET':
formset = AuthorFormset(request.GET or None)
elif request.method == 'POST':
formset = AuthorFormset(request.POST)
if formset.is_valid(): # Error saying that formset is not valid
for form in formset:
# so that `book` instance can be attached.
author = form.save(commit=False)
author.save()
return redirect('mom:home')
return render(request, template_name, {'formset': formset})
解决方案
我认为由于作者是 ForeignKey,因此您必须使用 TextInput 的值获取实际的用户实例,然后将该实例另存为值。尝试:
if formset.is_valid(): # Error saying that formset is not valid
for form in formset:
# so that `book` instance can be attached.
author = form.save(commit=False)
a = Author.objects.get(username=author.author) # Or however you get the unique author
author.author = a
author.save()
推荐阅读
- gcloud - 将服务暴露给静态地址
- moodle - 设置moodle vidtrack完成
- sql - 组织 SQL 脚本 - 最佳实践
- r - R - 避免使用 lubridate hms 和 ggplot 显示毫秒
- php - wordpress 插件致命错误:未捕获的错误:在 null 上调用成员函数 update()
- angular - Angular 4 - 向阻止滚动的“鼠标滚轮”事件添加了非被动事件侦听器。
- python - 将具有离散特征索引的数组传递给python中的mutual_info_classif
- javascript - 谷歌反应地图 - 如何更改控制颜色?
- batch-file - 如何删除不包括父文件夹和第一个子文件夹的文件夹?
- sql-server - 在 MS SQL 2016 上对 NewID() 奇怪的结果进行排序