Hi everyone !
In order to improve my Django skills, I decided to try to create a very basic forum app.
For the moment being I have three templates :
-
forums.html
-
topics.html
-
posts.html
My issue is with the second template “topics.html” :
Indeed, if you take a look at this section :
<tbody> {% for topic in topic_model %} <tr> <td><a href="{{topic.topic_name}}">{{topic.topic_name}}</a></td> <td>{{topic.topic_description}}</td> <td>{{topic.topic_author}}</td> <td>{{topic.topic_answers}}</td> <td>{{topic.topic_last_answer_by}}</td> </tr> {% endfor %} </tbody>
I’ve got an issue because if the topic_name is “Hello World”, this will result in :
localhost:8000/forums/topics/Hello World/
Which is not correct, what I would like is to automatically convert this to :
localhost:8000/forums/topics/hello-world/
Here is the full code for my models.py and views.py files :
models.py
class Topic(models.Model):
topic_forum = models.ForeignKey(Forum, related_name="topic_forum", default=None, on_delete=models.CASCADE)
topic_name = models.CharField(max_length=40)
topic_description = models.CharField(max_length=80, blank=True)
topic_author = models.ForeignKey(User, related_name="topic_author", on_delete=models.CASCADE)
topic_creation_date = models.DateTimeField(auto_now_add=True)
topic_answers = models.IntegerField(default=0)
topic_last_answer_by = models.ForeignKey(User, related_name="topic_last_answer_by", on_delete=models.CASCADE)
def __str__(self):
return self.topic_name
views.py
def forum_page(request, forum_name):
template_path = os.path.join("forums","topics.html")
forum = Forum.objects.get(forum_name__iexact=forum_name)
topic_model = Topic.objects.filter(topic_forum=forum)
processTopicName(topic_model)
return render(request,template_path,{"forum":forum, "topic_model": topic_model})
In the above view, you can see that I have added a processTopicName function :
def processTopicName(topic_model):
#Process topic name
new_topic_model = []
for topic in topic_model:
topic_new_name = topic_name.replace(" ","-")
topic_new_name = topic_new_name.lower()
new_topic_model.append(topic_new_name)
return topic_new_name
But I don’t really know how to implement it the right way…
Thank you in advance for your help