Reputation: 798
I try to update a ForeignKey field of a model in django form. I want a user not to write his name into a input field as an author of the article that he wrote but his id
must be saved in the field in Article
model. In my html-form I display only a button with hidden input. But in my views.py I write that the form should take user.id
and put it in the 'article_author'
field.
Unfortunately, I've got no updates into table. What am I doing wrong?
my model:
class Article(models.Model):
article_pub_date = models.DateField(default=None,null=True,verbose_name="Дата публикации")
article_title = models.CharField(max_length=70, verbose_name="Заголовок", null=True)
article_text = models.TextField(verbose_name="Текст", null=True)
article_author = models.ForeignKey(User, verbose_name='Автор', blank=True, null=True)
my views.py
def article_detail(request, article_id):
user = request.user
article = get_object_or_404(Article, pk=article_id)
author_form = ArticleForm(request.POST or None, instance=article, initial={'article_author': user.id})
if author_form.is_valid():
author_form.save()
else:
return redirect('/')
my forms.py
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ('article_author',)
widgets = {'article_author': forms.HiddenInput()}
and my template:
<form method="POST" action="">
{% csrf_token %}
{{ author_form.as_p }}
<input type="submit" value="BIND" class="btn">
</form>
Upvotes: 4
Views: 2458
Reputation: 73450
Try one of the following:
if author_form.is_valid():
article = author_form.save(commit=False)
article.article_author = user
# article.article_author_id = user.id #w ill work as well
article.save()
else:
return redirect('/')
or in the form instantiation:
initial={'article_author_id': user.id}
Upvotes: 2