Django error: has no attribute 'ForeingKey' - python

everyone!
I jus start leaning Python and Django. Can somebody help me with this topic. I can't understand why it doesn't work:
from django.db import models
# Create your models here.
class Topic(models.Model):
""" Тема которую изучает ползователь"""
text = models.CharField(max_length = 200)
date_added = models.DateTimeField(auto_now_add = True)
def __str__(self):
"""возвращает представление модели"""
return self.text
class Entry(models.Model):
""" Информация изученная пользователем """
topic = models.ForeingKey(Topic)
text = models.TexField()
date_added = models.DateTimeField(auto_now_add = True)
class Meta:
verbose_name_plural = 'entries'
""" Возвращает строковое представление модели"""
def __str__(self):
return self.text[:50] + "..."
The result is:
File "/Users/stepankurakin/pystudy/learning_log/learning_logs/models.py", line 14, in Entry
topic = models.ForeingKey(Topic)
AttributeError: module 'django.db.models' has no attribute 'ForeingKey'
How can i fix it?

I think you should fix the typo as first thing, and try again: it's ForeignKey.
The error AttributeError is usually triggered when you are asking an attribute (in this case the class ForeignKey) to an object that doesn't have that attribute. If you commit an error in the spelling you will see this exception.

Related

Django Models,There's a column in the table, but it cannot be referenced from this part of the query,

I've defined some models in django and I can successfully add data to them using objects in django but the problem is that when I try to do this directly from the database it gives me this "HINT" There's a column named origin_id in the table flight, but it cannot be referenced from this part of the query, I'm using postgresql for the database, So can anyone please help me with this? I know there are similar questions like this but I couldn't find the solution.
class AirportManager(models.Manager):
#classmethod
def ret(cls):
return 'This is a custom "Manager"'
#classmethod
def code(cls):
obj = Airport.objects.all()
return obj
class Airport(models.Model):
code = models.CharField(max_length = 3)
city = models.CharField(max_length = 20)
objects = AirportManager()
class Meta:
db_table = 'airport'
def __str__(self):
return f"{self.city} ({self.code})"
class Flight(models.Model):
origin = models.ForeignKey(Airport,on_delete=models.CASCADE)
destination = models.ForeignKey(Airport,on_delete=models.CASCADE,related_name = "arrivals")
duration = models.IntegerField()
flights = models.Manager()
class Meta:
db_table = 'flight'
def __str__(self):
return f'from "{self.origin}" to "{self.destination}" in "{self.duration}" hrs'

Getting Attribute error on using icontains

my two model class:
class Bank(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Branch(models.Model):
ifsc = models.CharField(max_length=200)
name = models.CharField(max_length=200)
address = models.TextField(max_length=200)
city = models.CharField(max_length=200)
state = models.CharField(max_length=200)
bank = models.ForeignKey(Bank, on_delete=models.CASCADE,max_length=200)
def __str__(self):
return f"{self.name}"
serializer classes,
class BankSerializer(serializers.ModelSerializer):
class Meta:
model = Bank
fields = '__all__'
class BranchSerializer(serializers.ModelSerializer):
bank = serializers.CharField(source='bank.name', read_only=True)
class Meta:
model = Branch
fields = ["ifsc","name","address","city","state","bank"]
and Views.py
class CityBankNameView(APIView):
def get_object(self, bank_name, city_name):
try:
bank = Bank.objects.get(name=bank_name)
branches = Branch.objects.filter(bank__icontains=bank, city=city_name) #<-- icontains
return branches
except:
return HttpResponse(status=status.HTTP_404_NOT_FOUND)
def get(self,request, bank_name, city_name):
branches = self.get_object(bank_name, city_name)
serializer = BranchSerializer(branches, many=True)
return Response(serializer.data)
I am getting attribute error when using bank__icontains
exact error:
AttributeError at /branches/DELHI/AXIS BANK
Got AttributeError when attempting to get a value for field ifsc on serializer BranchSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the bytes instance.
Original exception text was: 'bytes' object has no attribute 'ifsc'.
I am trying for hours but cannot find any solution to it. I seen various answers but none of them helps solve this one
bank__icontains= expects bank to be a string object, not a Bank object. You can thus rewrite the query to:
branches = Branch.objects.filter(bank=bank, city=city_name)
or if you want the Branches for which the name of the bank contains bank_name, you can filter with:
branches = Branch.objects.filter(bank__name__icontains=bank_name, city=city_name)

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__'

State Control/Workflow in Django

I'm having an object with a few fields such as order line, reference no, state
the state is a selection of draft and confirmed
what I want is when the record's state is confirmed, the other field can't be modified/ readonly
what's the best / common way to do this in django ?
thanks
I tired it with 3 example fields.
I create a model with 3 fields:
class New(models.Model):
title = models.CharField(max_length=100,unique=True)
body = models.TextField()
editable = models.BooleanField(default=True)
def __unicode__(self):
return self.title
My forms.py code is:
class MyNewForm(forms.ModelForm):
class Meta:
model = New
def clean(self):
cleaned_data = super(MyNewForm,self).clean()
title = cleaned_data.get('title')
body = cleaned_data.get('body')
editable = cleaned_data.get('editable')
if self.instance.pk:
try:
row = New.objects.get(id=self.instance.pk)
except New.DoesNotExist:
raise forms.ValidationError('Record not found')
if not row.editable and not editable:
raise forms.ValidationError('This record is not editable')
return cleaned_data
And my admin.py code is:
from news.models import New
from news.forms import MyNewForm
class MyNew(admin.ModelAdmin):
form = MyNewForm
admin.site.register(New,MyNew)
Hope it works fine for you.
A true/false field (i.e. the BooleanField) can do the job. Read the docs here: https://docs.djangoproject.com/en/dev/ref/models/fields/#booleanfield

django views question

In my django views i have the following
def create(request):
query=header.objects.filter(id=a)[0]
a=query.criteria_set.all()
logging.debug(a.details)
I get an error saying 'QuerySet' object has no attribute 'details' in the debug statement
.What is this error and what should be the correct statemnt to query this.And the model corresponding to this is as follows
where as the models has the following:
class header(models.Model):
title = models.CharField(max_length = 255)
created_by = models.CharField(max_length = 255)
def __unicode__(self):
return self.id()
class criteria(models.Model):
details = models.CharField(max_length = 255)
headerid = models.ForeignKey(header)
def __unicode__(self):
return self.id()
Thanks..
QuerySet.all() returns a QuerySet. Index it or iterate over it if you want to access the individual models:
logging.debug(a[0].details)
for m in a:
logging.debug(m.details)

Categories

Resources