V
V
Vlad2021-02-19 23:10:19
Django
Vlad, 2021-02-19 23:10:19

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_]+)/$']

In fact, a lot of things have been written on the Internet on this problem, but I still did not understand how to apply the advice received there. As far as I understand, by default, after sending the news, a redirect should occur, depending on what is written in the get_absolute_url of the model responsible for the news. Also, I read that specifying the get_success_url method can help, but either I didn’t use it correctly, or it doesn’t work either.

Please explain how this problem can be corrected. I understand that it's a slug, but I don't know where to look.

This is the Form View:
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})


This is Model News:
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})


This is the url.py path for view_news:
path('news/<slug:slug>/', ViewNews.as_view(), name='view_news'),


This is the View of the Specific 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

1 answer(s)
D
Dr. Bacon, 2021-02-20
@Vlad1987

Why did your slug turn out to be an empty string?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question