Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
module not detected django production
I'm trying to deploy my Django app onto a DigitalOcean VPS. I set everything up and was about to run python manage.py collectstatic when I hit this error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/demo/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/demo/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/home/demo/.local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/demo/.local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/demo/.local/lib/python2.7/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named embed_video The problem is that I already installed embed_video (Django's app name for this application) using pip install django-embed-video. My problem is that the app isn't being detected. If it helps, I'm implementing PostgreSQL as the production database, and SQLite as the development database, and I'm also using nginx and gunicorn as part of the process. -
Django too many values to unpack
I have an error : too many values to unpack It seems to be a problem with my list or may be it's an issue about the way I fill it. views.py favs = FavoriteGames.objects.filter(user_id=request.user.id).values_list('game_id', flat=True) mylist = [] for fav in favs: game = Games.objects.get(id=fav) mylist.append((game.id, game.guid, game.title, game.logo, "checked"), ) nogame = Games.objects.filter(~Q(id__in=favs)).values_list('id', 'guid', 'title', 'logo') form = GamesEditorForm(games=mylist) forms.py class GamesEditorForm(forms.Form): def __init__(self, *args, **kwargs): self.games = kwargs.pop('games') super(GamesEditorForm, self).__init__(*args, **kwargs) self.fields['favorite_games'].choices = self.games favorite_games = forms.MultipleChoiceField( required=True, initial=True, widget=forms.CheckboxSelectMultiple(), ) template {% for jeux in form.favorite_games %} <p>{{ jeux }}</p> {% endfor %} in forms.py, mylist return : [(1, 'paragon', 'Paragon', 'paragon.png', 'checked')] -
django Geonode python manage.py updatelayers fails
I've setup geonode and geoserver successfully and access the site using these installation instructions: http://docs.geonode.org/en/master/tutorials/install_and_admin/geonode_install/index.html However when I attempt to import the layers ive creater geoserver using the command python manage.py updatelayers I get the below error. I do not see anything obvious that would cause this, what are some possible solutions. File "manage.py", line 28, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 242, in run_from_argv self.execute(*args, **options.__dict__) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 285, in execute output = self.handle(*args, **options) File "/vol1/geonode/geonode/geonode/geoserver/management/commands/updatelayers.py", line 108, in handle remove_deleted=remove_deleted) File "/vol1/geonode/geonode/geonode/geoserver/helpers.py", line 458, in gs_slurp "bbox_y1": Decimal(resource.latlon_bbox[3]) File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 154, in get_or_create return self.get_queryset().get_or_create(**kwargs) File "/usr/local/lib/python2.7/dist-packages/modeltranslation/manager.py", line 341, in get_or_create return super(MultilingualQuerySet, self).get_or_create(**kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 383, in get_or_create obj.save(force_insert=True, using=self.db) File "/usr/local/lib/python2.7/dist-packages/polymorphic/polymorphic_model.py", line 90, in save return super(PolymorphicModel, self).save(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 545, in save force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 582, in save_base update_fields=update_fields, raw=raw, using=using) File "/usr/local/lib/python2.7/dist-packages/django/dispatch/dispatcher.py", line 185, in send response = receiver(signal=self, sender=sender, **named) File "/vol1/geonode/geonode/geonode/geoserver/signals.py", line 470, in geoserver_post_save set_styles(instance, gs_catalog) File "/vol1/geonode/geonode/geonode/geoserver/helpers.py", line 776, in set_styles default_style = gs_layer.default_style File "/usr/local/lib/python2.7/dist-packages/geoserver/layer.py", line 103, in _get_default_style return self._resolve_style(element) if element is not None else … -
ImportError: can not import name auth
I'm giving deploy in pythonanywhere and I came across this error that follows: ImportError: can not import name auth My User model: Import uuid From django.db import models From django.contrib.auth.models import User Class UserProfile (models.Model): Def username_is_available (self, request, username): Try: User = User.objects.get (username = username) If user == request.user: Return True Return False Except Exception as e: Return True Def email_is_available (self, request, email): Try: User = User.objects.get (email = email.strip ()) If user == request.user: Return True Return False Except Exception as e: Return True -
Django object lookups in templates
I am going through the Django project tutorial, and in this section it says: The template system uses dot-lookup syntax to access variable attributes. In the example of {{ question.question_text }}, first Django does a dictionary lookup on the object question. Failing that, it tries an attribute lookup – which works, in this case. If attribute lookup had failed, it would’ve tried a list-index lookup. Does this mean that the Django question is a dictionary object, and in the first instance, looks for question_text as the key, and if found, returns the value? Beyond this, I can't visualise what the two fall-back options are doing. -
Reading InMemoryUploadedFile twice
i' ve an InMemoryUploadedFile object and when i make a .read() on it, it' ll loose his content. Is it somehow possible to read this content twice from the same object? I tried to .copy() it, but of course that should not work. If it' s not possible, can i somehow put the content back to the same object? Reason for this: for a django form a prevalidation() method would like to read the content, but if it does, later i can' t save it. Performance here does not count. -
Unique id form field django
I have a form, which I call inside a nested for loop in my template. Here's forms.py class SubCategoryItemForm(forms.Form): paragraf = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control'}), required=True, label="Paragraf") name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control'}), required=True) description = forms.CharField(widget=CKEditorWidget(attrs={'class' : 'form-control'}), required=True) views.py def category_view(request, cat_id): category = Category.objects.get(id=cat_id) context = {"category": category, "sub_category_item_form": SubCategoryItemForm()} return render(request, 'registered/category.html', context=context) And in template(without the html): {{ category.name }} {{ category.description }} {% for subcat in category.foreign_category.all %} {{ subcat.name }} {{ subcat.description }} <form role="form" id="{{ subcat.id }}" action="{% url 'auth_sub_category_item_add' %}" method="POST"> {% csrf_token %} {{ sub_category_item_form }} <button type="submit">Save</button> </form> {% endfor %} The issue: I don't know how I can set the forms field id to be unique. As there might be up to 15 of this form in the sub categories. In specific the description form field needs an unique id. The forms posts and saves, but getting an annoying js error from the CKEditorWidget: Uncaught The editor instance "id_description" is already attached to the provided element. I can suppress this by editing the js, but it would be nice to know if there's any way to set field id dynamically. -
Django rest framework global pagination parameters not working for ModelViewSet
From the docs: Pagination is only performed automatically if you're using the generic views or viewsets. Cool, I'm using a ModelViewSet which inherits from ViewSet, so I tell myself that all I have to do is add this to my settings.py: 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 12, # for 12-col grid css frameworks This does not work. If I send a GET request for 27 items it returns all of them (in both the browsable API and json). Am I right in thinking I should only be returned 12? Sub-question: PAGE_SIZE is the number of top-level objects returned per page, right? I saw a few examples with PAGINATE_BY but it doesn't feature in the source so I presume it's deprecated? I'm using DRF 3.6.3, django 1.11.2. -
How to paginate django queryset by field effectively?
I have a model with a Boolean field, and I want to paginate the query set of this model by the Boolean field with the rule: Page size is 10 Each page contain 2 items whose Boolean field is True and 8 items whose Boolean field is False For example: With the Food model, I want every page has 2 fat food and 8 non-fat food class Food(models.Model): # whether fat food is_fat_food = models.BooleanField(default=False) # other field Now, I implement the pagination with the following algorithm in get_queryset. BTW, I use ListModelMixin in my interface to implement pagination. def get_queryset(self): fat_food_qs = Food.objects.filter(is_fat_food=True) non_fat_food_qs = Food.objects.filter(is_fat_food=False) final_qs = [] fat_page_size = 2 no_fat_page_size = 8 i = 0 j = 0 while i < len(fat_food_qs) and j < len(non_fat_food_qs): if i + fat_page_size > len(fat_food_qs): break if j + no_fat_page_size > len(non_fat_food_qs): break final_qs += fat_food_qs[i:i+fat_page_size] final_qs += non_fat_food_qs[j:j+non_fat_food_qs] i += fat_page_size j += non_fat_food_qs # remaining food no need to obey the rule, just append if i < len(fat_food_qs): final_qs += fat_food_qs[i:] if j < len(non_fat_food_qs): final_qs += non_fat_food_qs[j:] return final_qs By this algorithm, I get the right and expected result, but I think it is not efficient. … -
Django CeateView and change recodrs in other model
I have 2 models and during add record to database i want change one field in other model class Room2Create(CreateView): model = Room2 form_class = Room2Form template_name = 'room2_form.html' def form_valid(self, form): self.object = form.save(commit=False) q = Room1.objects.filter(id__startswith=self.object.room_status) q.room_status = self.object.room_status for elem in q: elem.save() self.object.save() return HttpResponseRedirect(self.get_success_url()) Can you help me ? What is wrong ? -
Overriding the logout link in Django admin
Is there a way to override the log out link on a Django admin page? I am trying to delete a cookie when a user logs out. -
How to create dynamic data for each users in django
Hi i have created one django app.it basically collect class assignments .pdf using froms.py also i have done login and logout neatly.now the question is i need to display a dynamic content for logged in user which means his class teachers,friends and user completed assignments.i can't figure out how to connect this things. There are many classes,teachers and friends in DB.but i need to show his/her circle only not all DB content. how can i show logged user content without showing all.sorry for my english!! -
Django OAuth Toolkit
I am trying to use oauth2 authentication using django oauth toolkit. I got the following exception : Could not import 'oauth2_provider.ext.rest_framework.OAuth2Authentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES' My settings.py file looks like : INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'adaccounts', 'corsheaders', 'clients', 'Gen42Backend', 'djcelery', 'oauth2_provider' ) REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.ext.rest_framework.OAuth2Authentication', ) } -
Email not getting send in django
I am not able to send emails through the django project. This is my settings.py EMAIL_USE_TLS = True EMAIL_HOST = 'smpt.gmail.com' EMAIL_HOST_USER = 'my_email@gmail.com' EMAIL_HOST_PASSWORD = 'my_password' EMAIL_PORT = 587 this is my views.py: def dif(request): for j in range(len(column_prop)): if column_prop[j] == column2_prop[j]: print "same" send_mail( 'regarding database structure', 'Structure wrong.', settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], fail_silently=True ) else: print "\n" print "not same" return true I am not able to spot the mistake in the code.Can anyone please help me to correct the problem. -
How to look up parameter name of django 'custom template tag' argument
I created custom template tag, which has lots of parameters: @register.inclusion_tag('components/mail_button.html', takes_context=True) def mail_button(context, button_content, button_name, button_link, button_width=265, button_height=47, background_color=COLOR_WHITE, margin_bottom=MARGIN_M): return { 'button_content': button_content, 'button_name': button_name, 'button_link': button_link, 'button_width': button_width, 'button_height': button_height, 'background_color': background_color, 'margin_bottom': margin_bottom, 'site': context['site'], 'LANGUAGE_CODE': context['LANGUAGE_CODE'] } Then in my template, I put my custom template tag with proper arguments. {% mail_image 'mail-image-content-animated.jpg' 432 524 'Augmented Reality App' '#ECF0F1' %} The question is, when using PyCharm, how can I possibly look up the parameter name, without navigating to my templatetags/mailing_tags.py ( (cmnd/ctrl + click)? If it is at all possible, I'd be grateful for an answer. Take care! -
JSON field postgress like
Is it possible to filter data in json field using not equal but like operator? Models: from django.contrib.postgres.fields import JSONField from django.db import models class Dog(models.Model): name = models.CharField(max_length=200) data = JSONField() where data row: {"breed": "labrador0", "owner": {"name": "Bob0", "other_pets": [{"name": "Fishy"}]}} Then i use Dog.objects.filter(data__breed='labrador0') i receive data, but if i want to receive all row where data.breed like 'labrador%' - i dont know how to do it. I try Dog.objects.filter(data__breed__contains='labrador') - no results. -
Attach img file in PDF Django Weasyprint
Hello friends I want to ask you for help. I need help with attach img file in pdf we use WeasyPrint for generation pdf from html. I don't know where to add the code: base_url=request.build_absolute_uri() to tasks.py. Where in the file tasks.py ? Because instead images i have empty place now. I try my best but i don't succeed. So please help. html file <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div> <img src="{% static 'images/static.jpg' %}" alt=""> </div> </body> </html> tasks.py from celery import task from django.shortcuts import get_object_or_404 from oferty.models import Order from django.template.loader import render_to_string from django.core.mail import EmailMultiAlternatives from django.conf import settings import weasyprint from weasyprint import default_url_fetcher, HTML from io import BytesIO @task def order_created(order_id): """ Task to send an e-mail notification when an order is successfully created. """ order = Oferta.objects.get(id=order_id) subject = 'xxx nr {}'.format(order.id) html_content = '<p><strong>Hallow, {}!</p></strong><br><p> email = EmailMultiAlternatives(subject, html_content,'admin@xxx.com', [order.email]) # generation PDF. html = render_to_string('order/order/pdf.html', {'order': order}) out = BytesIO() stylesheets = [weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')] weasyprint.HTML(string=html).write_pdf(out, stylesheets=stylesheets) # attach PDF. email.attach('order_{}.pdf'.format(order.id), out.getvalue(), 'application/pdf') email.attach_alternative(html_content, "text/html") email.send() I would appreciate your help -
Django password reset basic example
I'm trying to use the Django-password-reset library but the documentation isn't clear enough for me. Could anyone provide a basic example on how to carry out? -
Django Rest Framework Filter ModelViewSet Field Against Multipe Values
I have an issue with my DRF API. I would like to filter a list of issues against a list of ids. Like so: 127.0.0.1:8000/api/issues/?id=2,12 This returns the entire list of issues I've also tried http://127.0.0.1:8000/api/issues/?id=2&id=12 This returns a list containing only the object with the last supplied id (the object with id 12 I've also tried the following which all return the entire set http://127.0.0.1:8000/api/issues/?id__in=2&id__in=12 http://127.0.0.1:8000/api/issues/?id__in=2,12 Here's my serializer from rest_framework import serializers ... class IssueSerializer(serializers.HyperlinkedModelSerializer): '''Serializer for issues''' class Meta: '''Model filed definitions''' model = Issue fields = ('id', 'inspection_sheet', 'picture', 'description', 'resolution') And the view from rest_framework import filters from rest_framework import viewset ... class IssueSet(viewsets.ModelViewSet): '''Views for issues''' queryset = Issue.objects.all() serializer_class = IssueSerializer filter_backends = (filters.DjangoFilterBackend,) filter_fields = ('id',) -
Trying to implement django pagedown in the admin page
I have been trying to implement django pagedown feature on my django-admin page for blog posts I followed the documentation from Django Pagedown This is what I did models.py class Entry(models.Model): title = models.CharField(max_length=200) post_type = models.CharField(max_length=50,choices= ( ('Mobiles', 'Mobiles'), ('Laptops', 'Laptops'), ('Laptop_Accesories', 'Laptop_Accesories'), ('Tablets', 'Tablets'), ('Cameras', 'Cameras'), ('Others', 'Others'), ), default='Others') author = models.CharField(max_length=30, blank=False) description = models.TextField(max_length=150, blank=False, default="") body = models.TextField() slug = models.SlugField(max_length = 200, unique = True) publish = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now_add=True) forms.py from django import forms from pagedown.widgets import AdminPagedownWidget from blog import models from blog.models import Entry class EntryForm(forms.ModelForm): description = forms.TextField(widget=AdminPagedownWidget()) class Meta: model = Entry fields = "__all__" admin.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from . import models from django.contrib import admin class EntryAdmin(admin.ModelAdmin): list_display=("title","created") prepopulated_fields = {"slug" : ("title",)} class EAdmin(admin.ModelAdmin): form = EntryForm # Register your models here. admin.site.register(models.Entry, EntryAdmin) I get the error * description = forms.TextField(widget=AdminPagedownWidget()) AttributeError: 'module' object has no attribute 'TextField' * -
How to structure workers in micro service architecture?
I am currently working on a project which has micro service architecture. I have different apps running which will need workers for long processes. My question where do I keep workers in this architecture? Should I keep worker in apps itself where they are used or make a different app all together for the workers. One idea which I have now is to keep workers with apps where they are used, Where they can be invoked through management command. Then I will have a separate utility machine which will have all the apps to run the workers and that machine will be detached from load balancer. I want to know different approaches which can be taken to solve this problem with proper justification and also comment on my suggestion if it is good or not. -
Django channels AWS deployment, supervisor not running daphne and worker. Only httpd running
[program:Daphne] command=/opt/python/run/venv/bin/daphne -b 0.0.0.0 -p 5000 /opt/python/current/app/malang/malang.asgi:channel_layer autostart=true autorestart=true redirect_stderr=true user=root stdout_logfile=/tmp/daphne.out.log [program:Worker] environment=PATH="/opt/python/run/venv/bin" command= /opt/python/run/venv/bin/python manage.py runworker directory=/opt/python/current/app process_name=%(program_name)s_%(process_num)02d numprocs=4 autostart=true autorestart=true redirect_stderr=true stdout_logfile=/tmp/workers.out.log when I run 04_status_supervisord: command: "supervisorctl -c /opt/python/etc/supervisord.conf status" It only shows httpd running..but Daphne and workers are not running. Please help how to run them. I am following this article btw - https://blog.mangoforbreakfast.com/2017/02/13/django-channels-on-aws-elastic-beanstalk-using-an-alb/ -
Avoiding multiple queries t display model data on Django admin
I am using Django amdin for one of my data models. I want to display customized values on admin UI for each model. On db, the result of a single query runs as multiple queries on django admin, one for each row I am trying to avoid that. Here are my models: class words(models.Model): word_id=models.AutoField(primary_key=True) word=models.CharField(max_length=200,unique=True) def __unicode__(self): return '%s - %s' % (self.word,self.word_id) class meanings(models.Model): id=models.AutoField(primary_key=True) word_id=models.ForeignKey(words,on_delete=models.CASCADE,db_column='word_id') meaning=models.CharField(max_length=200) def __unicode__(self): return '%s %s %d ' % ( self.spelling_id.spelling,self.meaning,self.id) For the second model, while loading the page, for each row I saw there are 2 queries running one on words table and other on meanings table. (from debug toolbar) I tried avoiding that by using the below option. models.py: class meanings(models.Model): meaning_id=models.AutoField(primary_key=True) word_id=models.ForeignKey(words,on_delete=models.CASCADE,db_column='word_id') meaning=models.CharField(max_length=200) admin.py: def modified_output(self): cursor = connection.cursor() cursor.execute("select word,meaning,id from meanings a,words b where a.word_id=b.word_id and meaning_id= "+str(self.id)) row = dictfetchall(cursor) a=unicode(row[0]['word']) b=unicode(row[0]['meaning']) d=(row[0]['id']) return '%s %s %d ' % ( a,b,d) meanings.add_to_class("__str__", modified_output) Now for each row there is only 1 query running. But as the dependency on models have more than 2 tables in join of a query, it will still consume time. So my question is instead of running 1 query for each row, … -
Django model where only one row can have active = True
I am creating theme settings for a project I'm working on. I want the user to be able to create multiple themes (rows in the database) but only have one theme active at a time. class SingleActiveModel(models.Model): class Meta: abstract = True def save(self, *args, **kwargs): # Save active = False to all other rows or alternative super(SingleActiveModel, self).save(*args, **kwargs) class Theme(SingleActiveModel): some_setting = models.SomeField() active = models.BooleanField(default=False) -
How show related object in Django admin from the model with a foreign key point of view?
I got two Django models linked by a Foreign key: class Author(models.Model): ... class Book(models.Model): author = models.ForeignKey(Author) Please consider admin example below (I want to do the opposite): from django.contrib import admin from my_app.models import Author, Book class BookInline(admin.TabularInline): model = Book class AuthorAdmin(admin.ModelAdmin): inlines = [ BookInline, ] admin.site.register(Author, AuthorAdmin) With this example, we can see in the admin all authors, and for each author, their books. Now, I would like to to it the other way around. Have en entry per Book in the administration and display the Author informations (it can be readonly) on the Book details. I tried with the solution below, but obviously it didn't work: from django.contrib import admin from my_app.models import Author, Book class AuthorInline(admin.TabularInline): model = Author class BookAdmin(admin.ModelAdmin): inlines = [ AuthorInline, ] admin.site.register(Book, BookAdmin) Django raised an error : <class 'my_app.admin.AuthorInline'>: (admin.E202) 'my_app.Author' has no ForeignKey to 'my_app.Book'. Do you know how to do that ? More context : Django 1.11 I want to display Book and Author as full readonly, so the foreign key of the Book will not be changed (at least not from the admin)