django: cant import models from global app - python

Trying to import models from different app in views.py:
from global.models import Global
Console raise an error:
from global.models import Global
^
SyntaxError: invalid syntax
I checked a lot of information, but cant find what iam doing wrong.
global.models.py
from django.db import models
# Create your models here.
class Global(models.Model):
phone = models.CharField(max_length=50, blank=True)
email = models.EmailField(max_length=50, blank=True)
adress = models.CharField(max_length=100, blank=True)
class Meta:
verbose_name = 'Глобальные настройки'
verbose_name_plural = 'Глобальные настройки'
def __str__(self):
return 'Глобальные настройки'
projects.views.py
from django.shortcuts import render, redirect, get_object_or_404
from global.models import Global
from .models import Advertising, Films, Presentations, AuthorsLeft, AuthorsRight, BackstageImg
from django.utils import timezone
in my editor 'global' has blue color, and if i try to import another app it works normally. Could it be that 'global' reserved by django, or i simply doing something wrong?

from django.db.models.loading import get_model
global_model = get_model('global', 'Global')
You can use it, like this:
first_instance = global_model.objects.first()
print("Phone: {}".format(first_instance.phone))

Related

ModuleNotFoundError: No module named 'musiclibrary.song'

There is an issue while importing model 'Artist' of my django app in views.py.
from musiclibrary.song.models import Artist
when I runserver it gives ModuleNotFoundError.
from django.shortcuts import render
from django.http import HttpResponse
from musiclibrary.song.models import Artist
def hello_world(request):
return HttpResponse("Hello World!")
def home(request):
return render(request, "home.html")
def artist(request):
artist_list = Artist.objects.all(). //// I have to make this line of code work
context = {'artist_list': artist_list}
return render(request, 'artist.html', context)
Models code:
from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=250)
country = models.CharField(max_length=150)
birth_year = models.IntegerField()
genre = models.CharField(max_length=150)
class Song(models.Model):
Title = models.CharField(max_length=250)
release_date = models.IntegerField()
length = models.DateField()
artist = models.ForeignKey('Artist', on_delete=models.CASCADE)
Error log:
File "/Users/m.zcomputer/PycharmProjects/myFirstApp/musiclibrary/musiclibrary/views.py", line 4, in <module>
from musiclibrary.song.models import Artist
ModuleNotFoundError: No module named 'musiclibrary.song'
This is how my project is organized
You can go to:
PyCharm > Preferences > Project > Project Structure
Mark this module as Source
Like this
Apply > Ok
And try again.
you got that error bacause you don't import correctly.
from song.models import Artist
more :
when you want to import anything from your models.py or etc , you must import them from appname and your appname is song not musiclibrary.

django signals on inherited profile

