I have the following error:
The logic that I use in Django is based on a model and the ModelForm class. Here is the model:
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from django.urls import reverse
class Ingredient(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return f'{self.name}'
class Recipe(models.Model):
slug = models.SlugField(null=True, unique=True, blank=True, editable=False)
title = models.CharField(null=False, max_length=100)
description = models.CharField(null=False, max_length=250)
preparation = models.TextField(null=False)
score = models.IntegerField(null=True, validators=[MinValueValidator(1), MaxValueValidator(5)])
last_update = models.DateField(auto_now=True)
presentation_image = models.ImageField(upload_to='images', null=True, blank=True)
ingredients = models.ManyToManyField(Ingredient)
def __str__(self):
return f'{self.slug}, {self.title}, {self.description}, {self.preparation}, {self.score}, {self.last_update}, {self.presentation_image}, {self.ingredients}'
Here is the RecipeForm:
from django import forms
from django.core.validators import MinValueValidator, MaxValueValidator
from .models import Recipe
from .models import Ingredient
class RecipeForm(forms.ModelForm):
class Meta:
model = Recipe
exclude = ['slug', 'last_update']
widgets = {
'preparation': forms.Textarea()
}
labels = {
'title': 'Title',
'description': 'Description',
'preparation': 'Preparation',
'score': 'Score',
'presentation_image': 'Presentation Image',
'ingredients': 'Ingredients'
}
I understand that the problem is based on the fact that no slug is generated (since it is None in the shell). Since my path for a single recipe is based on a slug then Django simply tells me "Hey dude, no slug to work with, sorry... It's on you...".
This problem have occured when I tried to add a new recipe from the Django admin instead of my page (Here I can add the recipe but the slug will be None. In Django admin I just get the error)
What I can't understand is why the slug is not generated? The user must not enter a slug by it's own. It should be generated based on the title. User must not have a saying in it at the moment.
Can you please explain to me where my logic fails and what's the mistake so I can understand the issue clearly so I can avoid these rookie mistakes in the future?