Answer the question
In order to leave comments, you need to log in
How to fix NoReverseMatch at / error?
Good afternoon!
When submitting via the news form, Django throws the following error:
Reverse for 'view_news' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['news/(?P<slug>[-a-zA-Z0-9_]+)/$']
class CreateNews(CreateView):
form_class = NewsForm
template_name = 'news/add_news.html'
extra_context = {'unwanted_link': template_name}
def get_success_url(self):
return reverse('view_news', kwargs={'slug': self.object.slug})
class News(models.Model):
title = models.CharField(max_length=150, verbose_name='Наименование')
slug = models.SlugField(max_length=200, db_index=True, unique=True, verbose_name='URL')
content = models.TextField(blank=True, verbose_name='Контент')
created_at = models.DateTimeField(auto_now_add=True, verbose_name='Дата публикации')
updated_at = models.DateTimeField(auto_now=True, verbose_name='Обновлено')
photo = models.ImageField(upload_to='photos/%Y/%m/%d/', verbose_name='фото', blank=True)
is_published = models.BooleanField(default=True, verbose_name='Опубликовано')
category = models.ForeignKey('Category', on_delete=models.PROTECT, verbose_name='Категория')
views = models.IntegerField(default=0)
def get_absolute_url(self):
return reverse('view_news', kwargs={'slug': self.slug})
path('news/<slug:slug>/', ViewNews.as_view(), name='view_news'),
class ViewNews(DetailView):
model = News
context_object_name = 'news_item'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['unwanted_link'] = 'news/news_detail.html'
return context
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question