'how to collect the pk of the model that you are currently viewing (django)
hey I'm trying to make a question and answer project for django, how do I get the pk of the question that I am viewing right now to send an answer? I already set it up so that the url of the answer has /answer/pk of the question but I dont know how to get that info so the code knows where to post the model, how do I do that? also here is my code, thanks!
views.py
class AnswerForm(SuccessMessageMixin, CreateView):
template_name = 'forum/answer-question.html'
model = Answer
form_class = AnswerForm
success_message = 'Success!'
def form_valid(self, form, pk=None):
form.instance.question_id = Question.objects.only('id')
form.instance.user = self.request.user
form.save()
return super().form_valid(form)
forms.py
class AnswerForm(ModelForm):
class Meta:
model = Answer
fields = ['detail']
exclude = ('user', 'add_time')
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('questions/', views.QuestionsView.as_view(), name='questions'),
path('ask/', views.AskForm.as_view(), name='ask'),
path('answer/', views.AnswerForm.as_view(), name='answer'),
path('answer/<pk>', views.AnswerForm.as_view(), name='answer_with_pk'),
path('question/<pk>', views.QuestionDetailView.as_view(), name='detail'),
path('save-text', views.WriteCommentAnswerView.as_view(), name='save-text'),
path('save-vote', views.SaveVoteView.as_view(), name='save-vote'),
]
models.py
class Answer(VoteModel, models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
detail = models.TextField()
add_time = models.DateTimeField(auto_now_add=True)
def get_absolute_url(self):
return f"/questions/"
def __str__(self):
return self.detail
Solution 1:[1]
In AnswerForm you get all url parameters added to self because of base class DetailedView. In your case "self.pk". You can then add anything to the context for the html rendering by implementing get_context_data:
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
# Add in the publisher
context['question_pk'] = self.pk
return context
See https://docs.djangoproject.com/en/4.0/topics/class-based-views/generic-display/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
