Choose object and then another object related to this - django

It's quite hard for me to explain what i need with words so I here is some code:
class Configuration(models.Model):
name = models.CharField(max_length=250)
firmware_version = models.ForeignKey(FirmwareVersion)
devices_amount = models.PositiveIntegerField()
def __unicode__(self):
return unicode(self.name)
class Firmware(models.Model):
name = models.CharField(max_length=250)
circuit_model = models.ForeignKey(Versiiplates)
def __unicode__(self):
return unicode(self.name)
class FirmwareVersion(models.Model):
firmware = models.ForeignKey(Firmware)
version = models.CharField(max_length=100)
file = models.FileField(upload_to="firmware/")
upload_date = models.DateField(default = datetime.date.today())
notes = models.TextField(max_length=2500, null=True, blank=True)
def __unicode__(self):
return u'%s %s' % (self.firmware.__unicode__(), self.version)
Is there any way to choose in admin change-form for Configuration the Firmware first and then any FirmwareVersion related to it?

It's really simple to implement this behavior with django-smart-selects. In my case Configuration class should look like this:
class Configuration(models.Model):
name = models.CharField(max_length=250)
firmware = models.ForeignKey(Firmware, related_name="firmware")
firmware_version = ChainedForeignKey(FirmwareVersion, chained_field="firmware", chained_model_field="firmware", show_all="False", auto_choose=True)
devices_amount = models.PositiveIntegerField()
def __unicode__(self):
return unicode(self.name)

Related

Modify database in django

I am a beginner in django. Following is my Attendance Management App.
This is my models.py.
from django.db import models
class Subject(models.Model):
subject_name = models.CharField(max_length=20)
#attendance = models.ForeignKey(Attendance, on_delete =
models.DO_NOTHING)
attendance = models.IntegerField(default=0)
def __str__(self):
return self.subject_name
class Section(models.Model):
section_name = models.CharField(max_length=20)
subject = models.ManyToManyField(Subject)
def __str__(self):
return self.section_name
class Student(models.Model):
rollno = models.IntegerField()
name = models.CharField(max_length=20)
section = models.ForeignKey(Section, on_delete = models.DO_NOTHING,
default=0)
def __str__(self):
return str(self.rollno) + self.name
class Teacher(models.Model):
#teacher_name = models.CharField(max_length=20)
section = models.ForeignKey(Section, on_delete=models.CASCADE)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
#section_name = models.CharField(max_length=10)
#subject_name = models.CharField(max_length=30)
def __str__(self):
return self.section.section_name+' '+self.subject.subject_name
class TeacherList(models.Model):
teacher_name = models.CharField(max_length=20)
teacher = models.ManyToManyField(Teacher)
def __str__(self):
return self.teacher_name
The line below is not working in views.py
student = models.Student.objects.get(rollno = sroll)
student.section.subject.get(subject_name = 'java').attendance += 1
student.save()
This view is called from a template when a button is clicked to add attendance of a student.
The attendance in above code is not modified. Please help me out.
You're saving the student, instead of the subject.
student = models.Student.objects.get(rollno = sroll)
subject = student.section.subject.get(subject_name='java')
subject.attendance += 1
subject.save()
Or, better, do the update directly in one go:
student.section.subject.filter(subject_name='java').update(attendance=F('attendance')+1)
and there's no need to save at all.

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

How to change value of the field in a proxy model in Django

I have a base model, and proxy models. I want to change value of upload_to of 'image' filed, that depends on 'file_type' filed.
I'm not sure how to do this, do I need to specify it in my .Manager class or in Proxy class.
Can you please give me same detail how to do this.
class FileDescription(models.Model):
class Meta:
ordering = ['file_creation_time']
TYPE_CHOICES = (
('homework', 'Homework'),
('class', 'Class Papers'),
('random', 'Random Papers')
)
subject = models.ForeignKey('Subjects', null=True, blank=True, primary_key=True)
subject_name = models.CharField(max_length=100, unique=False)
file_type = models.CharField(max_length=100, choices=TYPE_CHOICES)
....
....
image = models.ImageField(upload_to= ??????????? blank=True, null=True, max_length=255)
def __unicode__(self):
return u'%s' % (self.file_name)
class HomeworkManager(models.Manager):
def get_query_set(self):
qs = super(HomeworkManager, self).get_query_set().filter(file_type='homework')
return qs
class ClassPapersManager(models.Manager):
def get_query_set(self):
qs = super(HomeworkManager, self).get_query_set().filter(file_type='class')
return qs
class RandomPapersManager(models.Manager):
def get_query_set(self):
qs = super(HomeworkManager, self).get_query_set().filter(file_type='random')
return qs
class Homework(FileDescription):
class Meta:
proxy = True
Don't worry about replacing upload_to just modify the method to handle different subclasses (use a method for upload_to if you're not already).
def my_upload_to(instance, filename):
if instance._meta.module_name == 'homework':
return '/path/to/homework/files/%s' % filename
if instance._meta.module_name == 'classpaper':
return '/path/to/classpaper/files/%s' % filename
if instance._meta.module_name == 'randompaper':
return '/path/to/randompaper/files/%s' % filename

