[英]Django: How to create form with ForeignKey field (input as CharField)
I have created two models Article and Author as this:我创建了两个模型文章和作者,如下所示:
model.py模型.py
class Article(models.Model):
title = models.CharField(max_length=200)
content = models.TextField(max_length = 5000)
author = models.ForeignKey('Author', on_delete=models.CASCADE)
class Author(models.Model):
author_name = models.CharField(max_length=200)
author_intro = models.TextField(max_length = 3000)
And I am trying to create a form that lets user input Article information *(including title, content, author only).我正在尝试创建一个表单,让用户输入文章信息 *(仅包括标题、内容、作者)。 So that whenever user input an author, that input data is stored in both author
(in Article model) and author_name
(in Author model).因此,无论何时用户输入作者,输入数据都存储在author
(在文章模型中)和author_name
(在作者模型中)中。 Is this possible to do?这是可能的吗? I can not seem to get it working.我似乎无法让它工作。 Here's what I tried:这是我尝试过的:
form.py:表单.py:
class articleForm(forms.ModelForm):
author = forms.ModelMultipleChoiceField(queryset=Author.objects.all())
class Meta:
model = Article
fields = ['title']
widgets = {
'content': forms.Textarea(attrs={'cols': 75, 'rows': 50})}
class authorForm(forms.ModelForm):
class Meta:
model = Author
fields = ['author_name']
views.py:视图.py:
def compose_article(request):
form_article = articleForm(request.POST or None)
if form_article.is_valid():
instance = form_article.save(commit=False)
instance.save()
context = {
"ArtileForm":form_article,
}
return render(request,"Upload.html",context)
Thanks in advance!提前致谢!
You need to provide the author name input as a char field and handle getting or creating the author manually.您需要将作者姓名输入作为字符字段提供,并手动获取或创建作者。 You also need to set unique=True
on author_name
.您还需要在author_name
上设置unique=True
。 Try a form like this:试试这样的表格:
class ArticleForm(forms.ModelForm):
author = forms.CharField()
class Meta:
model = Article
fields = ['title', 'author', 'content']
widgets = {
'content': forms.Textarea(attrs={'cols': 75, 'rows': 50}),
}
def save(self, commit=True):
author, created = Author.objects.get_or_create(
author_name=self.cleaned_data['author'],
defaults={'author_intro': ''}
)
self.cleaned_data['author'] = author.id
return super(ArticleForm, self).save(commit)
And a view like this:和这样的观点:
from django.views.generic.edit import CreateView
class ArticleFormView(CreateView):
form_class = ArticleForm
template_name = 'Upload.html'
# You can skip this method if you change "ArtileForm" to "form"
# in your template.
def get_context_data(self, **kwargs):
cd = super(ArticleFormView, self).get_context_data(**kwargs)
cd['ArtileForm'] = cd['form']
return cd
compose_article = ArticleFormView.as_view()
what worked for me was to move the code from the save to clean对我有用的是将代码从保存移动到清理
def clean(self):
group, created = Ideas_Group.objects.get_or_create(
category_text=self.cleaned_data.get('group'))
self.cleaned_data['group'] = group
return super(IdeasForm, self).clean()
and then in the views.py was just a regular process然后在 views.py 中只是一个常规过程
def post(self, request):
if request.method == 'POST':
form = IdeasForm(request.POST)
if form.is_valid():
ideapost = form.save(commit=False)
ideapost.save()
I've just arrived here about a similar problem.我刚到这里遇到类似的问题。 Starting with your code, in my case, I've added "__id".从您的代码开始,就我而言,我添加了“__id”。
class articleForm(forms.ModelForm):
author__id = forms.IntegerField(...
Printing this part of the form.打印表格的这一部分。 (27 is the id of my testcase.) (27 是我的测试用例的 ID。)
<tr><th><label for="id_author">Author:</label></th><td><select name="author" required id="id_author">
<option value="">---------</option>
<option value="27" selected>Author</option>
</select></td></tr>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.