I tried to create a form for creating a new article on the site, but this error came out. I've rechecked everything 10 times, but I don't understand what the error is.
hello/urls.py :
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='hello'),
path("cars/<slug:car_slug>/", views.car_slug, name='car_slug'),
path('cars/addpost/', views.addpost, name='addpost')
]
hello/views.py :
from django.shortcuts import get_object_or_404, render, redirect
from .models import *
from .forms import *
def index(request):
data = {}
return render(request, 'hello/index.html', data)
def car_slug(request, car_slug):
car = get_object_or_404(Cars, slug=car_slug)
data = {
'car': car
}
return render(request, 'hello/car_pk.html', data)
def addpost(request):
if request.method == 'POST':
form = AddPostForm(request.POST)
if form.is_valid():
Cars.objects.create(**form.cleaned_data)
return redirect("hello")
else:
form.add_error(None, "Ошибка добавления поста")
else:
form = AddPostForm()
data = {
'form': form,
'title': 'Добавление поста'
}
return render(request, 'hello/addpost.html', data)
hello/forms.py:
from django import forms
from .models import *
class AddPostForm(forms.Form):
title = forms.CharField(label='Название', max_length=300)
slug = forms.SlugField(label='URL', max_length=40)
content = forms.CharField(label='Характеристика', widget=forms.Textarea(attrs={'cols':60,
'rows': 10}))
is_published = forms.BooleanField(label='Состояние', required=False, initial=True)
brand = forms.ModelChoiceField(queryset=Brands.objects.all(), label="Бренды",
empty_label='Не выбрано')
hello/models.py :
from django.urls import reverse
from django.db import models
class Cars(models.Model):
title = models.CharField(max_length=255, verbose_name="Название")
slug = models.SlugField(verbose_name="URL", unique=True, db_index=True, max_length=255)
content = models.TextField(verbose_name="Характеристика", null=True)
time_create = models.DateField(verbose_name='Дата публикации', auto_now_add=True)
is_published = models.BooleanField(default=True )
brand = models.ForeignKey('Brands', on_delete=models.PROTECT)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('car_slug', kwargs={'car_slug': self.slug})
class Meta:
verbose_name = 'Машины'
verbose_name_plural = 'Машины'
class Brands(models.Model):
name = models.CharField(verbose_name="Бренды", max_length=250)
slug = models.SlugField(verbose_name="URL", unique=True, db_index=True, max_length=255)
def __str__(self):
return self.name
class Meta:
verbose_name = "Бренды"
verbose_name_plural = 'Бренды'
Here is a photo from the error:enter image description here ацукацуп ццкдлпцкдпоьйзщцозщайусз айцоащойцжаойждалойжвдлаожфывдлао жфывдлаофывджл аофыдлаофывждалофывж длаофывжд лаофывжадло ывфжалдофвыжадл фоывжадл фыовжадлф
CodePudding user response:
Does it show up in the Shell? python manage.py shell
from hello.models import Cars
Cars.objects.filter(slug='insert_car_slug').first()
# if above is empty run this:
for i in Cars.objects.all():
print('slug:', i.slug)
I think the issue might be that slug Url field.. cause it validations as a full Url. When going to that View you are only passing it addpost
which wouldn't be a full Url ..maybe just change that field to a CharField
and in the addpost View, inside the form.is_valid()
, it can be like:
if form.is_valid():
form.save()
return redirect("hello")
Might be better to do it that way so the Forms are in the Forms & Views are in the Views.
CodePudding user response:
Use this code and check
def car_slug(request, car_slug):
car = Cars.object.filter(slug=car_slug)
data = {
'car': car
}
return render(request, 'hello/car_pk.html', data)
show us the error from your terminal
CodePudding user response:
Try to test again with ASCII characters slug.
It looks like you are generating some Unicode characters which will not work with django slug https://docs.djangoproject.com/en/4.1/topics/http/urls/#path-converters.
According to their docs
slug - Matches any slug string consisting of ASCII letters or numbers, plus the hyphen and underscore characters. For example, building-your-1st-django-site.
So in order to work with Unicode slug, change your router path to:
path(r'cars/(?P<slug>[^/.] )/', views.car_slug, name='car_slug'),
Update the regex part [^/.] if you need something else to validate the path.