Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
manage.py doesn't log to stdout/stderr in Docker on Raspberry Pi
On a Raspberry Pi 2, I used the image resin/rpi-raspbian:stretch for running a Django application. In my Dockerfile, I Install the python3 package and start the application using ENTRYPOINT python3 manage.py runserver 0:8000. This works, BUT when my code throws error, I got NO output using docker log command. Example I have a ImportError. When I run the command manually using docker exec, I got the exception as expected: pi@pi2:/etc/docker/container/pms $ sudo docker exec -it pms_app_1 python3 manage.py runserver 0:8000 Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x75de3228> [...] ImportError: No module named 'ws4redisfrontend' But when I run the container using docker-compose and then open the logs, they're empty: pi@pi2:/myapp $ sudo docker logs myapp_1 pi@pi2:/myapp $ This behaviour is only present for the manage.py call. For example, when I extend the entrypoint like this: ENTRYPOINT python3 -c "print('printed by python inline script')" && python3 manage.py runserver 0:8000 I see printed by python inline script in the container-logs. As a newbie in Python/Django, I can't understand why this happens. But as my print example works, it seems a Django issue, and no general problem of Python. What am I missing? Debug mode is activated in settings.py. -
django mezzanine search shows model name after type
When I use the default search in mezzanine and added in my own model, the url bar displays my model name. How do I remove that? website.com?/search/?q=new+york&type=app.Places models.py class Places(models.Model): ... objects = SearchableManager() search_fields = ("city","country", "name") settings.py SEARCH_MODEL_CHOICES = [ 'app.Places', 'app.User'] -
'ImportError: No module named webappdjango.contrib' django1.10
In a Django tutorial, I am stuck at the integration of 'view.py' file to the localhost server: python manage.py runserver When running this, I get the error: ImportError: No module named webappdjango.contrib I am using Python 2.7 and Django 1.10.1 In the shell i am getting this error- [ *Unhandled exception in thread started by Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 120, in create mod = import_module(mod_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named webappdjango.contrib* ] -
Which DJango Authentication Backend
My application requirement is to use our LDAP directory to authenticate a User based on their network login. I setup the LDAP correctly using ldap3 in my system.py. I'm able to bind to a user and identify credentials in python, not using Django. Which authentication backend would I set Django up to use to make my login function as I want? -
Django's EmailMultiAlternative's send not being captured by tests
When executing tests with Django's test framework, emails sent via the EmailMultiAlternative are not being captured and are being sent to the EMAIL_OVERRIDE email address. Are there any reasons why this might happen? -
How to auto create Grous in Django 1.11.2
I try follow this tutorial "Programmatically creating a group : Can't access permissions from migration", and my code is: # -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-10-16 13:48 from __future__ import unicode_literals from django.db import migrations, models from django.contrib.auth.models import Group, Permission from django.contrib.auth.management import create_permissions def add_group_permissions(apps, schema_editor): for app_config in apps.get_app_configs(): create_permissions(app_config, apps=apps, verbosity=0) # Criando Administrador group, created = Group.objects.get_or_create(name='Administrador') if created: add_thing = Permission.objects.get( codename=['can_add_permision', 'can_change_permission', 'can_add_user', 'can_change_user', 'can_add_video', 'can_change_video', 'can_delete_video', 'can_add_documents', 'can_change_documents', 'can_delete_documents', 'can_add_news', 'can_change_news', 'can_delete_news', 'can_add_basics', 'can_change_basics', 'can_add_board', 'can_change_board', 'can_delete_board', 'can_add_history', 'can_change_history', 'can_delete_history', 'can_add_shortcuts', 'can_change_shortcuts', 'can_delete_shortcuts',] ) group.permissions.add(add_thing) group.save() logger.info('Grupo Administrador Criado') class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.RunPython(add_group_permissions), ] And my error is: self.model._meta.object_name django.contrib.auth.models.DoesNotExist: Permission matching query does not exist. Is it probably that problem is releated with dependencies? Or how I do? -
Finding co-founders for an NLP tech startup
I am struggling to find a way of hooking up with somebody who would be part of a co-founder team for an NLP-based tech startup. I am in the process of forming an NLP-based tech startup and looking for at a co-founder with better (and faster!) developer skills in python, NLTK, Gensim and possibly also Django (or similar). This is not a job. Roles (including mine!) would not be salaried until I can get venture capital seed funding in place. But, I can confidently say that the payoff for a successful venture would be very large (since you would own part of the company). Where can I hook up with suitably skilled and interested individuals? Thanks for any help... -
Using ValidationForm to signup a new user
I'm developing a Django project and I have a SignUp form. I'm also have a Validation form. Project manager want that, when user submit Validation form with information like: username, email, password, location, birth_date... will also signup the user into the database. Is it possible? How can I pass request.POST information to SignUp form? -
Change image through a dictionary on a django view
I am developing an application in django with support in several countries. On the site should appear the country flag according to the subdomain in which it is, but I can not find a way to send the necessary flag image through a django view. This is a example of my views.py def index(request): subdomain = request.META['HTTP_HOST'].split('.')[0] if subdomain == 'www': dic.update({"countryflag": ''}) elif subdomain == 'mx': dic.update({"countryflag": '<img src="{% static "images/mxflag.png" %}" alt="img">'}) elif subdomain == 'nz': dic.update({"countryflag": '<img src="{% static "images/nzflag.png" %}" alt="img">'}) return render(request, 'mysite/index.html', dic) I want to recive the variable "countryflag" in my basetemplate.html <div id="cp_side-menu-btn" class="cp_side-menu"> {{ countryflag }} </div> This doesn't works. I want to pass the entire image to the countryflag key. Is there a way to do this or I have to make an 'if' in the basetemplate.html? -
Many-to-many relations request to DataBase
I have next models: class Color(models.Model): color = models.CharField(max_length=50, verbose_name='Color') code = models.CharField(max_length=50, verbose_name='Code of color') class ColorSet(models.Model): name = models.CharField(max_length=50, verbose_name='Name of set') color_set = models.ManyToManyField(Color) How can I get filtered colors by color_set_ID in views? -
JWT Authentication Error "Invalid Signature" in Django Rest Framework
I'm new to Python and Django REST Framework and I'm trying to configure authentication using JWT (http://getblimp.github.io/django-rest-framework-jwt/). I'm able to create a token for a user upon registration however I'm getting an "Invalid Signature" error when I try to authenticate through my api. I have confirmed the error at https://jwt.io/. This seems to mean my token is being created improperly. Any Ideas? This is my configuration: from django.db import models class User(models.Model): first_name = models.CharField(max_length=45) last_name = models.CharField(max_length=45) username = models.CharField(max_length=45, unique=True) phone = models.CharField(max_length=20) password = models.CharField(max_length=100, blank=False, default='') from rest_framework import serializers from . models import User from django.contrib.auth.hashers import make_password class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first_name', 'last_name', 'username', 'phone', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): # the create method creates and saves an object in a single statement user = User.objects.create( first_name = validated_data['first_name'], last_name = validated_data['last_name'], username = validated_data['username'], phone = validated_data['phone'], password = make_password(validated_data['password']), ) return user from joyrides_api.models import User from joyrides_api.serializers import UserSerializer from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from rest_framework_jwt.utils import jwt_payload_handler from rest_framework import permissions from rest_framework_jwt.settings import api_settings from rest_framework.permissions import AllowAny from rest_framework_jwt.authentication import JSONWebTokenAuthentication … -
Can these regex urls get indexed by google without internal links?
My urls have the regex pattern r'/index/(?P<movie_id>\d)' i.e index/(any movie_id) and then I grab the movie info with an api by jQuery. There are millions of webpages like these. One for each movie. And all the backend code works only with the specific movie_id parameter. Would such pages be indexed by google if they have no internal links connecting within the website? The only links are from an ajax search bar which works only when someone types, which cannot be considered an internal link. -
Django additional local files
In my settings.py file, I've added a locale file under the root folder of my website to allow to override some translation depending of the website (currency based on ID, etc...) #Set the path where override the local files LOCALE_PATHS = [ os.path.join(BASE_DIR, "locale"), ] The problem it's that when this settings is in the settings.py, and I do the makemessages under my apps, it does not take care of the existing po files which are set for multiple languages under my apps folder, for exemple ./myapp/locale/en/LC_MESSAGES But when I removed this settings from the settings.py file, it works. How should I do to have the regular po file under each application, "build with the app", but allowing to have a custom.po file which override the default translation? Thank you for your help. Fabrice -
django-taggit obtain tags string from form
I trying to use django-taggit as a tag model. model.py class Product(models.Model): product_no = models.IntegerField(primary_key=True) ... tags = TaggableManager(blank=True) views.py def action(request): product = Product() user = User.objects.get(id=request.user.id) product.seller_username = user ... product.save() tag_list = taggit.utils._parse_tags(request.POST['tags']) product.tags.add(*tag_list) When I call method product.tags.add(), I'm getting an error say Product objects need to have a primary key value before you can access their tags Many solutions I find inform me to put product.save() before product.tags.add() to make pk available before access many-to-many field. I've try it and still the error. Note: the save() method work properly. It create new object in Product list and can be see in admin interface. -
django restframework: how to efficiently search on many to many related fields?
Given these models: class B: my_field = TextField() class A: b = ManyToMany(B) I have +50K rows in A, when searching for elements I want to do full text searches on my_field by traversing the many to many field b (i.e. b__my_field). This works fine when the number of many to many elements Bper A object is less than ~3. How ever if I have something greater than that performance drops impressively. Wondering if I could do some sort of prefetch related search? Is something like haystack my only option? -
how to upload js array data to database using django
I'm new to django. I'm now building a web app with couple slide bar in it. Once user drag these slide bars there data will be stored into an javaScript array. btw I'm using mysql . So, my question is how to upload the whole JS array into database using django? and for django is there a way to change js code just like changing the HTML code? thanks a lot! -
Django Template session not updating values
I am developing a human vs human chess app in django. The part for pawn promotion is not working. The session values are changing,but not getting updated to django template. The promote view def promote(request): #Update board with promoted piece board = request.session['board'] target = request.session['promote_target'] board[target[0]][target[1]] = request.POST['piece'] request.session['board'] = board request.session['promotion'] = False request.session['player'] = 1 request.session.modified = True return render(request,'chess_app/Default.htm') The js Function to call server function promotion(piece){ //Function to promote pawns //Add a confirm message $.ajax({url:"{%url 'promote'%}",data:{'piece':piece},type:'post',success:function(){location.reload()}}); } Everything works fine, but the session is not getting updated It would be great if you can help. -
How to serve files in Django without "/static" prefix
I have an angular 2 front-end with already written links between html js, css and other files such as images, that I would like to serve using Django. The structure from Angular 2 looks like following: -->index.html -->test.js -->test.css HTML file: <!doctype html> <html lang="en"> <head> <link href="test.css" rel="stylesheet"/> </head> <body> <script type="text/javascript" src="test.js"> </body> I wouldn't like to change the given paths from the angular 2 app, instead I would like to know the workaround to serve this files in django without using "/static/< appname>/" or "/static/" prefix or template tags in every link. Thank you in advance! -
Rendering different templates to the same url pattern based on a condition in django views
What i am trying to do ? I am trying to render index.html page if javaScript is enabled in the browser otherwise i want to render jsDisabled.html page if javaScript is disabled but i want both the pages to be rendered on the same url pattern for eg: 127.0.0.1:8000 should either render index.html if javaScript is enabled in the browser or it should render jsDisabled.html page if javaScript is disabled. I am not able to find a way out. Here is my code so far: base.html: {% load staticfiles %} <!DOCTYPE html> <html> <head> </head> <body class="noJs"> ... <a href="{% url 'index' 0 %}"> abc </a> ... <noscript> <style type="text/css"> .noJs { display: none; } </style> <meta http-equiv="refresh" content="{% url 'index' 1 %}"> </noscript> </body> </html> urls.py: from django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = [ ... url(r'^(?P<flag>[0-1])$', views.index, name='index'), ] views.py: from django.shortcuts import render def index(request, flag): if (flag): return render(request,'jsDisabled.html') else: return render(request,'index.html') -
create a calculated field form other models field
I'm new in django. I want to create a table includes some fields which calculated from other models field. class Student(models.Model): name = models.Charfield(max_length = 30) ... class Subject(models.Model): student = models.ForeignKey(Student, related_name = "student_subject") point = models.IntegerField(default = 0) ... How can I create a queryset to get average point for each student? -
Selenium: assert file download
I have following problem. Is there any way I can assert start of file download after button click using python selenium? Thanks in advance! -
Changing model field values through the view
I have this model: class UserNotification(models.Model): user = models.ForeignKey(User,related_name='user',null=True) post = models.ForeignKey('feed.UserPost',related_name='post') timestamp = models.DateTimeField(auto_now_add=True) notify_type = models.CharField(max_length=6) read = models.BooleanField(default=False) def get_absolute_url(self): return reverse('notify:user_notifications') def __str__(self): return str(self.user) It records a user's action in regards to another user's post so that the owner of the post can be notified. I then have this view: class NotifyMarkRead(RedirectView): def get_redirect_url(self,pk): obj = get_object_or_404(UserNotification,pk=pk) if obj.read != True: obj.read == True else: obj.read == False return obj.get_absolute_url() This is the view that handles the user clicking on the notification. This view is supposed to check if read is equal to True or False (it is false by default). If the user clicks on the notification the view is supposed to update read to True. However, it isn't doing that. So how do I update the read field in my model when a user goes through this view? Also I'm no that the page is being accessed however it just goes to /notify/1/read/ instead redirecting back to /notify/. Just sure if that's important here. Here are my urls: from django.conf.urls import url from notify import views app_name = 'notify' urlpatterns = [ url(r'^$',views.UserNotifications.as_view(),name='user_notifications'), url(r'^(?P<pk>\d+)/read/$',views.NotifyMarkRead.as_view(),name='user_notify_toggle'), ] -
Customize label tag and message error in Django AuthenticationForm class
I'm new in django. Is it possible to customize label tag if I want to use email as username login? However if the user doesn't introduce valid information, the error message shows username instead of email. -
--fake and --fake-initial explained
I've been a user of Django for about 2 years now and there is a feature I have always been affraid of using : faking migrations. I've looked pretty much everywhere and the most information I can get is from the documentation where it states that: --fake Tells Django to mark the migrations as having been applied or unapplied, but without actually running the SQL to change your database schema. This is intended for advanced users to manipulate the current migration state directly if they’re manually applying changes; be warned that using --fake runs the risk of putting the migration state table into a state where manual recovery will be needed to make migrations run correctly. --fake-initial Allows Django to skip an app’s initial migration if all database tables with the names of all models created by all CreateModel operations in that migration already exist. This option is intended for use when first running migrations against a database that preexisted the use of migrations. This option does not, however, check for matching database schema beyond matching table names and so is only safe to use if you are confident that your existing schema matches what is recorded in your initial … -
Django CMD Nested plugin inside parent plugin
I have rather a general question or a feature request, not sure. Looks like a very common use case, but I couldn't find any useful information though. I'm trying to prepare around 10-15 custom "high-order" plugins that will consist of simple: text image link h1-h7 elements I'd like these "high-order" to be available for the user in the plugin dropdown and when he selects one - it will add that plugin with nested plugins automatically. So say I have a list of the following "high-order" plugins: image-1 Another example - let's assume I'm creating a plugin that looks like this bar: image-3 I imagine it will automatically add multiple buttons, text and header fields as nested/child plugins into my parent plugin. Is that easily possible within Django CMS? I was googling for nested plugins, but couldn't find any useful information about it.