I can't find a way to pass comment model to a jQuery reply form. Code on github: github. Snippet code is below.
I have two models:
User = settings.AUTH_USER_MODEL
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
class Reply(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
comment = models.ForeignKey(Comment, on_delete=models.CASCADE)
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
I create reply form by jQuery:
$(document).ready(function(){
$form = $('<form class="mt-3" method="POST" action="/reply/"></form>');
$form.append("<input type='hidden' name='csrfmiddlewaretoken' value='" + csrftoken + "'>");
$form.append('<textarea name="content" id="" cols="30" rows="5"></textarea>');
$form.append('<br />');
$form.append('<input type="button" value="Cancel" class="btn btn-dark me-2 remove-button">');
$form.append('<input type="submit" value="Post" class="btn btn-primary">');
$(".reply-button").click(function(){
$button = $(this);
$button.parent().append($form);
});
//gán s? ki?n khi s? d?ng append m?t ??i t??ng sau này
$(document).on('click', '.remove-button', function(){
$form.remove();
});
})
Action redirect to ReplyView view:
class ReplyView(View):
def post(self, request, *args, **kwargs):
# I expect something can get Comment id for reply
qs = Comment.objects.filter(id = 1)
comment = qs.first()
if request.user.is_authenticated:
r = Reply(user = request.user, comment = comment, content= request.POST.get("content"))
r.save()
return redirect("comment-page")
question from:
https://stackoverflow.com/questions/65936409/how-to-pass-comment-object-to-reply-form-in-django 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…