"Unresolved attribute reference 'objects' for class 'Album' " in django using Pycharm - django-models

I follow bucky's tutorial for DJANGO and in my views file in line:
"all_albums = Album.objects.all()" PYCHARM gives a warning: " Unresolved attribute reference 'objects' for class 'Album'" HERE IS MY CODE. Any help will be apreciated
AVRAAM AVRAMOPOULOS
----------------------------
from django.db import models
class Album(models.Model):
artist = models.CharField(max_length=250,)
album_title = models.CharField(max_length=250)
genre = models.CharField(max_length=100)
album_logo = models.CharField(max_length=1000)
def __str__(self):
return str(self.album_title) + "-" + str(self.artist)
class Song(models.Model):
album = models.ForeignKey(Album, on_delete=models.CASCADE)
file_type = models.CharField(max_length=10)
song_title = models.CharField(max_length=250)
# my views file/
from django.shortcuts import render
from django.http import HttpResponse
from .models import Album
def index(request):
all_albums = Album.objects.all()
html = ''
for album in all_albums:
path = '/music/' + str(album.id) + '/'
html += '' + album.album_title + '<br/>'
return HttpResponse(html)
def detail(request, album_id):
return HttpResponse('<h2>Details for Album_id: ' + str(album_id) + '</h2>')

Your code is fine and you'll be able to run it despite this warning from PyCharm. The warning is only on your PyCharm IDE, because Django specific PyCharm features aren't available. To get those you need the professional edition of PyCharm and enable Django support here:
PyCharm / Preferences / Languages & Frameworks / Django

repost: in your Class definition, include a shortcut definition:
class MyPersistent(models.Model):
objects = models.Manager()

Related

URL with dot in Django Rest Framework

