'ModelChoiceField' object has no attribute 'objects' - python

I am using django framework for the first time. I want to fetch the data from my model course to show it in choice field of form. but when i am using the same model for two diiferent field in single form, it is showing the error 'ModelChoiceField' object has no attribute 'objects'. here is my code.
models.py:
from django.db import models
class course(models.Model):
course_id = models.CharField(primary_key = True, max_length = 2)
course_name = models.CharField(max_length = 20)
stream = models.CharField(max_length = 15)
number_of_sem = models.IntegerField(max_length = 2)
def __unicode__(self):
return self.course_id
forms.py:
from django import forms
from feedback_form.models import course
class loginForm(forms.Form):
course = forms.ModelChoiceField(queryset=course.objects.values_list('course_name', flat = True))
semester = forms.ModelChoiceField(queryset=course.objects.values('number_of_sem'))

Problem is in forms.py
class loginForm(forms.Form):
course = forms.ModelChoiceField(queryset=course.objects.values_list('course_name', flat = True))
semester = forms.ModelChoiceField(queryset=course.objects.values('number_of_sem'))
You have course field in forms.py when your refer course in your forms.ModelChoiceField it got confuse about course Model and course field.
Please change field variable name.

Related

The serializer field might be named incorrectly and not match any attribute or key on the `Project` instance

i'm trying to work with django-rest-framework and serializers ,and i keep getting this error :
AttributeError: Got AttributeError when attempting to get a value for field
recruitment_date on serializer EmployeeSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the
Project instance.
Original exception text was: 'Project' object has no attribute 'recruitment_date'
models.py :
class Employee(models.Model):
f_name = models.CharField(max_length=50,default='')
l_name = models.CharField(max_length=50,default='')
telephone = models.CharField(max_length=15,default='')
recruitment_date = models.DateField(auto_now_add=False)
salary = models.DecimalField(max_digits=12,decimal_places=2)
def __str__(self):
return self.f_name +' '+self.l_name
class Project(models.Model):
name = models.CharField(max_length=255, default='')
statuts = models.CharField(max_length=10,choices = STATUS,default= STATUS[0])
description = models.TextField(blank=True)
leader = models.OneToOneField(Employee,on_delete=models.CASCADE,related_name = 'leader')
p_employees = models.ManyToManyField(Employee)
estimated_budget = models.DecimalField(max_digits=12,decimal_places=4)
start_date = models.DateField(auto_now_add=False)
end_date = models.DateField(auto_now_add=False)
tasks = models.ManyToManyField(Task)
materials = models.ManyToManyField(Materials)
def __str__(self):
return self.name
serializers.py :
class EmployeeSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Employee
fields=['id','f_name','l_name','telephone','recruitment_date','salary']
class ProjectSerializer(serializers.HyperlinkedModelSerializer):
leader = EmployeeSerializer()
p_employees = EmployeeSerializer(many =True)
tasks = TaskSerializer(many =True)
materials = MaterialsSerializer(many =True)
class Meta :
model = Project
fields = ['name','statuts','description','leader','p_employees',
'start_date','end_date','tasks','materials']
That recruitment_date attribute/column might not actually exist in your Django database. Sure it's in your model, but did you make migrations then migrate?
Try running your development server and see if a message that says "Your models have changed" or something along those lines. Django is pretty good when it comes to those things.
If anything, I highly recommend you just makemigrations and migrate. It won't hurt.
Then
If the database already has that column/attribute, then just do this with your serializer. It's the best "good enough" solution I can do:
class Meta:
model = Employee
fields = '__all__'

Django, 2 forms on one page, one form uses data from the other

Here are my models:
from django.db import models
ATTACK_TYPES = ('EXA','Example')
class AttackImage(models.Model):
title = models.CharField(max_length=255)
image = models.ImageField(upload_to='attack_images')
source_url = models.URLField(blank=True,null=True)
class AttackItem(models.Model):
attack_image = models.ForeignKey(AttackImage, on_delete=models.CASCADE)
attack_used = models.CharField(max_length=55, choices=ATTACK_TYPES)
hidden_data_found = models.BooleanField(blank=True)
I want a user to be able to create an attackitem and an attackimage at the same time, with the attackitem having a foreignkey relation to the attackimage, as you can see. How can I do this? Thanks in advance.

Django model reference and manipulation

