First of all, I couldn’t figure out in which topic to post this issue. But I’m getting error in an HTML page, so here we go.
I’m implementing a Comment feature under User’s post in a Twitter clone Django project I’m making. I’ve created some files such as CommentForm
in forms.py, Comment()
in views.py, Comment
model in models.py & tweet_comment.html
page that’ll render page for commenting. I can’t quite figure out where it went wrong. Here are code snippets for same.
forms.py:
# For displaying Comment form
class CommentForm(forms.ModelForm):
body = forms.CharField(required=True,
widget=forms.widgets.Textarea(
attrs={
'placeholder':'Post your reply...',
'class':'form-control',
'style':'height: 150px; border-color: #484848;',
}
),
label=''
)
class Meta:
model = Comment
fields = ['content',]
models.py:
# Create Comment model
class Comment(models.Model):
user = models.ForeignKey(User, related_name='user', on_delete = models.CASCADE)
tweet = models.ForeignKey(Tweet,related_name = 'comments', on_delete = models.CASCADE)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add = True)
def __str__(self):
return '%s - %s' % (self.tweet.user, self.tweet)
views.py:
# Handling Comment under post
def tweet_comment(request, pk):
if request.user.is_authenticated:
tweet = Tweet.objects.get(id = pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit = False)
comment.user = request.user
comment.tweet = tweet
comment.save()
tweet.comment_count += 1
tweet.save()
return redirect(request.META.get('HTTP-REFERER'), id = pk)
else:
form = CommentForm()
return render(request, 'tweet_comment.html', {'form':form})
else:
messages.success(request, ('You must login to proceed.'))
return redirect('home')
& finally, tweet_comment.html:
<div class="col-sm-10">
{{ tweet.body }} <br />
<small class="text-muted">
({{ tweet.created_at }}) By
<a href="{% url 'profile' tweet.user.profile.id %}">@{{tweet.user.username}}</a>
- {{ tweet.number_of_likes }} Likes -
{% if user in tweet.likes.all %}
<a href="{% url 'tweet_like' tweet.id %}">
<i class="bi bi-heart-fill"
style="color: crimson; -webkit-text-stroke: 1px;"></i>
</a>
{% else %}
<a href="{% url 'tweet_like' tweet.id %}">
<i class="bi bi-heart" style="color: crimson; -webkit-text-stroke: 1px;"></i>
</a>
{% endif %}
</small>
</div>
I’m getting NoReverseMatch error at {% url ‘profile’ tweet.user.profile.id %} in above HTML page. I double checked urls.py file, but no issue there. Surprisingly it works as intended in admin area.