Slug returns Reverse for 'view-Question' with arguments '('',)' not found.尝试了 1 种模式

Slug returns Reverse for 'view-Question' with arguments '('',)' not found. 1 pattern(s) tried

我在 url 中使用 pk,但我将其更改为 slug。但是每次我在我的 Question 模型中添加一个新问题时,页面都会抛出这样的错误: Reverse for 'view-Question' with arguments '('', )' 未找到。尝试了 1 种模式:['view/(?P[-a-zA-Z0-9_]+)/\Z'] 但是当我转到管理员并在 slug 字段中添加一些文本时,错误消失了,我可以在查看问题模板和主页模板。但是当我也添加一个新的时,错误仍然出现在我的主页模板中。我如何在不向 slug 字段中添加一些文本的情况下解决此错误,请给我 slug url。

class Question(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, blank=False, null=False)
    body = RichTextField(blank=False, null=False) 
    category = models.CharField(max_length=50, blank=False, null=False)
    slug = models.SlugField(unique=True, max_length=50)

    def __str__(self):
        return str(self.title)

def viewQuestion(request, slug):
    question = get_object_or_404(Question, slug=slug)
    answers = Answer.objects.filter(post_id=question)
    context = {'question':question, 'answers':answers}
    return render(request, 'viewQuestion.html', context)

class My_Question(LoginRequiredMixin, CreateView):
    model = Question
    fields = ['title', 'body', 'category']
    template_name = 'question.html'
    success_url = reverse_lazy('index')

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super (My_Question, self).form_valid(form)

我的url我的

path('view/<slug:slug>/', views.viewQuestion, name='view-Question'),

我的主页模板:

    <div class="container">
    <div class="row justify-content-center">
        {% for question in list_of_question reversed %}
        <div class="col-md-4">
            <div class="card my-3">
                <div class="card-header">
                <p class="card-title">{{question.user.username.upper}}</p>
                </div>
                <div class="card-body">
                    <a href="{% url 'view-Question' question.slug %}" style="text-decoration: none;">
                        <p class="card-title">{{question.title}}</p>
                    </a>
                    <h5>{{question.category}}</h5>
                </div>
            </div>
        </div>
        {%endfor%}
    </div>
</div>

我通过在模型中添加带有 slugify 的保存功能并将 slugify 分配给我的标题字段解决了我的问题。

from django.utils.text import slugify

class Question(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, blank=False, null=False)
    body = RichTextField(blank=False, null=False) 
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    slug = models.SlugField(unique=True, max_length=200)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Question, self).save(*args, **kwargs)