I'm Using pk in my urls but i change it to slug. But every time i added a new question in my Question model the page throws me an error like this: Reverse for 'view-Question' with arguments '('',)' not found. 1 pattern(s) tried: ['view/(?P[-a-zA-Z0-9_]+)/\Z'] but when i go to the admin and add some text in to the slug field the error is gone and i can be able to see my content in the viewQuestion template and home template. but when I also added a new one the error still appear in my home template. How can i solve this error without adding some text into the slug Field, and gives me the slug url please.
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)
my urls
path('view/<slug:slug>/', views.viewQuestion, name='view-Question'),
my home template:
<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>
I solved my problem by adding save function with slugify in the models and assigned slugify to my title field.
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)