I have the following model with a primary_key=True specified:
class Team(models.Model):
name = models.CharField(
max_length=64,
primary_key=True,
)
... other fields
When I serialize this model, I do the following:
class TeamSerializer(serializers.ModelSerializer):
class Meta:
model = Team
fields = ('url', 'name',) # and another fields
My viewset:
class TeamViewSet(viewsets.ModelViewSet):
lookup_value_regex = '[-\w.]'
queryset = Team.objects.all()
serializer_class = TeamSerializer
filter_fields = ('name',) # and another fields
My urls.py:
router = routers.DefaultRouter()
router.register(r'teams', TeamViewSet)
urlpatterns = [
url(r'^api/', include(router.urls)),
# I am not sure if this url is right. I repeat of include(router.urls)
url(r'^api/teams/(?P<name>[-\w.]+)/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
Then, when I create a Team object with name attribute containing dot ., for example Latinos F.C. and I go to the rest url, I get:
I am not sure about of how to use the lookup_value_regex attribute in my viewset. In this answer is used with some basic regex, but if I use it, any Team object is reachable via my serialized Rest API.
How to can I get a url like as: /api/teams/Name.F.C. in my serialized Team model?
First of all check if you have set APPEND_SLASH to True in your settings, because if not - the missing slash (at the end of the URL) is a problem.
Second - I do not think that dot is a problem, the problem can be a space - coded as %20;
Third - such urls looks just ugly :) You should consider changing it to some kind of a slugs: Latinos F.C. -> latinos-fc;
If you do that (just add additional field on the model with slug - this field should be obviously unique) - set up the lookup_field on your view - this will solve your problem.
Consider the example:
views.py
class SomeViewSet(viewsets.ModelViewSet):
queryset = SomeModel.objects.all()
serializer_class = SomeSerializer
lookup_field = 'slug_name'
serializers.py
class SomeSerializer(serializers.ModelSerializer):
class Meta:
model = SomeModel
fields = ('id', 'name', 'slug_name')
read_only_fields = ('slug_name',)
def to_internal_value(self, data):
ret = super(SomeSerializer, self).to_internal_value(data)
ret['slug_name'] = slugify(ret['name'])
return ret
models.py
class SomeModel(models.Model):
name = models.CharField(max_length=100)
slug_name = models.SlugField(unique=True, max_length=100)
urls.py
router.register(r'teams', SomeViewSet, base_name='teams')
urlpatterns = router.urls
And now:
creation:
details:
Can you do that this way? Or you really need the dots?

GAE simple data model error '_ReverseReferenceProperty' object has no attribute 'fetch'

I have one-to-many model scheme. All seems correct, data population works but linkitem_set.fetch fails with:
AttributeError: '_ReverseReferenceProperty' object has no attribute
'fetch'
There also one question here on SO with the same error but without solution.
My code below:
class Project(db.Model):
name = db.StringProperty()
class LinkItem(db.Model):
url = db.StringProperty()
project = db.ReferenceProperty(Project)
class Show(webapp2.RequestHandler):
def get(self):
links = Project.linkitem_set.fetch(100)
self.response.headers['Content-Type'] = 'text/plain'
for li in links:
self.response.out.write(li + '/r/n')
class PopulateDb(webapp2.RequestHandler):
def get(self):
prj = Project(name = 'SomeProject 1')
prj.put()
for i in range(1000):
rlink = random.betavariate(1, 2)
link = LinkItem(url = str(rlink), project = prj)
link.put()
I'm using Python 2.7 and tested this localy and hosted.
I think that the problem is that the linkitem_set collection will only exist for an instance of Project, but you are trying to use it on the class itself.
Your code should look something more like this:
class Show(webapp2.RequestHandler):
def get(self):
prj_name = "" # Get a valid value, probably from URL params
prj_to_show = Project.all().filter("name=", prj_name).get()
if prj_to_show is not None:
links = prj_to_show.linkitem_set.fetch(100)
self.response.headers['Content-Type'] = 'text/plain'
for li in links:
self.response.out.write(li + '/r/n')

Using GeoDjango model as an abstract class

I'm playing with GeoDjango and have some doubts. I'll really appreciate any comment and suggestion.
This is my problem. First, I've defined this (abstract) class:
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
class LocatableModel(models.Model):
country = models.CharField(max_length=48, blank=True)
country_code = models.CharField(max_length=2, blank=True)
locality = models.CharField(max_length=48, blank=True)
sub_locality = models.CharField(max_length=48, blank=True)
street = models.CharField(max_length=48, blank=True)
address = models.CharField(max_length=120, blank=True)
point = models.PointField(null=True)
objects = models.GeoManager()
class Meta:
abstract = True
Second, I've defined this other 'Entity' class, which
represents a person or organization related to my site:
from django.db import models
class Entity(models.Model):
name = models.CharField(max_length=64)
slug = models.SlugField(max_length=64, unique=True)
website = models.URLField(verify_exists=False, blank=True)
email = models.EmailField(blank=True)
...
Finally, I've created a class from the previous ones:
import LocatableModel
import Entity
class Organization(Entity, LocatableModel):
timetable = models.CharField(max_length=64)
...
In my views, I'd like to find organizations near a specific point:
from django.contrib.gis.geos import Point
from django.contrib.gis.measure import D
def index(request):
pnt = Point(12.4604, 43.9420)
dic = { 'orgs': Organization.objects.filter(point__distance__lte=(pnt, D(km=7))) }
return render_to_response('index.html', dic)
But I receive the error:
"Join on field 'point' not permitted. Did you misspell 'distance' for
the lookup type?"
I think I'm doing a mess with the model 'objects' property, but I'm not sure. Any ideas?
Thanks in advance.
This error has been seen before, and claimed to be solved in this ticket 3 years ago:
https://code.djangoproject.com/ticket/9364
When I ran into this same problem, I noticed in the ticket that the query manager was set explicitly to GeoManager in the inherited model(s). So adding a line like,
class Organization(Entity, LocatableModel):
timetable = models.CharField(max_length=64)
...
objects = models.GeoManager()
...may solve the issue you're seeing, it worked for me.

Error while implementing django models . How to debug?

Error: One or more models did not validate:
maps.parking: 'layer_id' has a relation with model sdr_layer.Sdr_layer, which has either not been installed or is abstract.
This is the error that I have .
My maps/models.py looks like this
# This is an auto-generated Django model module created by ogrinspect.
from django.contrib.gis.db import models
class Parking(models.Model):
layer_id= models.ForeignKey(sdr_layer.Sdr_layer)
name = models.CharField(max_length=80)
descriptio = models.CharField(max_length=80)
geom = models.PointField(srid=4326)
objects = models.GeoManager()
# Auto-generated `LayerMapping` dictionary for Parking model
parking_mapping = {
'name' : 'Name',
'descriptio' : 'Descriptio',
'geom' : 'POINT25D',
}
Where sdr_layer/models.py looks like this
from django.db import models
class Sdr_Layer(models.Model):
layer_name = models.CharField(max_length = 100)
layer_attribute_name = models.CharField(max_length = 100)
I basically want the Sdr_layer.id to act as the foreign key for the app maps .
Make sure sdr_layer is listed your INSTALLED_APPS in settings.py
I think you intended models.ForeignKey(sdr_layer.Sdr_Layer).

Relationships in Django Admin

I get really confused with many-to-many database relationships, so can some one please clarify how I would achieve this?
I need a table of "Tags" (as in tag words) and a table for "Entries", such at many "Entries" could correspond to many Tag words.
Right now I have my models like this:
# models.py
class Tags(models.Model):
tag = models.CharField(max_length=255)
entry = models.ManyToManyField(Entry)
class Entry(models.Model):
entry = models.CharField(max_length=255)
description = models.TextField()
Now I'm confused, how would I setup my admin.py so I could then add tags when I create a new entry?
What you need is using the through feature of models:
class Tag(models.Model):
tag = models.CharField(max_length=255)
entry = models.ManyToManyField(Entry, through='TaggedEntries')
class Entry(models.Model):
entry = models.CharField(max_length=255)
description = models.TextField()
class TaggedEntries(models.Model):
entry = models.ForeignKey(Entry)
tag = models.ForeignKey(Tag)
and now use that model in your admin:
class TagsInline(admin.TabularInline):
model = TaggedEntries
extra = 1
class EntryAdmin(admin.ModelAdmin):
inlines = (TagsInline, )
admin.site.register(Entry, EntryAdmin)
admin.site.register(Tag)
You will need something along the lines of:
# admin.py
from django.contrib import admin
from models import *
class TagsInline(admin.TabularInline):
model = Tag
extra = 1
class EntryAdmin(admin.ModelAdmin):
inlines = (TagsInline, )
admin.site.register(Entry, EntryAdmin)
admin.site.register(Tag)
(Note, this code was written in a browser!)

Resources