django views question - python

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)

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'

I can't access the primary key in django?

I am sure I have made a rookie mistake somewhere down here.
So I have a details page for a particular link. Suppose I have list of incubators on my page, and if I click on one of them, I want to show its details. I am sure this can be done by using primary key but I keep getting errors.
models.py
class Incubators(models.Model):
# I have made all the required imports
incubator_name = models.CharField(max_length=30)
owner = models.CharField(max_length=30)
city_location = models.CharField(max_length=30)
description = models.TextField(max_length=100)
logo = models.FileField()
verify = models.BooleanField(default = False)
def get_absolute_url(self):
return reverse('main:details', kwargs={'pk': self.pk})
def __str__(self): # Displays the following stuff when a query is made
return self.incubator_name + '-' + self.owner
class Details(models.Model):
incubator = models.ForeignKey(Incubators, on_delete = models.CASCADE)
inc_name = models.CharField(max_length = 30)
inc_img = models.FileField()
inc_details = models.TextField(max_length= 2500)
inc_address = models.TextField(max_length = 600, default = "Address")
inc_doc = models.FileField()
inc_policy = models.FileField()
def __str__(self):
return self.inc_name
views.py
def details(request, incubator_id):
inc = get_object_or_404(Incubators, pk = incubator_id)
return render(request, 'main/details.html', {'inc': inc})
This is my urls.py but I'm sure there's no error here:
url(r'^incubators/(?P<pk>[0-9]+)', views.details, name = 'details'),
Can you explain a little why I am getting this error?
TypeError at /incubators/9
details() got an unexpected keyword argument 'pk'
Request Method: GET
Request URL: http://127.0.0.1:8000/incubators/9
Django Version: 1.11.3
Exception Type: TypeError
Exception Value:
details() got an unexpected keyword argument 'pk'
In your URL patterns, you're calling the variable "pk" but in your view you're calling it incubator_id
To fix this, change your URL pattern from:
url(r'^incubators/(?P<pk>[0-9]+)', views.details, name = 'details'),
to
url(r'^incubators/(?P<incubator_id>[0-9]+)', views.details, name = 'details'),

Django error: has no attribute 'ForeingKey'

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.

'ModelChoiceField' object has no attribute 'objects'

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.

Django foreign key question

All,
i have the following model defined,
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()
class options(models.Model):
opt_details = models.CharField(max_length = 255)
headerid = models.ForeignKey(header)
def __unicode__(self):
return self.id()
AND IN MY VIEWS I HAVE
p= header(title=name,created_by=id)
p.save()
Now the data will be saved to header table .My question is that for this id generated in header table how will save the data to criteria and options table..Please let me know..
Thanks..
Given your:
p= header(title=name,created_by=id)
p.save()
You can now:
c=criteria(details='some details', headerid=p)
c.save()
o=options(opt_details='more details', headerid=p)
o.save()
Hope this helps.
Take advantage of <related>_set query managers, it's clearer and shorter than constructing and saving objects in separate operations.
h = header.objects.create(title=name,created_by=id)
c = h.criteria_set.create(details='some details')
o = h.options_set.create(opt_details='more details')
And some offtopic: please, start class names from uppercase letter, it really makes code easier to read.

Categories

Resources