I have the following models in Django that have a structure as follows:
class Office_Accounts(models.Model):
accountid = models.EmailField(max_length=200, unique=True)
validtill = models.DateField(default=datetime.now)
limit = models.CharField(max_length=2)
class Device(models.Model):
device_type = models.ForeignKey(DeviceType,to_field='device_type')
serial_number = models.CharField(max_length=200,unique=True)
in_use_by = models.ForeignKey(User,to_field='username')
brand = models.CharField(max_length=200,default="-", null=False)
model = models.CharField(max_length=200,default="-", null=False)
type_number = models.CharField(max_length=200,blank=True,null=True, default = None)
mac_address = models.CharField(max_length=200,blank=True,null=True, default = None)
invoice = models.FileField(upload_to='Device_Invoice', null=True, blank = True)
msofficeaccount = models.ForeignKey(Office_Accounts, to_field="accountid")
class Meta:
verbose_name_plural = "Devices"
def full_name(self):
return self.device_type + self.serial_number + self.brand
I will display both of the models in admin.py.
Now, I want to display the count of each accountid present in the field "msofficeaccount" (present in Device Models) in my admin page of Office_Accounts model. For an example if xyz#abc.com appears in 10 rows of msofficeaccount field then, the count should be displayed as 10 in Office_Accounts admin page. Can anyone please guide me how should I approach this problem to solve it?
You could add a method to your admin class that returns the count of related devices for each office_account, but that would be very inefficient. Instead you can override get_queryset to annotate the count from a database aggregation function:
from django.db.models import Count
class Office_AccountsAdmin(admin.ModelAdmin):
list_display = (..., 'device_count')
...
def get_queryset(self, request):
qs = super().get_queryset(request)
return qs.annotate(device_count=Count('device'))
(On a minor note, Python style is always to use CamelCase for class names, and Django style is to use singular model names, so your model should really be called OfficeAccount.)

Populate Django ManyToManyField Options Based on Other Field in Admin

