简体   繁体   中英

Django get PK dynamically from views.py

I have a view that renders a comment form along with a template:

views.py

def news(request):
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = Article.objects.get(pk=2)
            print(comment.post)
            comment.author = request.user.username
            comment.save()
            return HttpResponseRedirect('')
    else:
        form = CommentForm()
    return render(request, '../templates/news.html', context={"form": form})

models.py

class Comment(models.Model):
    post = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comments', blank=True)
    author = models.TextField()
    text = models.TextField()

    def __str__(self):
        return self.text

forms.py

class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ('text',)

In views.py, where comment.post is getting assigned to Article objects, I want the pk to be applied dynamically. I tried doing it in the templates, where putting {{ article.pk }} in the templates output the right pk for the Article object but I wasn't sure how I'd go about applying it to my form.

The templates look simple: Article object, below it a comment form.

The problem is simple, I want the news(request) function to dynamically apply the pk of the current Article object in order to make the comment go to the right post.

You can either use the path if it's unique or you can just add a hidden field and set the article pk as value:

<input name="post" type="hidden" value={{ article.pk }} />

And your form:

class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ('text', 'post')

and you can access it from validated data in view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM