Django render is very slow - python

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.

Related

The model is not displayed in the django admin panel

I don't have the advertisement module displayed in the django admin panel. Here is the model code
from django.db import models
class Advertisement(models.Model):
title = models.CharField(max_length=1000, db_index=True)
description = models.CharField(max_length=1000, default='', verbose_name='description')
creates_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
price = models.FloatField(default=0, verbose_name="price")
views_count = models.IntegerField(default=1, verbose_name="views count")
status = models.ForeignKey('AdvertisementStatus', default=None, null=True, on_delete=models.CASCADE,
related_name='advertisements')
def __str__(self):
return self.title
class Meta:
db_table = 'advertisements'
ordering = ['title']
class AdvertisementStatus(models.Model):
name = models.CharField(max_length=100)
admin.py /
from django.contrib import admin
from .models import Advertisement
admin.site.register(Advertisement)
I was just taking a free course from YouTube. This was not the case in my other projects. Here I registered the application got the name in INSTALLED_APPS. Then I performed the creation of migrations and the migrations themselves. Then I tried to use the solution to the problem here , nothing helped. I didn't find a solution in Google search either.
127.0.0.1:8000/admin/
console
admins.py
The name of the file is admin.py not admins.py. Yes, that is a bit confusing since most module names in Django are plural. The rationale is probably that you define a (single) admin for the models defined.
Alternatively, you can probably force Django to import this with the AppConfig:
# app_name/apps.py
from django.apps import AppConfig
class AppConfig(AppConfig):
def ready(self):
# if admin definitions are not defined in admin.py
import app_name.admins # noqa

Django not showing a model in admin page

I have created a new model for my app Consumptions but it doesn't show up.
I know that I have to put it on the admin.py page but still not working.
I don't know what could be happening
This is my models.py page:
from logs.mixins import LogsMixin
# Other models
class MF(LogsMixin, models.Model):
"""Definición del modelo de Proveedor."""
name = models.CharField("Nombre", null=False, default="MF", max_length=50)
class Meta:
verbose_name = 'Módulo formativo'
verbose_name_plural = 'Módulos formativos'
def __str__(self):
return self.name
# Other models
And this is my admin.py page:
from django.contrib import admin
from .models import Provider, Consumption, Message, Course, Call, Platform, MF
admin.site.register(Provider)
admin.site.register(Consumption)
admin.site.register(Message)
admin.site.register(Course)
admin.site.register(Call)
admin.site.register(Platform)
admin.site.register(MF)
As you can see is not my only model, I do the same with all of them but the MF one is not showing up on the admin page.
What am I doing wrong?
Try following approach:
class ProviderAdmin(admin.ModelAdmin):
model = Provider
admin.site.register(Provider, ProviderAdmin)
In ProviderAdmin class you may specify filters, search fields or empty value handling:
search_fields = ('',)
list_filter = ('',)
empty_value_display = 'empty'

django: cant import models from global app

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))

Can't import serializer from other serializer in django rest-framework?

