This is my models
class Tasklist(models.Model):
clientname= models.CharField(max_length=100,null=True,blank=True)
task = models.CharField(max_length=100)
startdate = models.DateField(default=timezone.now, blank=True, null=True)
enddate = models.DateField(blank=True, null=True)
assignee = models.CharField(max_length=30)
status = models.CharField(max_length=30)
fstatus = models.BooleanField(default=False)
def __str__(self):
return self.task + " - Task - " + str(self.fstatus)
class edit_page(models.Model):
old_id = models.ForeignKey(Tasklist,on_delete=models.CASCADE)
updatedate = models.DateField(blank=True, null=True)
time_from = models.TimeField(blank=True, null=True)
time_to = models.TimeField(blank=True, null=True)
messagelogs = models.TextField(blank=True, null=True)
def __str__(self):
return self.messagelogs
This is My Views page
def edit_task(request, task_id):
if request.method == "POST":
updatedate=request.POST.get("updatedate","")
time_from=request.POST.get("time_from","")
time_to=request.POST.get("time_to","")
messagelogs=request.POST.get("messagelogs","")
test_list=edit_page(updatedate=updatedate,time_from=time_from,time_to=time_to,messagelogs=messagelogs)
test_list.save()
task = Tasklist.objects.get(pk=task_id)
form = TaskForm(request.POST or None, instance = task)
if form.is_valid():
form.save()
messages.success(request,("Task Edited "))
return redirect('email_updatetask', (task_id))
return redirect('todolist')
else:
task_obj = Tasklist.objects.get(pk=task_id)
return render(request, 'edit.html', {'task_obj': task_obj})
can u pls how can i store my primary keys into the second foreign key field via HTML files....
Related
I need to save a form with listaflor and multiple instances of flora2estado,When i try to send this form i get:
IntegrityError at /enviar_flora/
(1062, "Duplicate entry '99-10031' for key 'PRIMARY'")
views.py:
def CreateFlo(request):
form = FloForm()
if request.method == 'POST':
form = FloForm(request.POST)
if form.is_valid():
listafor = form.save()
estados = form.cleaned_data.get('estados')
for estado in estados:
Flora2Estado.objects.create(especie=listafor, estado= estado)
# or you can use bulk_create: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#bulk-create
return render(request,'accounts/enviar_flora.html')
models.py:
class Listaflor(models.Model):
especie_id = models.AutoField(db_column="especie_id",primary_key=True)
familia = models.ForeignKey(Familia, models.DO_NOTHING, db_column='familia_id', blank=True, null=True)
Especie = models.CharField(db_column='especie', max_length=255, blank=True, null=True)
class Meta:
managed = True
db_table = 'listaflor'
class Flora2Estado(models.Model):
estado = models.ForeignKey(EstadosM, models.CASCADE)
especie = models.ForeignKey(Listaflor, models.CASCADE,default=99999)
flora2estado = models.AutoField(primary_key=True, default=99999)
class Meta:
managed = True
db_table = 'flora2estado'
unique_together = (('estado', 'especie'),)
class EstadosM(models.Model):
estado_id = models.AutoField(primary_key=True)
estado_nome = models.CharField(max_length=100, blank=True, null=True)
nome_abbr = models.CharField(max_length=2, blank=True, null=True)
criadoem = models.DateTimeField(db_column='criadoEm')
class Meta:
managed = False
db_table = 'estados'
def __str__(self):
return self.estado_nome
I am developing an audit management information system where I can record all finding related to an audit. I have models with foreignkeys relationship. How do I see all findings with a particular assignment and audit_title and unit?
See relevant codes below.
model.py content
class Unit(models.Model):
unit_name = models.CharField(max_length=30, blank=True, null=True)
def __unicode__(self):
return self.unit_name
class Assignment(models.Model):
assignment_name = models.CharField(max_length=30, blank=True, null=True)
def __unicode__(self):
return self.assignment_name
class Task(models.Model):
task_title = models.CharField(max_length=35, blank=True, null=True)
return self.task_title
class Finding(models.Model):
assignment = models.ForeignKey(Assignment, blank=True, null=True)
audit_title = models.ForeignKey(Task, blank=True, null=True)
auditor = models.ManyToManyField(User, blank=True)
unit = models.ForeignKey(Unit, blank=True, null=True)
audit_period = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True)
contact_person = models.CharField('Contact Person', max_length=500, blank=True, null=True)
finding = models.TextField('Detail Finding', max_length=500, blank=True, null=True)
be = models.CharField(max_length=30, blank=True, null=True)
form.py
class FindingSearchForm(forms.ModelForm):
class Meta:
model = Finding
fields = ['assignment',
'audit_title',
'unit',
'be',
]
Am I have the following in my views.py but I have this error invalid literal for int() with base 10: ''
views.py content
def finding_list(request):
title = 'List of Finding'
queryset = Finding.objects.all()
queryset_count = queryset.count()
form = FindingSearchForm(request.POST or None)
context = {
"title": title,
"form": form,
"queryset_count": queryset_count,
}
if request.method == 'POST':
unit = form['unit'].value()
audit_title = form['audit_title'].value()
assignment = form['assignment'].value()
queryset = Finding.objects.all().order_by('-timestamp').filter(be__icontains=form['be'].value(),
unit_id=unit,
assignment_id=assignment,
audit_title_id=audit_title,)
if request.method == 'POST':
unit = form['unit'].value()
audit_title = form['audit_title'].value()
assignment = form['assignment'].value()
queryset = Finding.objects.all().order_by('-timestamp').filter(be__icontains=form['be'].value()
)
if (unit != ''):
queryset = queryset.filter(unit_id=unit)
if (audit_title != ''):
queryset = queryset.filter(audit_title_id=audit_title)
if (assignment != ''):
queryset = queryset.filter(assignment_id=assignment)
this is my code
views.py
def guardar(request):
if request.method == "POST":
idpersona = int(request.POST.get('id'))
persona = personal.objects.get(id=idpersona)
idep = int(request.POST.get('dependencia'))
dep = dependencia.objects.get(id=idep)
idcon = int(request.POST.get('concepto'))
con = concepto.objects.get(id=idcon)
fecha = request.POST.get('fecha')
print(fecha)
db_registro = lista_registro(
personal_id=persona,
fecha_registro=fecha,
dependencia_id=dep,
concepto_id=con,
descripcion=request.POST.get('descripcion'),
monto=request.POST.get('monto'),
)
db_registro.save()
return render(request, 'registro/exito.html')
Models.py
class lista_registro(models.Model):
personal_id = models.ForeignKey(personal, on_delete=models.CASCADE)
dependencia_id = models.ForeignKey(dependencia, on_delete=models.CASCADE)
concepto_id = models.ForeignKey(concepto, on_delete=models.CASCADE)
fecha_realizado = models.DateField()
fecha_registro = models.DateField(auto_now_add=True)
descripcion = models.CharField(max_length=1000)
pago_id = models.ForeignKey(pago, on_delete=models.CASCADE, default=2)
monto = models.CharField(max_length=100)
def __str__(self):
return "===> " + self.descripcion + " <==="
well my problem is that I get a NOT NULL constraint error. I get that this is a date error but I don't know how to solve this
when you define a field that will not be required just set null=True, blank=True on your models file
fecha_realizado = models.DateField(null=True, blank=True)
I need to populate two combos in a ModelForm, and I would like to initialize them with the current value of each foreign key.
My models are:
class Alumno(models.Model):
idalumno = models.AutoField(primary_key=True)
padre_idpadre = models.ForeignKey('Padre', models.DO_NOTHING, db_column='padre_idpadre', blank=True, null=True)
curso_idcurso = models.ForeignKey('Curso', models.DO_NOTHING, db_column='curso_idcurso')
nombre = models.CharField(max_length=45, blank=True, null=True)
class Meta:
db_table = 'alumno'
class Curso(models.Model):
idcurso = models.IntegerField(primary_key=True)
nombrecurso = models.CharField(max_length=45, blank=True, null=True)
class Meta:
db_table = 'curso'
class Padre(models.Model):
idpadre = models.AutoField(primary_key=True)
socio = models.NullBooleanField(blank=True, null=True)
nombre = models.CharField(max_length=45, blank=True, null=True)
primerapellido = models.CharField(max_length=45, blank=True, null=True)
segundoapellido = models.CharField(max_length=45, blank=True, null=True)
class Meta:
db_table = 'padre'
This is my Form in forms.py:
class AlumnoForm(forms.ModelForm):
padre = PadreModelChoiceField(queryset=Padre.objects.all(), initial=**XXXXXXXXX**) #I would like to init here with the value of the FK
curso = CursoModelChoiceField(queryset=Curso.objects.all(), initial=**XXXXXXXXXX**) #And here too
class Meta:
model = Alumno
fields = ('nombre','padre','curso',)
labels = {
'nombre': 'Nombre',
'padre': 'Padre',
'curso': 'Curso',
}
In views.py
def alumno_editar(request, pk):
alumno = get_object_or_404(Alumno, pk=pk)
if request.method == "POST":
form = AlumnoForm(request.POST, instance=alumno)
if form.is_valid():
alumno = form.save(commit=False)
alumno.save()
return redirect('alumno_listar')
else:
form = AlumnoForm(instance=alumno)
return render(request, 'administration/alumno_editar.html', {'form': form})
What should I write in the part XXXXXXXXXX of the code.
It could be misconception but I'm think is a common operation, althought I don't find it.
I have the following models that I need to create a form which allows for the updating of an existing Response (generated previously with a slug and then emailed to the respondent) and the creation of a Rating for each CV in CV.objects.all(). What's the easiest way to do this in Django. Currently I have a class-based UpdateView for Response and that's it.
class Response(models.Model):
first_name = models.CharField(max_length=200, null=True, blank=True)
last_name = models.CharField(max_length=200, null=True, blank=True)
email = models.EmailField(max_length=254)
slug = models.SlugField(max_length=32)
submited = models.BooleanField(default=False)
submit_time = models.DateTimeField(null=True, blank=True)
creation_time = models.DateTimeField(auto_now_add=True)
class CV(models.Model):
title = models.CharField(max_length=200)
image = models.ImageField(upload_to=content_file_name)
class Rating(models.Model):
cid = models.ForeignKey('CV')
rid = models.ForeignKey('Response')
score = models.IntegerField()
comment = models.TextField()
I eventually worked out how to do this. My code was as follows in case anyone is interested.
def add_response(request):
CVs = CV.objects.all()
if request.method == "POST":
ResForm = ResponseForm(request.POST, instance=Response())
RatForms = [RatingForm(request.POST, prefix=str(cv.id), instance=Rating(cid=cv)) for cv in CVs]
if ResForm.is_valid() and all([rf.is_valid() for rf in RatForms]):
new_response = ResForm.save(commit=False)
new_response.submit_time = datetime.now()
new_response.submited = True
new_response.save()
for rf in RatForms:
new_rating = rf.save(commit=False)
new_rating.rid = new_response
new_rating.save()
return HttpResponseRedirect('/thanks/')
else:
for i, _ in enumerate(RatForms):
RatForms[i].cv = CV.objects.filter(id=int(RatForms[i].prefix))[0]
print RatForms[i].cv
return render(request, 'response.html', {'response_form': ResForm, 'rating_forms': RatForms})
else:
ResForm = ResponseForm(instance=Response())
RatForms = [RatingForm(prefix=str(cv.id), instance=Rating(cid=cv)) for cv in CVs]
for i, _ in enumerate(RatForms):
RatForms[i].cv = CV.objects.filter(id=int(RatForms[i].prefix))[0]
print RatForms[i].cv
return render(request, 'response.html', {'response_form': ResForm, 'rating_forms': RatForms})