django updating multiple instances with different foreignkey - django

I'm trying to duplicate multiple data I only need to change their related foreignkeymy problem is that I'm able to duplicate but with the same foreignkey below is my code
any suggestions please
from django.db import models
class Category(models.Model):
category_name = models.CharField(max_length=100)
def __str__(self):
return self.category_name
class Client(models.Model):
cat = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True)
fname = models.CharField(max_length=100)
lname = models.CharField(max_length=100)
age = models.IntegerField()
married = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.fname + " " + self.lname + " " + str(self.cat)
def show_category(request, cat_id):
clients = Client.objects.filter(cat__id=cat_id)
if request.method =='POST':
for i in clients:
i.id = None
i.cat.id=3
i.save()
return redirect('/')
context = {'clients':clients}
return render(request, 'app/home_cat.html', context)

See the documentation on copying model instances:
def change_category(clients, new_category_id):
for client in clients:
client.pk = None
client._state.adding = True
client.cat_id = new_category_id
client.save()

Related

Django category view

I am new to django and maybe this is a stupid question but i got stuck with this for a while now.. so i have a few categories of meds, like AINS, antidepressants and each of this category has its own meds, and i am trying to show my users all the meds of a specific category: so if a users types in www.namesite.com/meds/AINS the it will show only the meds for that specific category .. AINS.I think that i should get the absolute url of every category and filter all the meds in that specific category?
Model:
class Category(models.Model):
category = models.CharField(max_length=30)
slug = models.SlugField()
def __str__(self):
return self.category
def get_absolute_url(self):
return reverse("meds", kwargs={'slug':self.category})
class Meta:
verbose_name_plural = 'Categorii'
class Medicament(models.Model):
title = models.CharField(max_length=50)
description = models.TextField(max_length=200)
category = models.ForeignKey(Category, on_delete='CASCADE')
price = models.DecimalField(decimal_places=2, max_digits=4)
prospect = models.TextField(default='Prospect')
company = models.TextField(default = 'company')
nr_unitati = models.IntegerField()
quantity = models.CharField(max_length=5, default='mg')
date_added = models.DateTimeField(auto_now_add=True)
rating = models.IntegerField(null=True, blank=True)
amount = models.IntegerField(default=0)
def __str__(self):
return self.title + ' ' + self.company + ' ' + str(self.nr_unitati) + ' ' + self.quantity
class Meta:
verbose_name_plural = 'Medicamente'
Views:
class MedCategoriesView(DetailView):
model = Category
template_name = 'products/AINS.html'
context_object_name = 'all_categories'
def get_context_data(self, **kwargs):
context = super(AINS_ListView, self).get_context_data(**kwargs)
context['meds'] = Medicament.objects.filter(category=self.object)
return context
Urls:
path('medicaments/<slug>/', MedCategoriesView.as_view(), name='meds'),
Using function based views.
def medicament(request, slug):
try:
medicaments = Medicament.objects.filter(category__slug=slug)
except Medicament.DoesNotExist:
raise Http404("Medicament does not exist")
return render(request, 'products/AINS.html', {'medicaments': medicaments})

How to group list items by user

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

django __str__ returned non-string(type tuple)

Hello i'm studying django, and
i have a problem with def str on models
models.py
class Student(models.Model):
id = models.AutoField(primary_key=True)
school_year = models.CharField(max_length=4,choices=SCHOOL_YEAR_CHOICES,default='2019')
campus = models.CharField(max_length=1,choices=CAMPUS_CHOICES,default='M')
type = models.CharField(max_length=1,choices=TYPE_CHOICES,default='N')
affiliate = models.CharField(max_length=1,choices=AFFILIATE_CHOICES,default='N')
name = models.CharField(max_length=30, unique=True)
def __str__(self):
return self.name,self.campus
class Comment(models.Model):
student = models.ForeignKey(Student, related_name='comments',on_delete=models.CASCADE)
created_by = models.ForeignKey(User,related_name='comments',on_delete=models.CASCADE)
message = models.TextField(max_length=1000, unique=False)
about = models.CharField(max_length=1,choices=ABOUT_CHOICES,default='L')
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
def __str__(self):
return self.created_by.first_name, self.student.name
if i remove that " student = models.ForeignKey ~~" on class Comment, it'll work
i think 'student' on class comment makes a problem
anyone help? thanks
and i'm using python3 with the lastest version of django
Use this on Comment model:
def __str__(self):
return self.created_by.first_name + ' ' + self.student.name
Also on Student model:
def __str__(self):
return self.name + ' ' + self.campus
Redefine __str__:
def __str__(self):
return self.name+' '+self.campus

QuerySet in Django - returns exception

I am trying to understand how exactly query works on Django, i followed the tutorials it´s not working I am not sure what i am doing wrong.
When I run
BeneficientePagar.objects.filter(nome__contains="Joao Pedro")
it returns
"Choices are %s" %s (name, ",".join(available))) django.core.exceptions.FieldError: Cannot resolve keyword "nome into field. Choices are: ID, beneficiente, beneficiente_id,join, join_id, moeda
from django.db import models
# Create your models here.
class Moeda(models.Model):
moeda_ficticia = models.FloatField()
class Join(models.Model):
nome = models.CharField(max_length=150)
nascimento = models.DateField()
cpf = models.IntegerField(primary_key=True)
endereco = models.CharField(max_length=150)
email = models.EmailField()
def __str__(self):
return self.nome
class Beneficiente(models.Model):
ID = models.AutoField(primary_key=True)
nome = models.CharField(max_length=150)
CNPJ = models.IntegerField(max_length = 10)
def __str__(self):
return self.nome
class Favores(models.Model):
ID = models.AutoField(primary_key=True)
favor = models.CharField(max_length=150)
dataInserido = models.DateField()
usuarios = models.ForeignKey(Join)
def __str__(self):
return self.favor
class BeneficientePagar(models.Model):
ID = models.AutoField(primary_key=True)
moeda = models.IntegerField()
beneficiente = models.ForeignKey(Beneficiente)
join = models.ForeignKey(Join)
def __str__(self):
return self.ID
Thanks in advance
If using BeneficientPager, you need to do
BeneficientePagar.objects.filter(beneficient__nome__contains="Joao Pedro")
You are getting the error because nome is a field on Beneficiente, not BeneficientePagar.
You can either do
Beneficiente.objects.filter(nome__contains="Joao Pedro")
which will return a queryset of Beneficientes. Or if you need BeneficientePagar you can query through the foreign key.
BeneficientePagar.objects.filter(beneficiente__nome__contains="Joao Pedro")

Two Django models with foreign keys in one view

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,
})