I have User model and a user can be of type 1 or 2.
Depending on what type of user is created, I want to associate a profile to the model. If type 1, it will be a Person, and type 2 a Company.
I have tried writing the code in models.py and also following the tutorial : https://simpleisbetterthancomplex.com/tutorial/2016/07/28/how-to-create-django-signals.html
signals/apps/entitiesmodels.py
class CompanyModel(AuditedModel):
name = models.CharField(max_length=64, db_index=True, verbose_name='Name', null=True, blank=True)
class PersonModel(AuditedModel):
name = models.CharField(max_length=64, db_index=True, verbose_name='Name', null=True, blank=True)
class Tester(PersonModel,PersistentModel):
# Link with user
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, blank=True, related_name='%(class)s_user')
class Company(CompanyModel,PersistentModel):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, blank=True, related_name='%(class)s_user')
signals/apps/entities/signals.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from . import models as entities_models
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def user_create_profile(sender, instance, created, **kwargs):
if created:
if instance.user_type == 1:
entities_models.Tester.objects.create(user=instance)
elif instance.user_type == 2:
entities_models.Company.objects.create(user=instance)
else:
pass
signals/apps/entities/app.py
from django.apps import AppConfig
class EntitiesConfig(AppConfig):
name ='entities'
def ready(self):
import entities.signals
signals/apps/entities/api_v1/views.py
from signals.apps.entities import models
from . import serializers
from signals.libs.views import APIViewSet
class PersonViewSet(APIViewSet):
queryset = models.Person.objects.all()
serializer_class = serializers.PersonSerializer
signals/apps/entities/api_v1/urls.py
from rest_framework.routers import DefaultRouter
from signals.apps.entities.api_v1 import views
# Create a router and register our viewsets with it.
app_name='entities'
router = DefaultRouter()
router.register(r'persons', views.PersonViewSet, base_name="entities-persons")
urlpatterns = router.urls
settings.py
LOCAL_APPS = (
'signals.apps.authentication',
'signals.apps.entities.apps.EntitiesConfig',
)
When running server, the error is:
File "/home/gonzalo/Playground/signals3/signals/signals/apps/entities/api_v1/urls.py", line 2, in <module>
from signals.apps.entities.api_v1 import views
File "/home/gonzalo/Playground/signals3/signals/signals/apps/entities/api_v1/views.py", line 1, in <module>
from signals.apps.entities import models
File "/home/gonzalo/Playground/signals3/signals/signals/apps/entities/models.py", line 47, in <module>
class Person(PersonModel):
File "/home/gonzalo/.virtualenvs/signals-test/lib/python3.6/site-packages/django/db/models/base.py", line 108, in __new__
"INSTALLED_APPS." % (module, name)
untimeError: Model class signals.apps.entities.models.Person doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I have the example code on github if someone wants to check it out : https://github.com/gonzaloamadio/django-signals3
Thank for the answer, when using that way of referring an app on settings, then you should use the import like this:
signals/apps/entities/api_v1/views.py
from signals.apps.entities import models
and in urls.py
from entities.api_v1 import views

Trouble accessing object

