models.py
class Paciente(models.Model):
expediente = models.CharField(primary_key=True,max_length=10)
nombre = models.CharField(max_length=100)
paterno = models.CharField(max_length=100)
materno = models.CharField(max_length=100)
estado = models.ForeignKey(Estado,related_name='Estado_set')
municipio = models.ForeignKey(Municipio,related_name='Municipio_set')`enter code here`
localidad = models.ForeignKey(Localidad,related_name='Localidad_set')
calle = models.CharField(max_length=100)
noExterior = models.IntegerField(max_length=4)
noInterior = models.CharField(max_length=4,blank=True, null=True)
...
def __unicode__(self):
name = "%s - %s %s %s"%(self.expediente,self.nombre,self.paterno,self.materno)
return name
class FamParentesco(models.Model):
GENERO = (
('F', 'Femenino'),
('M', 'Masculino')
)
paciente = models.ForeignKey(Paciente)
nombre = models.CharField(max_length=100)
edad = models.IntegerField(max_length=2,blank=True, null=True)
sexo = models.CharField(max_length=1, choices=GENERO)
parentesco = models.ForeignKey(Parentesco)
escolaridad = models.ForeignKey(Escolaridad,blank=True, null=True)
ocupacion = models.ForeignKey(Ocupacion,blank=True, null=True)
estadoCivil = models.ForeignKey(EstadoCivil,blank=True, null=True)
ingreso = models.DecimalField(max_digits=5,decimal_places=2,blank=True, null=True)
def __unicode__(self):
return self.nombre
class EgresoMensual(models.Model):
paciente = models.OneToOneField(Paciente, unique=True, related_name='egresomensual')
renta = models.DecimalField(max_digits=8,decimal_places=2,blank=True, null=True)
alimentacion = models.DecimalField(max_digits=8,decimal_places=2,blank=True, null=True)
luzaguacomb = models.DecimalField(max_digits=8,decimal_places=2,blank=True, null=True)
educacion = models.DecimalField(max_digits=8,decimal_places=2,blank=True, null=True)
vestidop = models.DecimalField(max_digits=8,decimal_places=2,blank=True, null=True)
pasajes = models.DecimalField(max_digits=8,decimal_places=2,blank=True, null=True)
abonos = models.DecimalField(max_digits=8,decimal_places=2,blank=True, null=True)
otros = models.DecimalField(max_digits=8,decimal_places=2,blank=True, null=True)
total = models.DecimalField(max_digits=8,decimal_places=2,blank=True, null=True)
class OtrosIngresos(models.Model):
paciente = models.OneToOneField(Paciente)
propiedades = models.BooleanField()
detalleprop = models.CharField(max_length=100)
rentas = models.BooleanField()
negocio = models.BooleanField()
detallearticulos = models.CharField(max_length=100)
class Vivienda(models.Model):
paciente = models.OneToOneField(Paciente)
tipo = models.CharField(max_length=100)
piso = models.BooleanField()
techo = models.BooleanField()
ventana = models.BooleanField()
habitaciones = models.IntegerField()
agua = models.BooleanField()
excreta = models.BooleanField()
basura = models.BooleanField()
energia = models.CharField(max_length=100)
hacinamiento = models.BooleanField()
promiscuidad = models.BooleanField()
class Observaciones(models.Model):
paciente = models.OneToOneField(Paciente)
observaciones = models.TextField()
forms.py
from django import forms
from django.forms import ModelForm
from django.forms.models import inlineformset_factory
from .models import EgresoMensual, Observaciones, OtrosIngresos, Paciente, FamParentesco, Vivienda
class PacienteForm(forms.ModelForm):
class Meta:
model = Paciente
ParentescoFormSet = inlineformset_factory(Paciente, FamParentesco)
class EgresoMensualForm(forms.ModelForm):
class Meta:
model = EgresoMensual
exclude = ('paciente')
class ObservacionesForm(forms.ModelForm):
class Meta:
model = Observaciones
class OtrosIngresosForm(forms.ModelForm):
class Meta:
model = OtrosIngresos
class ViviendaForm(forms.ModelForm):
class Meta:
model = Vivienda
views.py
from django.http import HttpResponseRedirect
from django.views.generic import CreateView
from .models import Paciente, FamParentesco
from .forms import PacienteForm, ParentescoFormSet, ObservacionesForm, ViviendaForm, OtrosIngresosForm, EgresoMensualForm
class PatientCreateView(CreateView):
template_name = 'add_expediente.html'
model = Paciente
form_class = PacienteForm
success_url = 'success/'
def get(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form_class()
family_form = ParentescoFormSet()
egreso_form = EgresoMensualForm()
return self.render_to_response(
self.get_context_data(form=form,
family_form=family_form,
egreso_form = egreso_form))
def post(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
family_form = ParentescoFormSet(self.request.POST)
egreso_form = EgresoMensualForm(self.request.POST, instance=request.paciente.egresomensual)
if (form.is_valid() and family_form.is_valid()):
return self.form_valid(form, family_form, egreso_form)
else:
return self.form_invalid(form, family_form, egreso_form)
def form_valid(self, form, family_form, egreso_form):
self.object = form.save()
family_form.instance = self.object
egreso_form.instance = self.object
family_form.save()
return HttpResponseRedirect(self.get_success_url())
def form_invalid(self, form, family_form, egreso_form):
return self.render_to_response(
self.get_context_data(form=form,
family_form=family_form,
egreso_form=egreso_form))
As I can display forms in my view with OneToOneField relationships?
I was trying to create a relationship with EgresoMesual Pacientee, going by the GET method creates me the form
But to go through the POST method and relate the form EgresoMensualForm
egreso_form = EgresoMensualForm (self.request.POST, instance = request.paciente.egresomensual)
I mark error:
AttributeError at / ece / file /
'WSGIRequest' object has no attribute 'patient'
How can I create a single form that takes models: EgresoMensual, OtrosIngresos, Holiday Observations
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 use ModelChoiceField with initial value just for display (readonly field).
But value displayed is model id and I want to display customized value that will be a concatenation of 3 fields. I've override ____str____ method but it is not applyed.
I try to make customize ModelChoiceFiedl to define label_from_instance that seems to be the way to do what I want but it is not applyed...
models.py
class Utilisateur(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
uti_ide = models.AutoField(primary_key = True)
# pro_ide = models.ForeignKey(Projet, on_delete = models.CASCADE) # related project
projets = models.ManyToManyField(Projet, through='UtilisateurProjet')
uti_nom = models.CharField("Nom", max_length=20)
uti_pre = models.CharField("Prénom", max_length=20)
uti_mai = models.CharField("Email", max_length=40)
uti_sit = models.CharField("Equipe", max_length=20, null=True, blank=True)
uti_pro = models.CharField("Fonction/profil", max_length=200, null=True, blank=True)
uti_log = models.CharField("Log utilisateur", max_length=20, null=True, blank=True)
uti_dat = models.DateTimeField("Date log",auto_now_add=True, null=True, blank=True)
log = HistoricalRecords()
#classmethod
def options_list(cls,pro_ide):
# projet = Projet.objects.get(pro_ide=pro_ide)
# utilisateurs = Utilisateur.objects.filter(pro_ide=projet.pro_ide)
utilisateurs = Utilisateur.objects.filter(projets__pro_ide=pro_ide)
the_opts_list = [(utilisateur.uti_ide, utilisateur.uti_nom+', '+utilisateur.uti_pre) for utilisateur in utilisateurs]
the_opts_list.insert(0, (None, ''))
return the_opts_list
class Meta:
db_table = 'tbl_uti'
verbose_name_plural = 'Utilisateurs'
ordering = ['uti_ide']
def __str__(self):
return f"{self.uti_nom}, {self.uti_pre} ({self.uti_mai})"
forms.py
class UtilisateurModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
print('label')
return obj.uti_nom+', '+obj.uti_pre+' ('+obj.uti_mai+')'
class UtilisateurProjetUpdateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
super(UtilisateurProjetUpdateForm, self).__init__(*args, **kwargs)
# print('kwargs',self.request)
# print('projet',self.request['projet'])
# print('utilisateur',self.request['utilisateur'])
PROJETS = Projet.objects.all()
UTILISATEURS = Utilisateur.objects.all()
self.fields["pro_ide"] = forms.ModelChoiceField(queryset = PROJETS, label = "Nom projet", widget = forms.HiddenInput(), initial = Projet.objects.get(pro_ide=self.request['projet']))
self.fields["uti_ide"] = UtilisateurModelChoiceField(queryset = UTILISATEURS, label = "Nom, prénom de l'utilisateur", widget = forms.TextInput(attrs={'readonly':'readonly'}), initial = Utilisateur.objects.get(uti_ide=self.request['utilisateur']),) #,to_field_name="uti_nom"
class Meta:
model = UtilisateurProjet
fields = ('pro_ide','uti_ide',)
in forms.py under that last class Meta: you need to add:
field_classes = {
'pro_ide': UtilisateurModelChoiceField,
'uti_ide': UtilisateurModelChoiceField,
}
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'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,
})