I18n translation of model form in Django - django

I have a form that I want to translate:
Models.py:
class Show(models.Model):
discount_tickets = models.IntegerField("Discount Tickets")
regular_tickets = models.IntegerField("Regular Tickets")
afillate_price = models.IntegerField("Afillate Price")
user_price = models.IntegerField("User Price")
start_time = models.CharField("Event Time", max_length=20)
sale_end_time = models.CharField("Sale End Time", max_length=20)
def __unicode__(self):
return unicode(self.discount_tickets)
class ShowForm(ModelForm):
pass
class Meta:
model = Show
How can I translate the field names?

from django.utils.translation import ugettext_lazy as _
class Show(models.Model):
discount_tickets = models.IntegerField(_("Discount Tickets"))
regular_tickets = models.IntegerField(_("Regular Tickets"))
afillate_price = models.IntegerField(_("Afillate Price"))
user_price = models.IntegerField(_("User Price"))
start_time = models.CharField(_("Event Time"), max_length=20)
sale_end_time = models.CharField(_("Sale End Time"), max_length=20)

Related

How to update fields on import Django?

I need to update fields on import for ManyToMany bulk editing.
When importing, now I can only add products, because when I try to add already existing fields, I get a message about already existing IDs.
How can I update products using import?
admin.py
class ProductResource(resources.ModelResource):
class Meta:
model = Part
class PartAdmin(ImportExportActionModelAdmin):
resource_class = ProductResource
filter_horizontal = ('analog',)
admin.site.register(Part, PartAdmin)
models.py
class Part(models.Model):
brand = models.CharField('Производитель', max_length=100)
number = models.CharField('Артикул', max_length=100, unique=True)
name = models.CharField('Название', max_length=100)
description = models.TextField('Комментарий', blank=True, max_length=5000)
analog = models.ManyToManyField('self', blank=True, related_name='AnalogParts')
images = models.FileField('Главное изображение', upload_to = 'parts/', blank=True)
images0 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True)
images1 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True)
images2 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True)
def __str__(self):
return str(self.brand + " " + self.number + " " + self.name)
return self.name
from django.contrib import admin
from .models import *
from import_export.admin import ImportExportActionModelAdmin
from import_export import resources
from import_export import fields
from import_export.widgets import ForeignKeyWidget
class ProductResource(resources.ModelResource):
#category = fields.Field(column_name='Артикул', attribute='number')
class Meta:
model = Part
import_id_field = 'number'
import_id_fields = ('number',)
def skip_row(self, instance, original):
original_id_value = getattr(original, self._meta.import_id_field)
instance_id_value = getattr(instance, self._meta.import_id_field)
if original_id_value != instance_id_value:
return True
if not self._meta.skip_unchanged:
return False
for field in self.get_fields():
try:
if list(field.get_value(instance).all()) != list(field.get_value(original).all()):
return False
except AttributeError:
if field.get_value(instance) != field.get_value(original):
return False
return True
admin.site.register(Kits)
class PartAdmin(ImportExportActionModelAdmin):
resource_class = ProductResource
filter_horizontal = ('analog',)
admin.site.register(Part, PartAdmin)
#class PartAdmin(admin.ModelAdmin):
# filter_horizontal = ('analog',)
#admin.site.register(Part, PartAdmin)

Adding Foreign Key to Django Import Export

I am trying to import data from a csv using Django_Import Export. I saw other SO posts but they are not helping. Below are the models
Models.py
class TblSubject(amdl.AagamBaseModel):
subject_id = models.AutoField(primary_key=True)
subject_name = models.CharField(max_length=20)
standard = models.ForeignKey('TblStandard', models.DO_NOTHING)
remembrance_credit = models.IntegerField(default=40)
applied_knowledge_credit = models.IntegerField(default=30)
understanding_credit = models.IntegerField(default=30)
subject_credit = models.IntegerField(default=100)
class Meta:
db_table = 'tblsubject'
def __str__(self):
return f'{self.subject_name}'
class SubjectChapter(amdl.AagamBaseModel):
subject_chapter_id = models.AutoField(primary_key=True)
subject = models.ForeignKey('TblSubject', on_delete=models.CASCADE)
chapter_id = models.IntegerField()
chapter_name = models.CharField(max_length=150)
remembrance_credit = models.IntegerField()
applied_knowledge_credit = models.IntegerField()
understanding_credit = models.IntegerField()
chapter_credit = models.IntegerField()
class Meta:
db_table = 'subject_chapter'
def __str__(self):
return f'{self.chapter_id} {self.chapter_name} : {self.subject}'
Here is the admin.py
from django.contrib import admin
from import_export import resources, fields
from import_export.widgets import ForeignKeyWidget
from .models import SubjectChapter, TblSubject
from import_export.admin import ImportExportModelAdmin
class SubjectChapterResource(resources.ModelResource):
class Meta:
model = SubjectChapter
import_id_fields = ('subject_chapter_id',)
subject = fields.Field(
column_name='subject_name',
attribute='subject_name',
widget=ForeignKeyWidget(TblSubject, 'subject_id'))
class SubjectChapterAdmin(ImportExportModelAdmin):
resource_class = SubjectChapterResource
admin.site.register(SubjectChapter, SubjectChapterAdmin)
And i am getting this below error
I am inserting data for SUBJECTCHAPTER from csv where the SUBJECT column is a foreign key from TBLSUBJECT and it contains the name of the TBLSUBJECT.
Change this
class SubjectChapterResource(resources.ModelResource):
class Meta:
model = SubjectChapter
import_id_fields = ('subject_chapter_id',)
subject = fields.Field(
column_name='subject_name',
attribute='subject_name',
widget=ForeignKeyWidget(TblSubject, 'subject_name'))
From subject_id to subject_name

