Y
Y
y_o_l_k_i_n___e_g_o_r2021-03-05 09:09:56
Django
y_o_l_k_i_n___e_g_o_r, 2021-03-05 09:09:56

Error django.urls.exceptions.NoReverseMatch: Reverse for 'news-update' with arguments '('',)' not found. 1 pattern(s) tr ied: ['news/(?P[0?

When I try to go to the page for adding a comment, an error occurs:

raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'news-update' with arguments '('',)' not found. 1 pattern(s) tr
ied: ['news/(?P<pk>[0-9]+)/update$']


views.py
from django.shortcuts import render, redirect
from .models import Articles
from .forms import ArticlesForm
from .forms import CommentForm
from .models import Comment
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import DetailView, UpdateView, DeleteView


class NewsDetailView(DetailView):
    model = Articles
    template_name = 'news/details.html'
    context_object_name = 'article'


class NewsUpdateView(UpdateView):
    model = Articles
    template_name = 'news/create.html'
    form_class = ArticlesForm



class NewsDeleteView(DeleteView):
    model = Articles
    success_url = '/news/'
    template_name = 'news/delete.html'


def like(request):
    if request.method == 'POST':
        if 'add_like' in request.POST:
            return HttpResponse('Вы поставили лайк.')
        else:
            return HttpResponse('Ошибка')


def create(requests):
    error = ''
    if requests.method == 'POST':
        form = ArticlesForm(requests.POST)
        if form.is_valid():
            form.save()
            return redirect('http://127.0.0.1:8000/news/')
        else:
            error = 'нет'
            return redirect('http://127.0.0.1:8000/news/')

    form = ArticlesForm()

    data = {
        'form': form,
        'error': error
    }
    return render(requests, 'news/create.html', data)


def news_home(request):
    search_query = request.GET.get('search', '')
    if search_query:
        news = Articles.objects.filter(anons__icontains=search_query)
        news_count = Articles.objects.filter(anons__icontains=search_query).count()
    else:
        news = Articles.objects.all().order_by("-date")
        news_count = Articles.objects.all().count()
    return render(request, 'news/news_home.html', {'news': news, 'news_count': news_count})


def questions(request):
    return render(request, 'news/questions.html')


def answer(request):
    return render(request, 'news/universal_answer.html')


def create_comment(request):
    error = ''
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(request.path_info)
        else:
            error = 'нет'
            return HttpResponseRedirect(request.path_info)

    form = CommentForm()

    data = {
        'form': form
    }
    return render(request, 'news/details.html', data)


model.py
from django.db import models


class Articles(models.Model):
    title = models.CharField('Название', max_length=50)
    theme = models.CharField('тема', max_length=20)
    anons = models.CharField('Теги', max_length=250)
    full_text = models.TextField('Статья')
    date = models.DateTimeField('Дата публикации', auto_now_add=True)
    like = models.IntegerField('Лайки')

    def __str__(self):
        return f'{self.title}'


    def get_absolute_url(self):
        return f'/news/{self.id}'


    class Meta:
        verbose_name = 'Новость'
        verbose_name_plural = 'Новости'


class Comment(models.Model):
    article_id = models.CharField('Номер вашей статьи', max_length=100)
    nickname = models.CharField('Ник', max_length=100)
    comment_text = models.TextField('Текст комментария')

    def get_absolute_url(self):
        return f'/news/'

    class Meta:
        verbose_name = 'Комментарий'
        verbose_name_plural = 'Комментарии'


forms.py

from .models import Articles
from django.forms import ModelForm, TextInput, Textarea
from .models import Comment

class ArticlesForm(ModelForm):
    class Meta:
        model = Articles
        fields = ['title', 'theme', 'anons', 'full_text', 'like']
        widgets = {
            'title': TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Название статьи'
            }),
            'theme': TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Тема статьи (1-3 слова)'
            }),
            'anons': TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Теги'
            }),
            'full_text': Textarea(attrs={
                'class': 'form-control',
                'placeholder': 'Текст'
            }),
        }


class CommentForm(ModelForm):

    class Meta:
        model = Comment
        fields = ['article_id', 'nickname', 'comment_text']


urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('like', views.like, name='news-like'),
    path('questions', views.questions, name='questions'),
    path('add-comment', views.create_comment, name='add-comment'),
    path('answer', views.answer, name='answer'),
    path('', views.news_home, name='news-home'),
    path('create', views.create, name='create'),
    path('<int:pk>', views.NewsDetailView.as_view(), name='news-detail'),
    path('<int:pk>/update', views.NewsUpdateView.as_view(), name='news-update'),
    path('<int:pk>/delete', views.NewsDeleteView.as_view(), name='news-delete'),
]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stefan, 2021-03-05
@MEDIOFF

Judging by the error, you are trying to update the news without passing the id to the url

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question