Hi, I am building a Q and A app and would like to create a view where users can see the specific questions they posted on the platform, but I am facing some challenges. The questions for each user are blank, I would like to know how to solve this challenge.
Here is my model.py
from django.urls import reverse
from django.contrib.auth.models import User
from django.utils.text import slugify
from django.db import models, IntegrityError
class Question(models.Model):
question_id = models.BigAutoField(unique=True, primary_key=True)
title = models.CharField(max_length=100)
content = models.TextField(verbose_name="")
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)
slug = models.SlugField(max_length=100, blank=True, null=True, unique=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("question_detail", args=[int(self.question_id), str(self.slug)])
def generate_slug(self):
if not self.slug:
base_slug = slugify(self.title)
self.slug = base_slug
counter = 1
while True:
try:
self.save()
break # Successfully saved with a unique slug
except IntegrityError:
self.slug = f"{base_slug}-{counter}"
counter += 1
def save(self, *args, **kwargs):
self.generate_slug()
super(Question, self).save(*args, **kwargs)
class Meta:
ordering = ["-created_at"]
class Answer(models.Model):
content = models.TextField(null=True, blank=True, verbose_name="")
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True, null=True, blank=True)
question = models.OneToOneField(
Question, on_delete=models.SET_NULL, null=True, blank=True
)
def __str__(self):
return self.content
class Meta:
permissions = (("can_answer", "Can Answer Questions"),)
This i the question URL
path(
"user_questions/",
UserQuestionsListView.as_view(),
name="user_questions",
),
And this is the template
{% extends "qa/base_generic.html" %} {% block content %}
<div class="container">
<h1 class="display-4">Questions</h1>
<ul class="list-group">
{% for question in user_questions %}
<li class="list-group-item">
<h3>
<a href="{{ question.get_absolute_url }}" class="custom-link"
>{{ question.title }}</a
>
</h3>
<em> <p class="text-muted">Posted on: {{ question.created_at}}</p></em>
</li>
{% endfor %}
</ul>
</div>
<style>
.custom-link {
color: #007bff;
text-decoration: none;
font-weight: bold;
}
.custom-link:hover {
text-decoration: underline;
}
</style>
{% endblock %}
Here is the UserQuestionsListView
class UserQuestionsListView(LoginRequiredMixin, ListView):
model = Question
template_name = "qa/user_questions.html"
context_object_name = "user_questions"
def get_queryset(self):
return Question.objects.filter(author=self.request.user)