Sub query result in Django not looping from drop down select box

This is the error am getting:
QuerySet.annotate() received non-expression(s): 17
What I want is a subquery that will do something similar to the
select * from inecdb.announced_pu_results
where polling_unit_uniqueid in
(
select uniqueid from polling_unit
where lga_id = (select uniqueid from lga where uniqueid= 17)
);
The subquery
obj3 = Pu_results.objects.filter(polling_unit_uniqueid__in=Subquery(Unit.objects.filter(lga_id=obj1)))
is not displaying any result please can any one help
This is my view
if request.method == 'POST':
selected_item = request.POST.get('item_id') #This is from html select box
obj = Lga.objects.get(lga_id=selected_item)
obj1 = obj.lga_id
obj3 = Pu_results.objects.filter(polling_unit_uniqueid__in=Subquery(Unit.objects.filter(lga_id=obj1)))
for obt in obj3:
print(obt.party_score) #I want looping results here
This is my Model
from django.db import models
from django.urls import reverse
#from django.urls import reverse
class Unit(models.Model):
uniqueid = models.IntegerField(primary_key=True)
polling_unit_id = models.IntegerField(blank=False)
ward_id = models.IntegerField(default=False)
lga_id = models.IntegerField(default=False)
uniquewardid = models.IntegerField(default=True)
polling_unit_number = models.CharField(max_length=50, unique=True)
polling_unit_name = models.CharField(max_length=51)
#pulling_unit_number = models.CharField(max_length=50)
polling_unit_description = models.CharField(max_length=300)
lat = models.CharField(max_length=255)
long = models.CharField(max_length=255)
entered_by_user = models.CharField(max_length=50)
date_entered = models.DateTimeField(blank=False)
user_ip_address = models.CharField(max_length=50)
def get_absolute_url(self):
#return f"/products/{self.id}/"
return reverse("polling:inec-pull-result", kwargs={"uniqueid": self.uniqueid})
class Lga(models.Model):
uniqueid = models.AutoField(primary_key=True)
lga_id = models.IntegerField()
lga_name = models.CharField(max_length=50)
state_id = models.IntegerField()
lga_description = models.TextField(blank=True, null=True)
entered_by_user = models.CharField(max_length=50)
date_entered = models.DateTimeField()
user_ip_address = models.CharField(max_length=50)
class Meta:
db_table = 'lga'
class Article(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
active = models.BooleanField(default=True)
You need to make sure that the queryset you use for the subquery returns just one column, use values() for that. Note that Subquery isn't needed:
units = Unit.objects.filter(lga_id=obj1).values('uniqueid')
obj3 = Pu_results.objects.filter(polling_unit_uniqueid__in=units)
Read the documentation for the in lookup for a more detailed explanation of passing a QuerySet to in.
This also works:
obj3 = Pu_results.objects.filter(
polling_unit_uniqueid__in = Subquery(
Unit.objects.values('uniqueid').filter(lga_id=obj1)
)
)

how to count total student according to 'course' model in django

I am trying to count the number of the student according to CourseMasterModel.
I did it in MySQL, but I want to in Django.
select cn.course_name,count(st.id) from course_master
cn,semister_master sem,division_master di,student_profile st where
st.division_id = di.id and di.semister_id = sem.id and sem.course_id =
cn.id GROUP BY cn.course_name;
class CourseMasterModel(models.Model):
course_name = models.CharField(max_length=20,unique=True)
total_semister = mod`enter code here`els.SmallIntegerField()
class Meta:
db_table = "course_master"
verbose_name_plural = 'Course (Department)'
verbose_name = "Course"
def __str__(self):
return self.course_name
class SemisterMasterModel(models.Model):
semister = models.SmallIntegerField()
total_div = models.SmallIntegerField()
course = models.ForeignKey(CourseMasterModel,on_delete=models.PROTECT)
class Meta:
db_table = "Semister_master"
verbose_name_plural = 'Semister'
verbose_name = "semister"
def __str__(self):
return "%s - %d" %(self.course.course_name,self.semister)
class DevisionMasterModel(models.Model):
div_name = models.CharField(max_length=2)
semister = models.ForeignKey(SemisterMasterModel,on_delete=models.CASCADE)
class Meta:
db_table = "division_master"
verbose_name_plural = 'Division'
verbose_name = "Division"
def __str__(self):
return "%s - %s - %s"%(self.semister.course.course_name,self.semister.semister,self.div_name)
class StudentProfileModel(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="profile")
division = models.ForeignKey('core.DevisionMasterModel',on_delete=models.CASCADE,verbose_name="Course / Semister / Division")
roll_no = models.IntegerField()
enrollment_no = models.IntegerField(unique=True, error_messages={'unique':"This enrollment number has already been registered."})
def __str__(self):
return self.user.username
class Meta:
db_table = "Student_Profile"
You can annotate your CourseMasterModel, like:
from django.db.models import Count
CourseMasterModel.objects.annotate(
nstudents=Count('semistermastermodel__devisionmastermodel__studentprofilemodel')
)
The CourseMasterModels that arise from this QuerySet have an extra attribute .nstudents that contains the number of related StudentProfileModels.
Note: usually the names of Django models have no Model suffix, so CourseMaster instead of CourseMasterModel.
In case you rename the models, the query is:
from django.db.models import Count
CourseMasterModel.objects.annotate(
nstudents=Count('semistermaster__devisionmaster__studentprofile')
)

python Django Cannot assign "<Juego: Juego object>": "Prediccion.idjuego" must be a "Juego" instance

Hello i have the following problem (sorry for my bad english)
I have the following models
I have 3 models which "Prediccion" has two foreign keys from "Juego" model and "Usuario"model
class Juego(models.Model):
#id = models.IntegerField(primary_key=True, db_column='Id')
equipoa = models.CharField(max_length=135, db_column='EquipoA')
equipob = models.CharField(max_length=135, db_column='EquipoB')
resultadoa = models.IntegerField(null=True, db_column='ResultadoA', blank=True)
resultadob = models.IntegerField(null=True, db_column='ResultadoB', blank=True)
fecha = models.DateField(null=True, db_column='Fecha', blank=True)
class Meta:
db_table = u'juego'
class Usuario(models.Model):
# id = models.IntegerField(primary_key=True, db_column='Id') # Field name made lowercase.
nombre = models.CharField(max_length=135, db_column='Nombre')
fechanacimiento = models.DateField(null=True, db_column='FechaNacimiento', blank=True)
nombreusuario = models.CharField(max_length=135, db_column='NombreUsuario')
clave = models.CharField(max_length=135, db_column='Clave')
class Meta:
db_table = u'usuario'
class Prediccion(models.Model):
#id = models.IntegerField(primary_key=True, db_column='Id')
idusuario = models.ForeignKey(AuthUser, db_column='IdUsuario')
idjuego = models.ForeignKey(Juego, db_column='IdJuego') # Field name made lowercase.
equipoa = models.IntegerField(null=True, db_column='EquipoA', blank=True)
equipob = models.IntegerField(null=True, db_column='EquipoB', blank=True)
resultado = models.IntegerField(null=True, db_column='Resultado', blank=True)
class Meta:
db_table = u'prediccion'
And have I have the following view
from django.shortcuts import render_to_response
from scorecenter.JuegoApp.models import Juego
from scorecenter.PrediccionApp.models import Prediccion
from scorecenter.PrediccionApp.models import TipoResultado
from scorecenter.PrediccionApp.models import AuthUser
def juegosap(request, pagina="1", idgame=-1, resa=-1, resb=-1):
if(idgame==-1 and resa==-1 and resb==-1):
pag = int(pagina)
pag = pag-1
lista = Juego.objects.order_by('-fecha', '-id')[pag*4:pag*4+4]
template_name = 'juegos_semana.html'
return render_to_response(template_name,{'lista':lista})
else:
game = Juego.objects.get(id=int(idgame))
print(game.equipoa)
print(game.id)
user = AuthUser.objects.get(username=request.user)
print(user.username)
temporal = Prediccion(idusuario = user, idjuego = game, equipoa=int(resa), equipob=int(resb))
temporal.resultado = 1
temporal.save()
pag = int(pagina)
pag = pag-1
lista = Juego.objects.order_by('-fecha')[pag*4:pag*4+4]
template_name = 'juegos_semana.html'
return render_to_response(template_name,{'lista':lista})
But I am getting the following error:
Cannot assign "<Juego: Juego object>": "Prediccion.idjuego" must be a "Juego" instance.
in the next line:
temporal = Prediccion(idusuario = user, idjuego = game, equipoa=int(resa), equipob=int(resb))
your idjuego is a foreign key so the value must equivalent to id,
try:
temporal = Prediccion(idusuario = user, idjuego = game.id, equipoa=int(resa), equipob=int(resb))
Also, in each of your model, please put unicode so that it will not return "< object >". Here is a sample:
def __unicode__(self):
return self.field_name
temporal.idjuego_id = game.id
temporal.save()
ForeignKey fields store their value in an attribute with _id at the end, which you can access directly to avoid visiting the database.
The _id version of a ForeignKey is a particularly useful aspect of Django, one that everyone should know and use from time to time when appropriate.