I've been working on an issue all day and am at my wits end. I have two models with a manytomany relationship (bookmark, and boomark group). I am trying to access the bookmarks accosiated with the bookgroup in my view. When print the context to take a peak I get None returned. I've pasted the code below in a gist...any help would be so greatly appreciated.
models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from itertools import chain
import datetime
import hashlib
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django_mysql.models import JSONField, Model
from django.template.loader import render_to_string
from django.core.mail import send_mail
from django.utils import timezone
from django.conf import settings
class Bookmark(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
resource = models.ForeignKey("Resource", on_delete=models.CASCADE, related_name="bookmarks")
bookmark_groups = models.ManyToManyField("BookmarkGroup")
# meta
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
unique_together = ('user', 'resource',)
ordering = ('resource',)
def __str__(self):
return "{} | {}".format(self.user, self.resource)
class BookmarkGroup(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(null=False, unique=True)
bmark = models.ManyToManyField(Bookmark)
def __str__(self):
return self.name
views.py
from __future__ import unicode_literals
import json
from django.shortcuts import render, get_list_or_404
from django.http import JsonResponse
from django.views import View
from django.views.generic import DetailView
from app.serializers import BookmarkGroupSerializer
from app.models import Resource,Bookmark,ResourceShare,PrivateNote,BookmarkGroup
from app.views.resources import get_enriched_resources
class BookmarkGroupView(DetailView):
model = BookmarkGroup
def get_context_data(self, **kwargs):
context = super(BookmarkGroupView, self).get_context_data(**kwargs)
print(context['object'].bmark.resource)
return context
The key here is ManyToMany relationship, but you are trying to access it like a single object.
context['object'].bmark.all()[0].resource
OR
context['object'].bmark.first().resource
UPDATED:
With emptiness check
try:
resourse = context['object'].bmark.all()[0].resource
except:
resourse = None
OR
bmarks = context['object'].bmark.all()
resourse = bmarks[0].resource if bmarks else None

invalid literal for int() with base 10: 'iie27cmjouht24y424g44s5qlm999vcj' in django

I have the following views.py:
from django.template import loader
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from student.models import CustomUser
from student.forms import UserForm
from django.template.context_processors import csrf
from django.shortcuts import render_to_response
from django.contrib.auth.signals import user_logged_in
from .models import UserSession
def user_logged_in_handler(sender,request,CustomUser,**kwargs):
UserSession.objects.get_or_create(
user=CustomUser,
session_id= request.session.session_key
)
user_logged_in.connect(user_logged_in_handler)
def delete_user_sessions(CustomUser):
user_sessions=UserSession.objects.filter(user=CustomUser)
for user_session in user_sessions:
user_session.session.delete()
I have the following models.py:
class UserSession(models.Model):
user= models.ForeignKey(settings.AUTH_USER_MODEL)
session=models.ForeignKey(Session)
Also in models.py I have class CustomUser(AbstractUser). What's wrong in my views.py as the error says when I try to access /admin/
invalid literal for int() with base 10: 'iie27cmjouht24y424g44s5qlm999vcj'
The full models.py is as follows:
from django.utils import timezone
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from django.contrib.sessions.models import Session
class CustomUser(AbstractUser):
addr1= models.CharField(max_length=20)
addr2= models.CharField(max_length=20)
city= models.CharField(max_length=20)
state= models.CharField(max_length=20)
country= models.CharField(max_length=20,choices=country_choices)
pincode= models.IntegerField(default=0,blank=True,null=True)
securityq= models.CharField(max_length=20)
securitya= models.CharField(max_length=20)
class userresp(models.Model):
uid=models.ForeignKey(settings.AUTH_USER_MODEL,blank=True,null=True)
resp=models.CharField(max_length=20)
datetime=models.DateTimeField(default=timezone.now)
def __unicode__(self):
return u"{} {}".format(self.uid,self.datetime)
class Meta:
db_table="userresp"
class UserSession(models.Model):
user= models.ForeignKey(settings.AUTH_USER_MODEL)
session=models.ForeignKey(Session)
What can I do here?
he error is sorted...
def user_logged_in_handler(sender,request,user, **kwargs):
UserSession.objects.get_or_create(
user= user,
session_id= request.session.session_key
)
user_logged_in.connect(user_logged_in_handler, sender=CustomUser)
The error is coming from this line in your code session_id= request.session.session_key. Django expects the session id to be an int but the session key being generated is string. Check and make sure that you are asking for the correct data.

Django render is very slow

This is my training django project. I am using GeoIP, django-modeltranslation, i18n. Showing video gallery page is very slow. The database contains about 20 entries.
Model
from __future__ import unicode_literals
from django.db import models
from ckeditor_uploader.fields import RichTextUploadingField
from datetime import datetime
import urllib, json, re
from django.utils.translation import ugettext_lazy as _
class Video(models.Model):
class Meta:
abstract = True
title = models.CharField(max_length=80, unique=True)
text = RichTextUploadingField()
link = models.CharField(max_length=80)
slug = models.CharField(db_index=True,max_length=40,blank=True,null=True)
created_date = models.DateTimeField(auto_now_add=True)
pub_date = models.DateTimeField(default=datetime.now())
is_active = models.BooleanField(default=True)
position = models.IntegerField(default=0)
meta = models.TextField(blank=True,null=True)
def __unicode__(self):
return self.title
class VideoMessage(Video):
class Meta:
verbose_name = _('VideoMessage')
verbose_name_plural = _('VideoMessages')
Translation
from modeltranslation.translator import translator, TranslationOptions
from models import VideoMessage
class VideoMessageTranslationOptions(TranslationOptions):
fields = ('text', 'link', 'meta',)
translator.register(VideoMessage, VideoMessageTranslationOptions)
Views
from django.shortcuts import render
from django.views.generic import View
from models import VideoMessage
class Index(View):
def get(self, request):
params={}
messages=VideoMessage.objects.exclude(is_active=False).exclude(link='').order_by('-position')
params['videos']={}
params['videos']['message']=messages
return render(request, 'index.html', params)
gprof2dot tree. 100% = ~2000ms
I parsed the image at each rendering. It was bad idea.
Try to find out what takes the longest time.
You can use something like Opbeat where you can get a free account. You can see a breakdown on what takes time on different requests so you can focus on whatever is slow.
Also, is this happening only during development or also in production? Having DEBUG=True in a production setup is not only a bad idea but also it can have a big impact on performance.

Categories