Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - usage of redirect_to_login
I want to use redirect_to_login in my view. For some reason, I get redirected to login twice (and therefore the URL is malformed). My TestView(View) looks like this (relevant part): def dispatch(self, request, *args, **kwargs): if not self.test_func(): if self.redirect_to_login: return redirect_to_login(self.request.get_full_path()) else: return HttpResponseForbidden() My urls.py (relevant part): url(r'^test/$', TestView.as_view()), When I type localhost:8000/test/ into my browser, I end up at http://localhost:8000/login/?next=/%3Fnext%3D/test/ instead of expected http://localhost:8000/login/?next=/test/ Any ideas what the problem might be? In case you need more files, just please ask. -
Django ManyToMany Through model inline in ModelForm
I'm trying to figure out the simpiest way to add through model into the modelform. class UserProfile(models.Model): user = models.OneToOneField('auth.User',related_name='userprofile') profile_picture = models.ImageField() #TODO: povinne ale moze vybrat z defaultov languages = models.ManyToManyField('userprofiles.Language',through='UserProfileLanguage') class UserProfileLanguage(models.Model): userprofile = models.ForeignKey('UserProfile',related_name='userprofile_languages') language = models.ForeignKey('Language') level = models.CharField(max_length=50,choices=settings.USERPROFILE_LANGUAGE_LEVEL_CHOICES) class Language(models.Model): english_name = models.CharField(max_length=100, unique=True) native_name = models.CharField(max_length=100,null=True, blank=True) As you can see userprofile can have multiple languages, but there is a level of this knowledge required. I can't add 'languages' field into a ModelForm fields because I need to specify level for any language. I'm curious if there is some built in way to do this or should I create manualy ModelFormset and override UserProfile save(..) method. -
How do I host a Django project on a host that already exists?
I have a project in Django and I have a host that was sent to me where my project should appear, but I do not know how I will do it. I uploaded the project folder with a Filezilla, but I do not know if it is possible to run the Django commands in SSH or SFTP. I've watched some related videos, but they all teach how to host them in Heroku and PythonAnyWhere, but I need to host it on my university website. What should I do? -
Django makemigrations wonkyness
I am experience two, probably related, odd issues that have just recently began plaguing me. Issue One: When I run python makemigrations myapp --settings=mysettings it detects a change in one of my models that I did not make. Namely, it detects an 'id' field added to my model without a default. It therefore wants me to provide a one-off default. When I do this, it then fails to migrate giving me generic error messages such as the in() argument must be a string or a number, not (whatever I entered, an integer, a string, a datetime, anything as a one-off). The annoying thing about this is that there is no ID field added and I am not sure why it is detected this change. Issue Two: Makemigrations is not detecting changes. I recently added a new model to a django app that has been working fine for quite some time. It does indeed exist in the installed apps, however it will not detect that a new model is being added to my models.py of this app. There is really no reason I can see this happening. I have been working around this issue by writing my own migration files, but … -
Auto-generated field 'user_ptr' clashes with declared field of the same name
I have a Django app that has CustomUser. My model looks something like class CustomUser(AbstractBaseUser): def get_short_name(self): pass def get_full_name(self): pass firstName = models.CharField(max_length=300) middleName = models.CharField(max_length=300, blank=True) lastName = models.CharField(max_length=300, blank=True) username = models.CharField(unique=True, max_length=50) businessName = models.CharField(max_length=500, default=None) mobileNumber = models.CharField(max_length=20) contactNumber = models.CharField(max_length=20) addressLine1 = models.CharField(max_length=300) addressLine2 = models.CharField(max_length=300) city = models.CharField(max_length=300) state = models.CharField(max_length=300) role = models.CharField(max_length=20) email_id = models.CharField(max_length=300, unique=True) aadharNumber = models.BigIntegerField(default=0) panNumber = models.CharField(max_length=20, default=None) registrationDate = models.BigIntegerField(default=0) bankDetail = models.ManyToManyField('BankDetail', related_name="bankDetail") dateCreated = models.DateTimeField(auto_now_add=True) dateModified = models.DateTimeField(auto_now=True) objects = AccountManager() USERNAME_FIELD = 'email_id' REQUIRED_FIELDS = ['username'] I was following the example in this blog https://afropolymath.svbtle.com/authentication-using-django-rest-framework to implement User authentication. I get the following error when I run makemigrations I did look at a few solutions on StackOverflow but those don't seem to solve my problem. Django error message "Add a related_name argument to the definition" AlterField on auto generated _ptr field in migration causes FieldError Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line … -
Django Serializes not outputting to template
I have a local branch and a remote dev branch. These instructions work on the local branch perfectly, but when I push to the remote branch they do not. They're both running the same django version and the files are identical!! $(document).delegate("#btn-generate-note", "click", function(event) { var stringToTransfer = ""; var json = [{"model": "logi.tblpolines", "pk": 2014279, .... etc }); That's the output from the browser: A beautiful JSON for var json, but this is the output from the remote server: $(document).delegate("#btn-generate-note", "click", function(event) { var stringToTransfer = ""; var json = ; ... It's nothing. I can't for the life of me reason why. Here's the template.html code: var stringToTransfer = ""; var json = {{ json_list_items|safe }}; And the view.py code: json_list_items = serializers.serialize('json', items_query.objects.all()) ... return render(request, 'some/address/in/space.html', context={ 'po_id': po_id, ... 'json_list_items': json_list_items }) The imports are identical everything is the same, but I'm not getting a json back in the remote. I've been on this for hours. -
Django Channels websocket connection handshake failing
I've been trying to follow this tutorial on using Django Channels for a WebSocket-enabled web app. When I get to the part where I'm supposed to test if the server is accepting sockets, I get the following error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "E:\Python\django\multichat\venv\lib\site-packages\websocket\_core.py", line 214, in connect self.handshake_response = handshake(self.sock, *addrs, **options) File "E:\Python\django\multichat\venv\lib\site-packages\websocket\_handshake.py", line 69, in handshake status, resp = _get_resp_headers(sock) File "E:\Python\django\multichat\venv\lib\site-packages\websocket\_handshake.py", line 129, in _get_resp_headers raise WebSocketBadStatusException("Handshake status %d", status) websocket._exceptions.WebSocketBadStatusException: Handshake status 200 Also, according to the tutorial, I'm supposed to see something akin to this in the server console: WebSocket CONNECT / [127.0.0.1:55905] But instead I am getting this: "GET / HTTP/1.1" 200 1716 It's looking like either my python shell script is sending an HTTP request when its supposed to be sending a WebSocket request, or my server is interpreting the WebSocket request as an HTTP request. I have no idea what would cause either of those things to happen. My settings.py file is a freshly generated one with only the following added to it: redis_host = os.environ.get('REDIS_HOST', 'localhost') # Channel layer definitions # http://channels.readthedocs.org/en/latest/deploying.html#setting-up-a-channel-backend CHANNEL_LAYERS = { "default": { # This example app uses the … -
Django page not found, ajax request not working correctly
Trying to send an ajax request to a django server and get a response containing some random data. The homepage works, but the ajax request gives a 404 error as follows: Using the URLconf defined in bms_project.urls, Django tried these URL patterns, in this order: ^headstation/ ^admin/ The current path, chart_data/, didn't match any of these. You're seeing this error because you have <code>DEBUG = True</code> in your Django settings file. Change that to <code>False</code>, and Django will display a standard 404 page. The url pattern is listen in a urls.py file inside the "headstation directory, then included by the normal urls.py script. It works for the home page: project urls.py urlpatterns = [ url(r'^headstation/', include('headstation.urls')), url(r'^admin/', admin.site.urls), ] headstation urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^chart_data/$', views.chart_data, name='chart_data') ] views.py def index(request): # get context of request from client context = RequestContext(request) # construct dictionary to pass template + context context_dict = {'buildingName': 'The Building', 'boldmessage': 'Put a message here'} #render and return to client return render_to_response('headstation/home.html', context_dict, context) def chart_data(request): if (request.method == 'POST'): dataX = [0,10,20,30,40,50,60] dataY = [25.0,24.2,25,24.0,24.5,25.1,25.5] response = {"x": dataX, "y": dataY} return JsonResponse(response) and finally, home.html where the ajax request is coming … -
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.