AttributeError on Django - python

I'm stuck with (I think) a dummy error on Django that I can't find where it's the fault.
On "catalog/models.py" I have (it connects to a MySQL database):
from django.db import models
class Application(models.Model):
nameApp = models.CharField(max_length=50)
tarification = models.ForeignKey(Tarification)
Then, I'm using django-tables2 (Doc to fill tables) to make tables on Django, so on my tables.py I have:
import django_tables2 as tables
from catalog.models import AppCost, Application, Tarification
class BillTable(tables.Table):
class Meta:
appName = Application.nameApp
userApp = AppCost.userApp
tarifName = Tarification.nameTarif
tarifCost = Tarification.cost
startTime = AppCost.startTime
finishTime = AppCost.finishTime
totalCost = AppCost.totalCost
# add class="paleblue" to <table> tag
attrs = {'class': 'paleblue'}
And I get an error when I render my website:
type object 'Application' has no attribute 'nameApp'
On the line appName = Application.nameApp from BillTable
But, looking at "Database" window on Pycharm I see the table schema and it's:
catalog_application
id
tarification_id
nameApp
other stuff
And looking with MySQL Workbench the schema looks the same. So, why I'm getting this error?
Regards.

As Daniel Roseman mentioned above, the code you might looking for is below, it does not need a new model:
import django_tables2 as tables
from catalog.models import AppCost, Application, Tarification
class AppCostTable(tables.Table):
userApp = tables.Column()
startTime = tables.Column()
finishTime = tables.Column()
totalCost = tables.Column()
class Meta:
model = AppCost
class ApplicationTable(tables.Table):
appName = tables.Column(accessor='nameApp')
class Meta:
model = Application
class TarificationTable(tables.Table):
tarifName = tables.Column(accessor='nameTarif')
tarifCost = tables.Column(accessor='cost')
class Meta:
model = Tarification
class BillTable(AppCostTable, ApplicationTable, TarificationTable, tables.Table):
pass
If you do not mind to have another model, then inside your catalog.models you can add a new Bill model:
class Bill(models.Model):
application = models.ForeignKey('Application')
appcost = models.ForeignKey('AppCost')
tarification = models.ForeignKey('Tarification')
In your table file:
from catalog.models import Bill
class BillTable(tables.Table):
appName = tables.Column(accessor='application.nameApp')
tarifName = tables.Column(accessor='tarification.nameTarif')
tarifCost = tables.Column(accessor='tarification.cost')
userApp = tables.Column(accessor='appcost.userApp')
startTime = tables.Column(accessor='appcost.startTime')
finishTime = tables.Column(accessor='appcost.finishTime')
totalCost = tables.Column(accessor='appcost.totalCost')
class Meta:
model = Bill

You're very confused about how to use django-tables. You need to specify one model in the Meta class, then just the fields attribute to add a list of fields from that model, as strings, to display. You can't just specify fields from three arbitrary models.

Related

Nested Relationship in Django Doesn't Work

