django 在/posts/posts/in/uthi-group/comment/中配置不正确

sqyvllje  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(77)

所以我有一个项目称为星星社会项目这个项目是类似于一个socail媒体,你可以张贴和创建组,但这个项目你只能张贴时,你在一个组。所以我得到一个错误消息,这是不熟悉我的标题。解决方案,我已经尝试过的是我添加了绝对网址到我的职位模型,但我仍然得到这个错误,现在我很沮丧,我我不知道该怎么办。所以为什么我得到这个错误是因为我试图创建一个评论部分,当我点击添加评论时,我得到了错误消息。所以我在这里要求有人帮助我,因为我真的不熟悉这个错误,我刚刚学习django大约2个月了。

models.py

from django.contrib.auth import get_user_model
from django.db import models
from groups.models import Group
from misaka import html
from django.urls import reverse
from django.utils import timezone
from django.shortcuts import get_object_or_404

User = get_user_model()

class Post(models.Model):

    user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now=True)
    message = models.TextField()
    message_html = models.TextField(editable=False)
    group = models.ForeignKey(Group, related_name='posts', null=True, blank=True, on_delete=models.CASCADE)

    def __str__(self):
        return self.message

    def save(self, *args, **kwargs):

        self.message_html = html(self.message)
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse(
            'posts:single',
            kwargs={
                'username': self.user.username,
                'pk': self.pk
            }
        )

    class Meta:

        ordering = ['-created_at']

class Comment(models.Model):

    post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
    username = models.CharField(max_length=50)
    text = models.TextField()
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.text

    # This is my solution on the error but im still getting that error message
    def get_absolute_url(self):
        return reverse('groups:single', kwargs={'slug': self.slug})

字符串
集团models.py

from django.contrib.auth import get_user_model
from django import template
from django.db import models
from django.utils.text import slugify
from misaka import html
from django.urls import reverse

User = get_user_model()
register = template.Library()

class Group(models.Model):

    name = models.CharField(max_length=255, unique=True)
    slug = models.SlugField(allow_unicode=True, unique=True)
    description = models.TextField(blank=True, default="")
    description_html = models.TextField(editable=False, blank=True, default="")
    members = models.ManyToManyField(User, through='GroupMember')

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):

        self.slug = slugify(self.name)
        self.description_html = html(self.description)
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('groups:single', kwargs={'slug': self.slug})

    class Meta:
        ordering = ['name']

class GroupMember(models.Model):

    user = models.ForeignKey(User, related_name='user_groups', on_delete=models.CASCADE)
    group = models.ForeignKey(Group, related_name='memberships', on_delete=models.CASCADE)

    def __str__(self):
        return self.user.username

    class Meta:

        unique_together = ('user', 'group')


urls.py

from django.urls import path
from posts import views

app_name = 'posts'

urlpatterns = [
    path('', views.PostList.as_view(), name='all'),
    path('by/<username>/', views.UserPost.as_view(), name='for_user'),
    path('by/<username>/<int:pk>/', views.PostDetail.as_view(), name='single'),
    path('new/', views.CreatePost.as_view(), name='create'),
    path('delete/<int:pk>/', views.DeletePost.as_view(), name='delete'),
    path('posts/in/<slug>/comment/', views.AddComment.as_view(), name='add_comment'),
]


集团urls.py

from django.urls import path
from groups import views

app_name = 'groups'

urlpatterns = [
    path('new/', views.CreateGroup.as_view(), name='create'),
    path('posts/in/<slug>/', views.SingleGroup.as_view(), name='single'),
    path('', views.ListGroups.as_view(), name='all'),
    path('join/<slug>/', views.JoinGroup.as_view(), name='join'),
    path('leave/<slug>/', views.LeaveGroup.as_view(), name='leave'),
]


views.py

class AddComment(LoginRequiredMixin, generic.CreateView):

    model = Comment
    template_name = 'posts/comment_form.html'
    fields = '__all__'


_post.html

<div class="media">
    <h3 class="mr-5"><a href="{% url 'posts:for_user' username=post.user.username %}">@{{ post.user.username }}</a></h3>

    <div class="media-body">
        <strong>{{ post.user.username }}</strong>
        <h5>{{ post.message_html|safe }}
            <time class="time"><a href="{% url 'posts:single' username=post.user.username pk=post.pk %}">{{ post.created_at }}</a></time>

            {% if post.group %}
                <span class="group-name">in <a href="#">{{ post.group.name }}</a></span>
            {% endif %}
        </h5>

        <h2>Comment...</h2>
        {% if not post.comments.all %}
            <h3>No comment yet...</h3>
            <a href="{% url 'posts:add_comment' slug=group.slug %}">Add Comment</a>
        {% else %}  
            <a href="{% url 'posts:add_comment' slug=group.slug %}">Add Comment</a>
            <br>
            {% for comment in post.comments.all %}
            <br>
                {{ comment.text }}
            <br>
                <strong>
                    {{ comment.username }} -
                    {{ comment.created }}
                </strong>
            <br>
            {% endfor %}
        {% endif %}

        <div class="media-footer">
            {% if user.is_authenticated and post.user == user and not hide_delete %}
                <a class="btn btn-simple" href="{% url 'posts:delete' pk=post.pk %}" title="delete"><span class="fa fa-remove text-danger" aria-hidden="true"></span><span class="text-danger icon-label">Delete</span></a>
            {% endif %}
        </div>
    </div>
</div>


comment_form.html

{% extends 'posts/post_base.html' %}

    {% block post_content %}
        <h2>Add Comment</h2>

        <form id="commentForm" method="POST">
            {% csrf_token %}
            {{ form.as_p }}
            <button class="btn btn-large btn-primary">Add Comment</button>
        </form>
    {% endblock %}

cpjpxq1n

cpjpxq1n1#

出现此错误是因为您试图访问注解模型中的slug

def get_absolute_url(self):
    return reverse('groups:single', kwargs={'slug': self.slug})

字符串
和注解模型不包含任何名为slug的列有两种方法可以处理此错误,首先可以在Comment模型中创建slug字段并从url传递slug值。第二种方法是在urls.py中添加id而不是slug,如下图所示

app_name = 'posts'
    
urlpatterns = [
   ....
   path('posts/in/<id>/comment/', views.AddComment.as_view(), name='add_comment'),
]


在您的posts models.py中,

class Comment(models.Model):
    ........
    def __str__(self):
        return self.text

    def get_absolute_url(self):
        return reverse('posts:add_comment', kwargs={'id': self.id})


你正试图得到未定义的手段在你的groups应用程序的反向没有这样的类型的网址

相关问题