Answer the question
In order to leave comments, you need to log in
How to pass value from template to model via form?
Models: user (User model) and his comments.
class Comment(models.Model):
name = models.ForeignKey(User, related_name='comments')
body = models.TextField()
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('body',)
{{ request.user.username }}
<form>
<input type="hidden" name="name" value="{{ request.user.username }}">
{{ comment_form.as_p }}
...
</form>
Answer the question
In order to leave comments, you need to log in
This isn't exactly what you're asking, of course, but I wouldn't keep the name hidden, but just do it like this:
...
if form.is_valid():
comment = form.save(commit=False)
comment.user = request.user
comment.save()
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question