Problem
I have 2 models, leads and notes. I want a lead to be able to have 1 or more notes. I have used a generic foreign key because I want to plan for the future and a note could be assigned to say a person or a meeting for example.
Following the instructions for django rest framework and Rest Framework Generic Relations I am trying to import one serializer from the other to make a reverse relation possible.
Error
I can't import the serializers in both files(call one serializer from the other) because I get:
File "/Users/james/Documents/UtilityCRM-Server/crm/leads/urls.py", line 2, in <module>
from leads import views
File "/Users/james/Documents/UtilityCRM-Server/crm/leads/views.py", line 11, in <module>
from leads.serializers import LeadSerializer
File "/Users/james/Documents/UtilityCRM-Server/crm/leads/serializers.py", line 4, in <module>
from notes.serializers import NoteSerializer
File "/Users/james/Documents/UtilityCRM-Server/crm/notes/serializers.py", line 6, in <module>
from leads.serializers import LeadSerializer
ImportError: cannot import name LeadSerializer
Its weird because if I open the django shell and run the following it lets me import them all:
from leads.serializers import LeadSerializer
from notes.serializers import NotesSerializer
from callbacks.serializers import CallbackSerializer
Any help would be greatly appreciated!
Code
This is my installed app section of my settings file:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 3rd Party Apps
'rest_framework',
'generic_relations',
# My Apps
'leads.apps.LeadsConfig',
'callbacks.apps.CallbacksConfig',
'notes.apps.NotesConfig',
]
notes/models.py
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class Note(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=100)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
# Relations
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
note_object = GenericForeignKey('content_type', 'object_id')
def __str__(self):
return self.title
leads/models.py
from __future__ import unicode_literals
from django.db import models
from django.contrib.contenttypes.fields import GenericRelation
from django.utils import timezone
from notes.models import Note
from callbacks.models import Callback
GAS = 'G'
ELECTRICITY = 'E'
LEAD_TYPE_CHOICES = (
(GAS, 'Gas'),
(ELECTRICITY, 'Electricity'),
)
# Create your models here.
class Lead(models.Model):
author = models.ForeignKey('auth.User')
type = models.CharField(
max_length=1,
choices=LEAD_TYPE_CHOICES,
default=GAS,
)
business_registration_number = models.IntegerField(max_length=20)
business_name = models.CharField(max_length=50)
mpan = models.IntegerField(max_length=21)
supplier = models.CharField(max_length=45)
contract_length = models.IntegerField(max_length=2)
contract_start_date = models.DateField()
contract_end_date = models.DateField()
address_line_1 = models.CharField(max_length=45)
address_line_2 = models.CharField(max_length=45)
address_line_3 = models.CharField(max_length=45)
address_city = models.CharField(max_length=45)
address_county = models.CharField(max_length=45)
address_postcode = models.CharField(max_length=10)
contact_title = models.CharField(max_length=45)
contact_first_name = models.CharField(max_length=45)
contact_middle_name = models.CharField(max_length=45)
contact_last_name = models.CharField(max_length=45)
contact_telephone = models.IntegerField(max_length=11)
contact_email = models.EmailField(max_length=60)
created_date = models.DateTimeField(default=timezone.now)
# Relations
assigned_to = models.ForeignKey('auth.User', related_name='+')
#from_batch = models.ForeignKey('data_batch.DataBatch', related_name='+')
#callbacks = GenericRelation(Callback)
notes = GenericRelation(Note)
class Meta:
ordering = ('contract_end_date', 'business_name',)
def __str__(self):
return self.business_name
I have 2 serializers:
leads/serializers.py
from rest_framework import serializers
from leads.models import Lead, LEAD_TYPE_CHOICES
from notes.serializers import NoteSerializer
class LeadSerializer(serializers.ModelSerializer):
notes = NoteSerializer(many=True, read_only=True)
class Meta:
model = Lead
fields = (
'id',
'business_name',
'business_registration_number',
'supplier',
'contract_length',
'contract_start_date',
'notes'
)
notes/serializers.py
from generic_relations.relations import GenericRelatedField
from rest_framework import serializers
from notes.models import Note
from leads.models import Lead
from leads.serializers import LeadSerializer
from callbacks.models import Callback
from callbacks.serializers import CallbackSerializer
class NoteSerializer(serializers.ModelSerializer):
"""
A `Note` serializer with a `GenericRelatedField` mapping all possible
models to their respective serializers.
"""
note_object = GenericRelatedField({
Lead: LeadSerializer(),
Callback: CallbackSerializer()
})
class Meta:
model = Note
fields = (
'id',
'author',
'title',
'text',
'created_date',
'note_object',
)
As I have mentioned previously in a comment, I believe this happens due to circular (cyclic) imports in Python.
This happens particularly when you are declaring related fields in models, and some models have not been instanced yet.
In this case, when you execute your program, it tries to import LeadSerializer, that requires importing NoteSerializer, that requires importing LeadSerializer, that requires importing NoteSerializer... see where this is going?
Your stacktrace says it all:
from leads.serializers import LeadSerializer
from notes.serializers import NoteSerializer
from leads.serializers import LeadSerializer
Generating ImportError: cannot import name LeadSerializer
What I have done to solve this was declaring all the serializers in a single file. Therefore, you have two options:
Move LeadSerializer to notes/serializers.py
Move NoteSerializer to leads/serializers.py
It is not the most elegant way to solve this, but it has done its trick.
The section below provides no further explanation on how to solve this problem, but an observation regarding this issue.
Perhaps Django & DRF could futurely provide methods to avoid this, such as declaring the serializers as
note_object = GenericRelatedField({
Lead: 'leads.serializers'.LeadSerializer,
Callback: CallbackSerializer()
})
or
notes = 'notes.serializers'.NoteSerializer(many=True, read_only=True)
Faced with this and made this thing:
notes = serializers.SerializerMethodField()
def get_notes(self, obj):
from leads.serializers import LeadSerializer
return LeadSerializer(<your_queryset>, many=True/False, read_only=True/False).data
There is an idea to tackle this before I have also got this same error here I will explain to you how I resolve this.
Put your apps inside the project directory
project
-project
-appname1
-models.py
-serilizer.py
-appname2
-models.py
-serilizer.py
-settings.py
in settings.py
INSTALLED_APPS = ['project.appname1', 'project.appname2']
then try to import appname1 serializers into appname2
like this
from project.appname1.serializers import( ArtistSerializer, ArtisTokenSerilizer, ProfessionSerilizer, FollowersSerializer,
FollowingSerializer, ChatMessageSerializer, SendMessageSerializer, ConversationMessageSerializer,
ProjectTypeSerializer)

How can I get a textarea from model+ModelForm?

models.py=>
from django.db import models
from django.forms import ModelForm
from datetime import date
import datetime
from django import forms
from django.forms import Textarea
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
created = models.DateField(auto_now_add=True)
modified = models.DateField(auto_now_add=True)
def __unicode__(self):
return self.title
class PostModelForm(ModelForm):
class Meta:
model = Post
But I get a text input not textarea for models.TextField(). Is that a reason of css?
I think this section in the documentation should be useful to solve the problem.
from django.forms import ModelForm, Textarea
class PostModelForm(ModelForm):
class Meta:
model = Post
widgets = {
'content': Textarea(attrs={'cols': 80, 'rows': 20}),
}
Alternative to jcollardo's solution (same result, different syntax):
from django import forms
class PostModelForm(forms.ModelForm):
content = forms.CharField(widget=forms.Textarea)
class Meta:
model = Post
You are using models not forms, which means you can't use textarea properly. Instead you can try TextField:
field_name = models.TextField( **options)

Categories