问题
I have created two models Article and Author as this:
model.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). Is this possible to do? I can not seem to get it working. Here's what I tried:
form.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:
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!
回答1:
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
. 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()
回答2:
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
def post(self, request):
if request.method == 'POST':
form = IdeasForm(request.POST)
if form.is_valid():
ideapost = form.save(commit=False)
ideapost.save()
来源:https://stackoverflow.com/questions/35764551/django-how-to-create-form-with-foreignkey-field-input-as-charfield