I'd like the view only show the "personajes" that were created by the current user.
If I I'm not understanding wrong, what I have to do is filter the choices, depending who is the current user logged in, before the form render.
I guess that what I have to edit is the queryset
argument in ModelChoiceField(**kwargs)
but I don't know where I have to do this.
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Autor(models.Model):
nombre = models.CharField(max_length=40)
apellido = models.CharField(max_length=40)
usuario = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True)
def __str__(self):
return "%s %s" % (self.nombre, self.apellido)
class Personaje(models.Model):
nombre = models.CharField(max_length=40)
personalidad = models.CharField(max_length=20)
creador = models.ForeignKey(Autor, on_delete=models.CASCADE)
def __str__(self):
return "nombre: %s Creador: %s" % (self.nombre, self.creador)
class Historia(models.Model):
autor = models.ForeignKey(Autor, on_delete=models.CASCADE)
personajes = models.ManyToManyField(Personaje)
desarrollo = models.TextField()
views.py
I'm not catching the request.user.id yet by simplicity (I'm really stuck with the filter thing) I know how to do that, hardcoding the user id will be just fine.
from django.shortcuts import render
from django.views.generic import CreateView
from core.models import Historia
# Create your views here.
class CrearHistoria(CreateView):
model = Historia
fields = ['personajes', 'desarrollo']
template_name = 'core/crear_historia.html'