'Submit form post from another view with input field
I am relatively new to Django and I'm making a small "social" project. It basically consists of user profiles, and on those profiles you can post "comments".
I have a view that displays the comments each user has, and a separate view that allows you to post comments. This works as expected.
The problem I am facing right now is the following. - I have an < input type=text > field in the view to view comments, and I want to be able to post a comment from there and have it saved in the database. I have tried grabbing the post kwargs in the form, but I couldn't get it to work correctly nonetheless have it save automatically. How can I get this done?
Here is the code that I have so far.
Comments view:
class CommentsView(auth_mixins.LoginRequiredMixin, views.ListView):
model = ProfileComments
template_name = 'comments/comments_view.html'
paginate_by = 5
def get_queryset(self):
receiver = PROFILE_MODEL.objects.get(pk=self.kwargs['pk'])
if receiver:
return self.model.objects.filter(receiver=receiver)
return None
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
receiver = PROFILE_MODEL.objects.get(pk=self.kwargs['pk'])
if receiver:
context.update({
'receiver': receiver
})
return context
View to post comments:
class CreateCommentView(auth_mixins.LoginRequiredMixin, views.CreateView):
form_class = CommentsForm
template_name = 'comments/post_comment.html'
@staticmethod
def get_profile_model_by_pk(pk):
return PROFILE_MODEL.objects.get(pk=pk)
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['author'] = self.request.user.userprofile
kwargs['receiver'] = self.get_profile_model_by_pk(self.kwargs['pk'])
return kwargs
def get_success_url(self):
return reverse_lazy('comments', kwargs={'pk': self.kwargs['pk']})
And this is the template for viewing comments, here is the code for the input I'm using:
<div style="width: 1310px ;margin: 0 auto">
<form class="col-12 col-lg-auto mb-3 mb-lg-0 me-lg-3"
method="POST" action="{% url 'post comment' pk=receiver.pk %}">
{% csrf_token %}
<input type="text" name="post_comment_text"
class="form-control" placeholder="Leave a comment" aria-label="Leave a comment">
</form>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