I am having problems filtering options for a ManyToManyField on the Django Admin Add screen based on input to another field on the same form. I am new to Django and have been unable to use any of the generic fixes described elsewhere because they are all slightly different than my situation. Here is my situation:
I have three models in my project: Class, Student, and AttendanceRecord. In the Django Admin, when adding an attendance record, I would like to change the options for the field Absent_Students based on the selection made for the field Associated_Class. So, for example, if Associated_Class "CS 450" is selected, the options for Absent_Students should change to only students whose class_list includes CS 450.
Here are my models:
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from django.utils.encoding import python_2_unicode_compatible
import random, string
# Create your models here.
#This is the model for a student
#python_2_unicode_compatible
class Student(models.Model):
pass
Student_First_Name = models.CharField(max_length=200)
Student_Last_Name = models.CharField(max_length=200)
Student_ID_Number = models.CharField(max_length=200)
Student_Class = models.ForeignKey('Class', null=True)
def __str__(self):
return self.Student_Last_Name + ',' + self.Student_First_Name
# This is the model for a class
#python_2_unicode_compatible
class Class(models.Model):
class Meta:
verbose_name_plural = "Classes"
Class_Name = models.CharField(max_length=200)
Student_List = models.ManyToManyField('Student', related_name='class_list')
Professor = models.ForeignKey(User,null=True)
AddCode = models.IntegerField
pass
def __str__(self):
return self.Class_Name
def getName(self):
return self.Class_Name
def getProfessor(self):
return self.Professor.id
def getProf(self):
return self.Professor
def getStudents(self):
return self.Student_List
#This is the model for attendance records
class AttendanceRecord(models.Model):
class Meta:
verbose_name = "Attendance Record"
Associated_Class = models.ForeignKey(Class, on_delete=models.CASCADE, related_name='Attendance_Records')
Date = models.DateField()
Absent_Students = models.ManyToManyField('Student', blank=True)
Present_Students = models.ManyToManyField('Student', related_name='a')
def get_associated_class_id(self):
return self.Associated_Class
def __str__(self):
return self.Associated_Class.__str__() + ' on date ' + self.Date.__str__(self)
I have tried doing this by editing the AttendanceRecordAdminForm class and AttendanceRecordAdmin class. My problem is that when setting the self.fields['Absent_Students].queryset I do not know how to access the currently selected Associated_Class on the form. I keep getting an error that "AttendanceRecord has no Associated_Class". Here are those classes just discussed in their entirety:
class AttendanceRecordAdminForm(forms.ModelForm):
class Meta:
model = AttendanceRecord
fields = '__all__'
def __init__(self, *args, **kwargs):
super(AttendanceRecordAdminForm, self).__init__(*args, **kwargs)
instance = kwargs.get('instance', None)
self.fields['Absent_Students'].queryset = Student.objects.filter(class_list__id=self.instance.get_associated_class_id())
self.fields['Present_Students'].queryset = Student.objects.filter(class_list__id=1)
class AttendanceRecordAdmin(admin.ModelAdmin):
form = AttendanceRecordAdminForm
filter_horizontal = ('Absent_Students', 'Present_Students',)
Basically, I am looking for a way to access the currently entered Associated_Class on the admin form so I can properly filter the queryset.
After hours more of online searching I finally found what I needed. A chained ManyToMany from the smart_select app makes this very easy. This link: How to use django-smart-select describes the install process and also links to the documentation for using it once it is installed. Hopefully this helps some others as well.

Is it possible to save the primary key value of more than one fields of a model into an another model's single 'field' using foreign key relation?

models.py:
import datetime
from django.db import models
from pygments.lexers import get_all_lexers
LEXERS = [item for item in get_all_lexers() if item[1]]
class Classname(models.Model):
class_name = models.CharField(max_length=8)
def __str__(self):
return self.class_name
class Sectionname(models.Model):
class_name = models.ForeignKey(Classname)
section_name = models.CharField(max_length=1, default='A')
def __str__(self):
return self.section_name
class Teachername(models.Model):
field = """ I want to define here a foreign key field(inherited from Sectionname model)which saves the primary key value of row corresponding to two fields (class_name, section_name) above."""
teachname = models.CharField(max_length=50, verbose_name='teacher Name')
def __str__(self):
return self.teachname
class Attendancename(models.Model):
teacher_name = models.ForeignKey(Teachername)
date = models.DateField('Date')
intime = models.TimeField('IN-TIME')
outtime = models.TimeField('OUT-TIME')
def hours_conversion(self):
tdelta = (datetime.datetime.combine(datetime.date.today(),self.outtime) - datetime.datetime.combine(datetime.date.today(),self.intime))
hours, minutes = tdelta.seconds//3600, (tdelta.seconds//60)%60
return '{0}hrs {1}mins'.format(hours, minutes)
def __str__(self):
return "%s" %self.teacher_name
forms.py:
from django import forms
from django.forms import ModelForm
from .models import Classname, Sectionname, Teachername, Attendancename
class ClassnameForm(ModelForm):
class_name = forms.CharField(max_length=8)
class Meta:
model = Classname
fields = ('class_name',)
class SectionnameForm(ModelForm):
class_name = forms.ModelChoiceField(queryset=Classname.objects.all())
class Meta:
model = Sectionname
fields = ('section_name', 'class_name',)
class TeachernameForm(ModelForm):
field = """ Here I also want to do the same thing, I tried to make a form field, which shows value of both 'section_name' and 'class_name' from above model but only saves the value of corresponding row's primary key."""
class Meta:
model = Teachername
fields = ('classname', 'secname', 'teachname',)
class AttendancenameForm(ModelForm):
teacher_name = forms.ModelChoiceField(queryset=Teachername.objects.all())
class Meta:
model = Attendancename
fields = ('teacher_name', 'date', 'intime', 'outtime',)
I'm trying to save the 'pk' value of Sectionname model fields('calss_name', 'section_name') into Terachername model's single 'field', I also want to show the both the values to user using form field 'field', but behined the scenes only primary key values needs to be saved.
Is it possible to do so? If it is then how can I implement it in my app?
Please! provide your suggestions....
Thanks! in advance.....
You cannot store two foreign keys to two different tables in a single models.ForeignKey field, and it really wouldn't make any sense (if the reason is not obvious to you then you should learn more about relational model).
But anyway: since a Sectionname belongs to one single Classname, you don't need anything else than the Sectionname pk to get the related Classname:
class Teachername(models.Model):
sectionname = models.ForeignKey(Sectionname)
teachname = models.CharField(max_length=50, verbose_name='teacher Name')
def __str__(self):
return self.teachname
teacher = Teachername.objects.get(pk=XXX)
print teacher, teacher.sectionname, teacher.sectionname.classname
Or if a teacher is supposed to teach more than one section:
class Teachername(models.Model):
sectionnames = models.ManyToMany(Sectionname)
teachname = models.CharField(max_length=50, verbose_name='teacher Name')
def __str__(self):
return self.teachname
teacher = Teachername.objects.get(pk=XXX)
for sectionname in teacher.sectionnames.all():
print teacher, sectionname.classname

Categories

Resources