How to always filter on a field on objects requests

I have two models :
class Album(models.Model):
#Attributes
title = models.CharField(max_length=200)
displayed = models.BooleanField()
created_on = models.DateTimeField(auto_now_add=True)
class Photos(models.Model):
#Attributes
title = models.CharField(max_length=500)
link = models.CharField(max_length=500)
album = models.ForeignKey(Album, unique=False, verbose_name=_('album'))
def upload_path(self, filename):
return 'upload/photos/%s/%s' % (self.id, filename)
def upload_path_thumbnail(self, filename):
return 'upload/photos/%s/%s' % (self.id, "thumnail_" +filename)
thumbnail = models.ImageField(upload_to=upload_path_thumbnail)
photo = models.ImageField(upload_to=upload_path)
created_on = models.DateTimeField(auto_now_add=True)
displayed = models.BooleanField()
And I want to force, when i select Photos, to always filter on displayed=1.
Thank you
Use a custom manager:
class DisplayedPhotoManager(models.Manager):
def get_queryset(self):
return super(DisplayedPhotoManager, self).get_queryset().filter(displayed=1)
class Photos(models.Model):
objects = DisplayedPhotoManager()
...
this will override standard "objects" manager (which can be dangerous).
A nicer pattern is often:
class DisplayedPhotoManager(models.Manager):
def get_queryset(self):
return super(DisplayedPhotoManager, self).get_queryset().filter(displayed=1)
class Photos(models.Model):
objects = models.Manager()
displayed = DisplayedPhotoManager()
...
and use 'displayed' instead of 'objects':
Photo.displayed.all()

Django-models ForeignKey Objects display Field Name instead of Object Values

I am using a ForeignKey called Memberno in My Django models. After entering data in the Members Class, it appears in the other classes as "member object" in the 'memberno' field. For ForeignKey, I am using 'raw_id_fields' as a workaround, but for normal fields and even 'filter_horizontal' , each memberno value is displayed as "member object". I would like the values to appear as they are in the member class i.e. 1, 2, ...
from django.db import models
# Create your models here.
class Members(models.Model):
DESIGNATION_CHOICES=(
('ADM', 'Administrator'),
('OFF', 'Club Official'),
('MEM', 'Ordinary Member'),
)
memberno = models.AutoField(primary_key=True)
fname = models.CharField(max_length=15)
sname = models.CharField(max_length=15)
onames = models.CharField(max_length=30, blank=True)
email = models.EmailField()
phoneNumber = models.CharField(max_length=15)
regNo = models.CharField(max_length=15)
designation = models.CharField(max_length=3,choices=DESIGNATION_CHOICES)
image = models.ImageField(max_length=100,upload_to='photos/%Y/%m/%d', blank=True, null=True)
course = models.CharField(max_length=30, blank=True, null=True)
def __unicode__(self):
return u'%s %s %s' % (self.fname, self.sname, self.memberno)
def get_absolute_url(self):
return '%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.id)
def get_download_url(self):
return '%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.name)
class Security(models.Model):
memberno = models.ForeignKey(Members, unique=True)
username = models.CharField(max_length=30, primary_key=True)
password = models.CharField(max_length=70)
def __unicode__(self):
return u'%s %s %s' % (self.username, self.password, self.memberno)
class Subscriptions(models.Model):
memberno = models.ForeignKey(Members)
receiptNo = models.CharField(max_length=30, primary_key=True)
type = models.CharField(max_length=50)
date = models.DateField()
amount = models.FloatField(max_length=99)
def __unicode__(self):
return u'%s %s %s' % (self.receiptno, self.type, self.memberno)
class events(models.Model):
eventName = models.CharField(max_length=25)
eventID = models.AutoField(primary_key=True)
details = models.TextField()
attendanceFee = models.FloatField(max_length=99)
date = models.DateField()
memberno = models.ManyToManyField(Members)
def __unicode__(self):
return u'%s %s %s' % (self.eventName, self.eventID, self.memberno)
The admin interface appears to use __str__() to determine the display of a model. I make it a habbit to always define both __unicode__() and __str__() when I create a model. For example:
class Activity(models.Model):
activity_code = models.ForeignKey(ActivityCode)
note = models.TextField(blank=True)
def __str__(self):
return "(%s) %s" % (self.activity_code.short, self.note)
def __unicode__(self):
return u'(%s) %s' % (self.activity_code.short, self.note)
Update:
It looks as though your def __unicode__(self) is not indented properly in your code. As a result it is not a part of your class, and is not being used. Indenting is very important in Python.
I am not sure I understand your question completely, but have you defined a unicode method for your models?