Python Django. Нет URL-адреса для перенаправления. Либо укажите URL, либо определите метод get_absolute_url в модели
Hello everyone. I'm facing a problem that I can't solve. I have get_absolute_url defined in the models, but for some reason I get an error: "No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model." Here is the code (models.py):
class Vendor(models.Model):
name = models.CharField(max_length=255, default='')
vendor_type = models.ForeignKey('VendorType', on_delete=models.PROTECT, null=False)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse_lazy('motherboard_vendors')
class VendorType(models.Model):
class Type(models.IntegerChoices):
MOTHERBOARD = 1, 'Материнская плата'
CPU = 2, 'Процессор'
STORAGE = 3, 'Накопитель памяти'
VIDEOCARD = 4, 'Видеокарта'
RAM = 5, 'Оперативная память'
MONITOR = 6, 'Монитор'
SOFTWARE = 7, 'Программное обеспечение'
PROJECTOR = 8, 'Проектор'
PRINTER = 9, 'Принтер'
name = models.CharField(choices=Type.choices, max_length=255, default='')
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse_lazy('motherboards')
forms.py:
class AddMotherboardVendorForm(forms.ModelForm):
class Meta:
model = Vendor
fields = ['name']
widgets = {
'name': forms.TextInput(attrs={'class': 'form-input'}),
}
def clean_name(self):
name = self.cleaned_data['name']
if len(name) > 50:
raise ValidationError("Длина превышает 50 символов")
return name
def save(self):
vendor = super().save(commit=False)
vendor.vendor_type_id = VendorType.Type.MOTHERBOARD
vendor.save()
return vendor.get_absolute_url()
views.py:
class AddMotherboardVendor(LoginRequiredMixin, CreateView):
form_class = AddMotherboardVendorForm
template_name = "home/motherboard/addmotherboardvendor.html"
title_page = 'Добавление производителя материнской платы'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = self.title_page
return context
urls.py:
path('motherboard_vendors/add_motherboard_vendor/', views.AddMotherboardVendor.as_view(), name='add_motherboard_vendor')
There used to be another entity Vendor:
class MotherboardVendor(models.Model):
motherboard_vendor_name = models.CharField(max_length=255, default='')
def __str__(self):
return self.motherboard_vendor_name
def get_absolute_url(self):
return reverse_lazy('motherboard_vendors')
But as
soon as I replaced it, an error started to pop up: "No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.". I tried deleting the database with migrations and recreating it, but I didn't see anything new. I recreated the whole project, but it didn't help either. On all other models, where there is get_absolute_url - everything works correctly. Maybe someone who has encountered this and can tell me what the problem is?I tried adding def get_success_url() to the AddMotherboardVendorForm, but got the same error