I'm trying to save data in a model that has a m2m relation from django admin, but when I save that error, try changing the relation to foreignkey but it's not what I need, any ideas?
models.py
class Post(models.Model):
titulo = models.CharField(verbose_name="titulo del post", max_length=50)
posting = HTMLField(verbose_name="posting",blank=True,null=True)
categoria = models.ManyToManyField("posts.Categoria", verbose_name="categorias del post")
slug = models.SlugField(verbose_name="slug del post", help_text="identificador unico del post", unique=True)
admin.py
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
readonly_fields = ('slug',)
def save_model(self,request,obj,form,change):
if change:
formato = "%d%S"
es = " "
if obj.titulo.find(es) >= 1:
obj.slug = obj.titulo.replace(es, "-").lower() + "-" + obj.fecha_creacion.strftime(formato)
else:
obj.slug = obj.titulo.lower() + "-" + obj.fecha_creacion.strftime(formato)
obj.save()
What this error is telling you is that your post, doesn't actually exist in the database for a many-to-many relationship to be created.
You said you were trying to save it in the admin? I can assume that you were assigning a category to it and then trying to save it.
The way to fix this is to save the parent model first, and then add the categories.
For example:
post = Post.objects.create(titulo="Test") # Create post first
post.categoria = Categoria.objects.last() # and then assign m2m relationship
post.save() # save post.
Another way you can do this in the admin is to set
categoria = models.ManyToManyField("posts.Categoria", verbose_name="categorias del post")
to this:
categoria = models.ManyToManyField("posts.Categoria", verbose_name="categorias del post", blank=True)
Run your migrations, open the admin page and create a new post without assigning a category and click save.
Once the post has been created, you can now assign a category and click save again.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.