I'm starting with Django. I have 3 models, a parent class "Cliente" and two child classes, "Persona" and "Empresa".
models.py
class Cliente(models.Model):
idcliente = models.AutoField(unique=True, primary_key=True)
direccion = models.CharField(max_length=45L, blank=True)
telefono = models.CharField(max_length=45L, blank=True)
email = models.CharField(max_length=45L, blank=True)
def __unicode__(self):
return u'Id: %s' % (self.idcliente)
class Meta:
db_table = 'cliente'
class Empresa(models.Model):
idcliente = models.ForeignKey('Cliente', db_column='idcliente', primary_key=True)
cuit = models.CharField(max_length=45L)
nombre = models.CharField(max_length=60L)
numero_ingresos_brutos = models.CharField(max_length=45L, blank=True)
razon_social = models.CharField(max_length=45L, blank=True)
def __unicode__(self):
return u'CUIT: %s - Nombre: %s' % (self.cuit, self.nombre)
class Meta:
db_table = 'empresa'
class Persona(models.Model):
idcliente = models.ForeignKey('Cliente', db_column='idcliente', primary_key=True)
representante_de = models.ForeignKey('Empresa', null=True, db_column='representante_de', blank=True, related_name='representa_a')
nombre = models.CharField(max_length=45L)
apellido = models.CharField(max_length=45L)
def __unicode__(self):
return u'Id: %s - Nombre completo: %s %s' % (self.idcliente, self.nombre, self.apellido)
class Meta:
db_table = 'persona'
I want to manage a class and its parent in the same view. I want to add, edit and delete "Cliente" and "Persona"/"Cliente" in the same form. Can you help me?
There is a good example in the Documentation Here.
I wrote this based on the documentation, so it is untested.
def manage_books(request, client_id):
client = Cliente.objects.get(pk=client_id)
EmpresaInlineFormSet = inlineformset_factory(Cliente, Empresa)
if request.method == "POST":
formset = EmpresaInlineFormSet(request.POST, request.FILES, instance=author)
if formset.is_valid():
formset.save()
# Do something. Should generally end with a redirect. For example:
return HttpResponseRedirect(client.get_absolute_url())
else:
formset = EmpresaInlineFormSet(instance=client)
return render_to_response("manage_empresa.html", {
"formset": formset,
})
Related
I have a models with FileField for videos.
When i upload only one video i can return it with this code in the view.py:
def cours(request, id, slug):
c = Cours.objects.get(id=id, slug=slug)
p = Plan_simple.objects.get(cours=c)
return render(request, 'upload/cours.html', locals())
But when i upload two or more videos whith formset, and i change get fuction by filter it doesn't work:
def cours(request, id, slug):
c = Cours.objects.get(id=id, slug=slug)
p = Plan_simple.objects.filter(cours=c)
return render(request, 'upload/cours.html', locals())
the models.py
class Cours(models.Model):
titre = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
auteur = models.CharField(max_length=42)
comment = models.TextField(null=True)
link = models.CharField(max_length=100)
date = models.DateTimeField(default=timezone.now, verbose_name="Date de parution")
categorie = models.ForeignKey('Categorie', on_delete=models.CASCADE)
def save(self, *args, **kwargs):
self.slug = slugify(self.titre)
super(Cours, self).save(*args, **kwargs)
class Meta:
verbose_name = "cours"
db_table = "cours"
ordering = ['date']
class Plan_simple(models.Model):
partie = models.CharField(blank=True, max_length=100)
date = models.DateTimeField(default=timezone.now, verbose_name="Date de parution")
vid = models.FileField(upload_to='file/', blank=True, null = True)
cours = models.ForeignKey(Cours, related_name = "plan_simple", on_delete=models.CASCADE)
def __str__(self):
return self.partie
class Meta:
db_table = "plan_simple"
Can you help me?
Thanks
The issue is with this line. It does not request anything from the database. It only specifies a filter.
p = Plan_simple.objects.filter(cours=c)
You should change it to this...
p = Plan_simple.objects.filter(cours=c).all()
I have an object with foreign key Edp. A user can have several RespostaEdp as per the design. However, when printing the list I want to group them by user. Any ideas on how to get this done? I tried the solution below but I cannot access user values.
#teacher_required
def listarRespostasEDA(request):
edpsTodas = Edp.objects.all()
title = 'Estruturas Digitais Pedagogicas'
template = 'edp/listarEDArespondida.html'
edps = list()
for edp in edpsTodas:
if edp.respostas.all().count() != 0:
# if not edp.respostas.none:
edps.append(edp)
return render(request, template, {'title': title, 'edps': edps})
def listaAlunosResponderamEdp(request, slug):
edp = get_object_or_404(Edp, slug=slug)
# respostas = RespostaEdp.objects.filter(edp=edp)
lista = list()
respostas = RespostaEdp.objects.filter(edp=edp).values('aprendiz').distinct().order_by('aprendiz')
for r in respostas:
for k,v in r.items():
aluno = User.objects.filter(pk=v)
lista.append(aluno)
print (lista)
return render(request, 'edp/teste.html', {'lista':lista})
class RespostaEdp(models.Model):
edp = models.ForeignKey(Edp, verbose_name='Edp', related_name='respostas', on_delete=models.CASCADE)
video_embedded = EmbedVideoField(blank=True, null=True)
texto = models.TextField('Texto', blank=True)
video = models.FileField(upload_to='video/', storage=upload_storage, default="media/none.mp4")
aprendiz = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='aluno', related_name='respostaAluno', on_delete=models.CASCADE)
# aprendiz = models.ForeignKey(Student, verbose_name='aprendiz ', related_name='respostaAprendiz', on_delete=models.CASCADE)
created_at = models.DateTimeField('Criado em', auto_now_add=True)
updated_at = models.DateTimeField('Atualizado em', auto_now=True)
def __str__(self):
return self.edp.titulo + " - " + self.aprendiz.username
def iniciar(self):
self.save()
#models.permalink
def get_absolute_url(self):
return ('edp:detalhe_edp_resposta', (), {'slug': self.slug})
class Meta:
verbose_name = 'Resposta Estrutura Digital de Aprendizagem'
verbose_name_plural = 'Resposta Estrutura Digital de Aprendizagem'
ordering = ['-created_at']
class User(AbstractUser):
eh_aluno = models.BooleanField(default=False)
eh_professor = models.BooleanField(default=False)
And here is the models of the users:
class User(AbstractUser):
eh_aluno = models.BooleanField(default=False)
eh_professor = models.BooleanField(default=False)
class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
def __str__(self):
return self.user.username
I'm trying to insert data in my ManyToMany relationship but i don't get it, my form always is invalidad.
I get this error when i try to save the form "The view apps.alumno.views.SubirActividad didn't return an HttpResponse object. It returned None instead."
Models:
class Alumno(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
nocontrol = models.CharField(max_length=8)
grupo = models.ForeignKey(Grupo, on_delete=models.CASCADE)
def __str__(self):
return '{}'.format(self.nocontrol)
class Actividad(models.Model):
nombre = models.CharField(max_length=50)
descripcion = models.CharField(max_length=100)
asignatura = models.ForeignKey(Asignatura, on_delete=models.CASCADE)
alumno = models.ManyToManyField(Alumno, through='ActividadAlumno', through_fields=('actividad', 'alumno'),)
def __str__(self):
return '{}'.format(self.nombre)
class ActividadAlumno(models.Model):
actividad = models.ForeignKey(Actividad, on_delete=models.CASCADE)
alumno = models.ForeignKey(Alumno, on_delete=models.CASCADE)
fecha = models.DateField(auto_now_add=False, auto_now=True)
documento = models.FileField(upload_to='asignatura/tarea/')
calificacion = models.IntegerField(null=True)
Form:
class ActividadAlumnoForm(forms.ModelForm):
class Meta:
model = ActividadAlumno
fields = [
'actividad',
'alumno',
'documento',
'calificacion',
]
labels = {
'actividad': 'Fecha de entrega',
'alumno': 'Entregado',
'documento': 'Estado',
'calificacion': 'Calificacion',
}
widgets = {
'actividad': forms.Select(),
'alumno': forms.Select(),
'documento': forms.ClearableFileInput(),
'calificacion': forms.NumberInput(),
}
View:
def SubirActividad(request, id_actividad):
actividad = Actividad.objects.get(id=id_actividad)
if request.method=='POST':
form = ActividadAlumnoForm(request.POST)
if form.is_valid():
form.save()
return redirect('alumno:asignatura_detalle', clave=form.instance.asignatura.clave)
else:
alumno = Alumno.objects.get(user=request.user)
form = ActividadAlumnoForm(initial={'actividad': actividad, 'alumno':alumno})
return render(request, 'alumno/actividad_subir.html', {'form':form})
I have searched 20-30 posts and I did not find anything useful. I am to store data to database by selecting values from HTML file or form in view. Please tell me how I can achieve this. what code I am missing. Thanks in advance for Help.
view.py
def blog_list(request):
form = AttendanceForm()
if request.method == "POST":
form1 = AttendanceForm(request.POST)
if form1.is_valid:
form1.save()
return render(request, 'blog/blog_list.html',{
'form1':form1,
})
return render(request, 'blog/blog_list.html',{
'form':form,
})
my forms.py
class AttendanceForm(forms.ModelForm):
action = forms.ModelChoiceField(queryset=Action.objects.all(), empty_label="-----------", required=True)
employee = forms.ModelChoiceField(queryset=Employee.objects.all(), empty_label="-----------", required=True)
class Meta:
model = Action
fields = ['employee','action']
my model.py
class Action(models.Model):
action_name = models.CharField(max_length = 100)
def __str__(self):
return self.action_name
class Employee(models.Model):
employee_id = models.AutoField(primary_key = True)
employee_name = models.CharField(max_length = 100)
def __str__(self):
return self.employee_name
class Attendance(models.Model):
u = models.ForeignKey(Employee)
action = models.ForeignKey(Action)
action_time = models.DateTimeField(default=timezone.now())
In Python you need to call methods by using parentheses.
if form.is_valid():
form.save()
It is working fine after these changes in Model:
class Action(models.Model):
action_name = models.CharField(max_length = 100)
def __str__(self):
return self.action_name
class Employee(models.Model):
employee_id = models.AutoField(primary_key = True)
employee_name = models.CharField(max_length = 100)
def __str__(self):
return self.employee_name
class Attendance(models.Model):
employee = models.ForeignKey(Employee)
action = models.ForeignKey(Action)
action_time = models.DateTimeField(default=timezone.now())
In models.py:
class Client(AbstractBaseUser):
username = models.CharField(max_length=32, unique=True)
email = models.EmailField('email address', unique=True, db_index=True)
avatar = models.ImageField('avatar', upload_to='avatars')
id = id(object)
class Order(models.Model):
class Meta():
db_table = 'order'
short_desc = models.CharField(max_length=30)
subject = models.ForeignKey(Subject, blank=True)
user_id = models.ForeignKey('Client', to_field='id', related_name='client_id', default='0', blank=True)
performer_id = models.ForeignKey('Client', to_field='id', related_name='performer_id', default='0', blank=True)
worktype = models.ForeignKey(Type, blank=True)
level = models.IntegerField(default=0, blank=True)
readiness = models.BooleanField(default=False, blank=True)
description = models.TextField(max_length=2000, blank=True)
file = models.FileField(upload_to='orderfiles', blank=True)
#maxdate = models.DateField(blank=True)
addate = models.DateField(auto_now=True, blank=True)
price = models.IntegerField(max_length=10, blank=True)
responses = models.IntegerField(blank=True)
In forms.py:
class AddOrderForm(forms.ModelForm):
short_desc = forms.CharField(widget=forms.TextInput,label="Краткое описание(послужит именем)")
subject = forms.ModelChoiceField(queryset=Subject.objects.all(), label="Предмет")
worktype = forms.ModelChoiceField(queryset=Type.objects.all(), label="Тип")
level = forms.IntegerField(widget=forms.TextInput,label="Уровень сложности (от 1 до 5)")
description = forms.CharField(widget=forms.TextInput,label="Полное описание")
#maxdate = forms.DateField(widget=forms.TextInput,label="maxdate")
price = forms.IntegerField(widget=forms.TextInput,label="Ваша цена")
responses = forms.IntegerField(widget=forms.TextInput,label="Кол-во ответов на заказ")
class Meta:
model = Order
fields = ['short_desc', 'level', 'description', 'price', 'responses', 'subject', 'worktype']
In views.py:
def addorder(request, user_id):
"""
Adding Order view
"""
if request.POST:
form = AddOrderForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
return redirect('/')
auth1 = auth.get_user(request).username
return render_to_response('customer.html', { 'form': form,'username' : auth1}, context_instance=RequestContext(request))
I need the field user_id in class Order to be initialized immediately after adding order(). Where should I do it and in which way? I need something like this logic: Client adds an Order through AddOrderForm and then user_id field of just added object of class Order has to be initialized with an object of class Client, whose id equals user_id in parameters of addorder() function.
You can do that using commit=False while saving the form. This is typical way of saving the object using model form which has fewer fields.
def addorder(request, user_id):
"""
Adding Order view
"""
if request.POST:
form = AddOrderForm(request.POST)
if form.is_valid():
order = form.save(commit=false)
order.client_id = Client.objects.get(id=user_id)
order.save()
return redirect('/')
else:
return redirect('/')
auth1 = auth.get_user(request).username
return render_to_response('customer.html',
{ 'form': form,'username' : auth1},
context_instance=RequestContext(request))
Disclaimer: Handle errors e.g. Client.objects.get() may fail. Use appropriate fields to search.