A
A
Anton2016-12-29 11:57:02
Django
Anton, 2016-12-29 11:57:02

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()

Comment form:
class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('body',)

A variable is available
{{ request.user.username }}
in the template If you write in the template
<form>
  <input type="hidden" name="name" value="{{ request.user.username }}">
        {{ comment_form.as_p }}
...
</form>

, then in the view cleaned_data will only have the value of the field specified in the comment form - body. name will have a KeyError.
Can you tell me how to initialize the name field of a comment with the value available in the template? How to change the comment form?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
clojurerabbit, 2016-12-29
@Gambetto

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 question

Ask a Question

731 491 924 answers to any question