These are my models here:
class Site(models.Model):
siteID = models.CharField(max_length=255, primary_key=True)
class EndDevice(models.Model):
class Meta:
unique_together = ("edevID", "siteID")
edevID = models.CharField(max_length=255)
siteID = models.ForeignKey(Site, related_name='endDeviceList', on_delete=models.CASCADE)
deviceCategory = models.BigIntegerField()
This is my serilaizer:
class DeviceSerializer(serializers.ModelSerializer):
class Meta:
model = EndDevice
fields = ("edevID", "siteID", "deviceCategory")
class SiteSerializer(serializers.ModelSerializer):
endDeviceList = DeviceSerializer(many = True, read_only=True)
class Meta:
model = Site
fields = ("siteID", "endDeviceList")
This is my view:
class IndividualSite(generics.RetrieveUpdateDestroyAPIView):
'''
PUT site/{siteID}/
GET site/{siteID}/
DELETE site/{siteID}/
'''
queryset = EndDevice.objects.all()
serializer_class = SiteSerializer
I am trying to get/put/delete results using this class and I am trying to get all the EndDevice instances which have same siteID. But my serialzer only shows the siteID and doesn't show the endDeviceList (which should have the instants of the model EndDevice)
The problem is quite similar to this link:django rest-farmework nested relationships.
I have been trying different ways to serialize the objects, I think this is probably the smartest way, but have been really unsucccessful. Any help will be appreciated.
The urls.py:
urlpatterns = [
urlpatterns = [path('site/<str:pk>/', IndividualSite.as_view(), name = "get-site"),]
And it is connected to the main urls.
you are using read_only field for the Foreign relationship, remove that, as read_only wont display them
class SiteSerializer(serializers.ModelSerializer):
endDeviceList = DeviceSerializer(many = True)

django-tables2 custom column

I'm working now on my first Django project. I want to render results table which contains all fields from Priekabos model and one custom column from Grafikas which should contain something similar to:
SELECT max(kada_moketi) FROM grafikas WHERE priekabos_id = ?
Whatever I try from examples nothing works. Should I write another view function with that custom query:
(Grafikas.objects.filter(priekabos_id=1)
neither with:
.aggregate(Max('kada_moketi')
neither with:
.latest('kada_moketi')
worked for me I created a new table class in tables.py which later PriekabosTable will inherit? That didn't work for me too.
Here's my code:
models.py
class Grafikas(models.Model):
id = models.AutoField(primary_key=True)
mokejimo_nr = models.IntegerField()
kada_moketi = models.DateField()
priekabos = models.ForeignKey('Priekabos', models.DO_NOTHING)
class Priekabos(models.Model):
id = models.AutoField(primary_key=True)
sutarties_nr = models.CharField(unique=True, max_length=45, verbose_name='Sut. Nr.')
nuomos_pradz = models.DateField()
sutarties_trukme = models.IntegerField()
views.py
def priekabos_table(request):
table = PriekabosTable(Priekabos.objects.all())
RequestConfig(request, paginate={'per_page': 20}).configure(table)
return render(request, 'isperkamoji_nuoma/priekabos_table.html', {'table': table})
tables.py
class PriekabosTable(tables.Table):
class Meta:
model = Priekabos
attrs = {"class": "paleblue"}
fields = ('id', 'sutarties_nr', 'nuomos_pradz')
For better understanding, here's 'grafikas' table:
MySQL 'grafikas' table
It sounds like you might be able to fetch the extra field using annotate.
from django.db.models import Max
queryset = Priekabos.objects.annotate(max_kada_moketi=Max('grafikas__kada_moketi'))
table = PriekabosTable(queryset)
Remember to add the field to your table.
class PriekabosTable(tables.Table):
class Meta:
model = Priekabos
attrs = {"class": "paleblue"}
fields = ('id', 'sutarties_nr', 'nuomos_pradz', 'max_kada_moketi')

Manytomany field in Django mongoengine Document

I have the following Django model:
from mongoengine import *
from datetime import datetime
class Company(Document):
name = StringField(max_length=500)
class Feedback(Document):
text = StringField(max_length=500)
is_approved = BooleanField(default=False)
date = DateTimeField(default=datetime.now())
I want to add a manytomany field of Feedback in Company
Thanks in advance.
This is not a Django model, but a mongoengine Document. It does not have ManyToManyField. Instead you should probably add a ReferenceField inside a ListField to your Company class, like this:
class Company(Document):
name = StringField(max_length=500)
feedbacks = ListField(ReferenceField(Feedback))
class Feedback(Document):
text = StringField(max_length=500)
is_approved = BooleanField(default=False)
date = DateTimeField(default=datetime.now())
Source: http://docs.mongoengine.org/guide/defining-documents.html#one-to-many-with-listfields

How to deal with circular imports in tastypie

I'm currently developing a django-tastypie web app.
I've two django models :
class Student(models.Model):
name = models.CharField()
class Course(models.Model):
name = models.CharField()
student = models.ForeignKey(Student)
And from that, I've two Tastypie resources in two different files.
But here comes my problem. I want to be able to filter student from course, and course from student :
from website.api.course import CourseResource
class StudentResource(ModelResource):
course = fields.ForeignKey(CourseResource, "course")
class Meta:
queryset = Student.objects.all()
resource_name = "student"
filtering = { "course" : ALL }
and
from website.api.student import StudentResource
class CourseResource(ModelResource):
student = fields.ForeignKey(StudentResource, "student")
class Meta:
queryset = Course.objects.all()
resource_name = "course"
filtering = { "student" : ALL }
But of course, I got a circular import issue. How could I solve that ?
Thanks !
You don't need to import the other resource in each module. Try using a string as the argument instead.
class StudentResource(ModelResource):
course = fields.ForeignKey('website.api.course.CourseResource', "course")
class CourseResource(ModelResource):
student = fields.ForeignKey('website.api.student.StudentResource', "student")

list Box Django Forms

I'm using Django forms and need to create a list box.
What would be the equivalent of listbox in Django form fields?
I checked the documentation #
https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield
but unable to find it.
Here is my code snippet,
Models.py
class Volunteer(models.Model):
NO_OF_HRS = (('1','1')
('2','2'))
datecreated = models.DateTimeField()
volposition = models.CharField(max_length=300)
roledesc = models.CharField(max_length=300)
Duration = models.CharField(choices=NO_OF_HRS,max_length=1)**
forms.py
class VolunteerForm(forms.ModelForm)
datecreated = forms.DateField(label=u'Creation Date')
volposition = forms.CharField(label=u'Position Name', max_length=300)
roledesc = forms.roledesc(label=u'Role description',max_length=5000)
Duration = forms.CharField(widget=forms.select(choices=NO_OF_HRS),max_length=2)
When I try to run, I get the following error,
NO_OF_HRS is not defined
Your NO_OF_HRS tuple is defined inside the model and not available to the form. It has to be imported in forms.py just like any other Python object. Try moving the tuple outside the model definition and import in your forms.py like this:
models.py
NO_OF_HRS = (('1','1')
('2','2'))
class Volunteer(models.Model):
# ...
duration = models.CharField(choices=NO_OF_HRS, max_length=1)
forms.py
from path.to.models import NO_OF_HRS
class VolunteerForm(forms.Form):
# ...
duration = forms.CharField(widget=forms.Select(choices=NO_OF_HRS), max_length=1)
It also looks like you want to use a ModelForm. In this case you don't need to add any field definitions to your VolunteerForm, simply set your model in the inner Meta class.
forms.py
from path.to.models Volunteer
class VolunteerForm(forms.ModelForm):
class Meta:
model = Volunteer

Categories