Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to redirect to another app directory after loging in django?
I have two app directories in my django project named "visit" and "main". After Loging the user in through visit app, how do I change the app directory to another main i;e how to display templates from another app (excuse my english) ? visit/views.py : from django.shortcuts import render from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect from django import forms from .forms import UserRegistrationForm def index(request): return render(request, 'visit/index.html', context=None) def profile(request): # I need to change directory form here return render(request, 'main/templates/main/profile.html') def registration(request): if request.method == "POST": form = UserRegistrationForm(request.POST) if form.is_valid(): formObj = form.cleaned_data username = formObj["username"] name = formObj["name"] email = formObj["email"] password = formObj["password"] if not (User.objects.filter(username=username).exists() or User.objects.filter(email=email).exists()): User.objects.create_user(username, email, password) user = authenticate(username=username, name=name, password=password) login(request, user) return HttpResponseRedirect('/profile/') else: form = UserRegistrationForm() return render(request, 'visit/registration/register.html', {'form': form}) -
No module named 'django.urls'
I'm trying to set up django-registration-redux, but when I set up the url (r '^ accounts /', include ('registration.backends.default.urls')) in the urls.py file and I try to access any page I get the following error message: ModuleNotFoundError No module named 'django.urls' I have checked the manual several times and everything is in order. What is missing? Where is my mistake? urls.py file """p110 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf import settings from django.conf.urls.static import static from django.conf.urls import include, url from django.contrib import admin from boletin import views from .views import about urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', views.index, name='index'), url(r'^contact/$', views.contact, name='contact'), url(r'^about/$', about, name='about'), url(r'^accounts/', include('registration.backends.default.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) -
Django queryset result is wrong for the test
My model is: class AndroidOffer(models.Model): name = models.CharField(max_length=128, db_index=True) # ... countries = models.ManyToManyField(Country) And the following code (I skipped previous filtering): active_offers = active_offers.filter(countries__in=[country]) It generates this SQL query: SELECT "offers_androidoffer"."id", "offers_androidoffer"."name", "offers_androidoffer"."title", "offers_androidoffer"."is_for_android", "offers_androidoffer"."is_for_ios", "offers_androidoffer"."url", "offers_androidoffer"."icon", "offers_androidoffer"."cost", "offers_androidoffer"."quantity", "offers_androidoffer"."hourly_completions", "offers_androidoffer"."is_active", "offers_androidoffer"."description", "offers_androidoffer"."comment", "offers_androidoffer"."priority", "offers_androidoffer"."offer_type", "offers_androidoffer"."package_name", "offers_androidoffer"."is_search_install", "offers_androidoffer"."search_query", "offers_androidoffer"."launches" FROM "offers_androidoffer" INNER JOIN "offers_androidoffer_platform_versions" ON ("offers_androidoffer"."id" = "offers_androidoffer_platform_versions"."androidoffer_id") INNER JOIN "offers_androidoffer_countries" ON ("offers_androidoffer"."id" = "offers_androidoffer_countries"."androidoffer_id") WHERE ("offers_androidoffer"."is_active" = True AND "offers_androidoffer"."quantity" > 0 AND NOT ("offers_androidoffer"."id" IN (SELECT U0."offer_id" FROM "offers_androidofferstate" U0 WHERE (U0."device_id" = 1 AND (U0."state" = 3 OR U0."state" = 4)))) AND NOT ("offers_androidoffer"."package_name" IN (SELECT V0."package_name" FROM "applications_app" V0 INNER JOIN "applications_deviceapp" V1 ON (V0."id" = V1."app_id") WHERE (V1."device_id" IN (SELECT U0."device_id" FROM "users_userdevice" U0 WHERE U0."user_id" = 2) AND NOT (V0."package_name" IN (SELECT U2."package_name" FROM "offers_androidofferstate" U0 INNER JOIN "offers_androidoffer" U2 ON (U0."offer_id" = U2."id") WHERE (U0."device_id" = 1 AND (U0."state" = 0 OR U0."state" = 1 OR U0."state" = 2))))))) AND "offers_androidoffer_platform_versions"."platformversion_id" IN (14) AND "offers_androidoffer_countries"."country_id" IN (6252001)) ORDER BY "offers_androidoffer"."priority" DESC; If I run this query in Postgresql console, it will return 0 rows, but active_offers has 4 results (all rows in table), like if I remove AND "offers_androidoffer_countries"."country_id" IN (6252001) statement. … -
How to pull a html template on a $.post call, and include data?
I have the following code on one Django HTML template that when it runs it pulls the html from another template and loads it into the #container element. $.get('/form/', function(form){ $('#container').html(form); }); So if I was to follow the same thought process I have this code on another page in which I need to use a POST request instead of GET. $.post( '/form/results/', {item: $('#item-selector').val(), csrfmiddlewaretoken: csrftoken}, function(data){ $('#container').html(data) } ) So what I'm trying to get the post request to do is to pull the html from the url and insert it into the #container element but I can't get it to work. If you need any more information just comment below and I will add it. -
What is an example use case of using primaryfieldserializer in django rest framework?
I had a goal, to link cities and their neighborhoods together in a request response in a nested serializer. Neighborhoods have a Foriegn key to cities. for clarity here are my models and serializer originally used. class SearchCity(models.Model): city = models.CharField(max_length=200) class SearchNeighborhood(models.Model): city = models.ForeignKey(SearchCity, on_delete=models.CASCADE) neighborhood = models.CharField(max_length=200) class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer): searchneighborhood_set = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = SearchCity fields = ('city','searchneighborhood_set') read_only_fields =('city', 'searchneighborhood_set') but that returned only the neighborhood primary keys with the cities not a full city object. This: city: "Chicago" searchneighborhood_set: 0: 5 1: 4 2: 3 city: "New York" searchneighborhood_set: 0: 8 1: 7 2: 6 instead of what it should be, this: city: Chicago searchneighborhood_set: 0: {pk: 5, neighborhood: 'River North} .... I got the above request, not by using primarykeyrelatedserializer but by using the serializer used for seralizing neighborhood objects which looks like this: class SearchNeighborhoodSerializer(serializers.ModelSerializer): class Meta: model = SearchNeighborhood fields = ('pk','neighborhood') so now replace the primarykeyrealatedserializer with my neighborhood one and the proper nested serailzer is this: class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer): searchneighborhood_set = SearchNeighborhoodSerializer(many=True, read_only=True) class Meta: model = SearchCity fields = ('city','searchneighborhood_set') read_only_fields =('city', 'searchneighborhood_set') so this begs the question, what is an actual use case for the primarykeyrelated … -
relation "django_admin_log" already exists
when i try to run python manage.py migrate i run into following error Upon running python manage.py run migrations it says no changes detected. and when i runserver it gives me warning that i have unapplied migrations as well.i have been searching internet for two hours but got not solution. Someone knowing the solution please share :) -
How to add django Group field to a Customer User Register
i used this Code in serializer.py group = Group.objects.get() group.user_set.add(self.object) it work fine when the Group Field have just one item and added in DB with no problem. But when i add more than one item in The Group List Field i am getting an Error: get() returned more than one Group -- it returned 2! what can i do ? Image:For one item Work Fine Image:With More than one i am getting This Error This is My Full Code: from rest_framework import serializers from . import models from django.contrib.auth import get_user_model from django.contrib.auth.models import Group User = get_user_model() class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) confirm_password = serializers.CharField(write_only=True) def validate(self, data): if not data.get('password') or not data.get('confirm_password'): raise serializers.ValidationError("Please enter a password and ""confirm it.") if data.get('password') != data.get('confirm_password'): raise serializers.ValidationError("Those passwords don't match.") return data def create(self, validated_data): user = get_user_model().objects.create( username=validated_data['username'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], email=validated_data['email'] ) group = Group.objects.get() group.user_set.add(self.object) user.set_password(validated_data['password']) user.save() return user class Meta: model = get_user_model() fields = ( 'username', 'password', 'confirm_password', 'first_name', 'last_name', 'email', 'groups', ) -
Django middleware for consuming an external api
Here's the deal, I need to consume an API and every time I perform a request a header needs to be appended, I've checked the middleware documentation but this is only working for incoming requests, is there anything that can be used in this situation. -
What is main use of queryset.in_bulk in Django framework?
I'm curious, what is use cases for queryset's in_bulk method? -
django/python logging with gunicorn: how does django logging work with gunicorn
I have a Django/Python application deployed(using gunicorn) with 9 workers with 5 thread each. Let's say if on a given time 45 requests are getting processed, Each thread is writing a lot of logs. How Django avoids writing logs for multiple threads at the same time? And how the file open and close works for each request(does this happen at each request, if yes, any other efficient way of logging)? -
How to manually create tags using Bootstrap Tags Input
I am using Bootstrap Tags Input for introducing tagging mechanism in my project. So far I can easily load predefined tags using add method as described in the documentation, But I am unable to create tags manually. Say I type some text and press space or comma button then a new tag should be created, Just like we add tags while writing Stack overflow question. Is it possible to add this behaviour, any help would be appreciated. -
'update_grid' object has no attribute 'title'
I have written model.py and views.py.When I add the json variable from Admin it gives following error 'update_grid' object has no attribute 'title' My views.py def save_grid(request): if request.method == 'POST': data = json.loads(request.body) grid = update_grid(data=data) grid.save() return HttpResponse('success') # if everything is OK My models.py from django.db import models from django.utils import timezone from jsonfield import JSONField class update_grid(models.Model): data = JSONField() def __str__(self): return self.title My JSON variable is of the form [{"col":1,"row":1,"size_x":1,"size_y":1},{"col":2,"row":1,"size_x":1,"size_y":1},{"col":3,"row":1,"size_x":1,"size_y":1},{"col":4,"row":1,"size_x":1,"size_y":1},{"col":1,"row":2,"size_x":1,"size_y":1},{"col":2,"row":2,"size_x":1,"size_y":1},{"col":3,"row":2,"size_x":1,"size_y":1},{"col":4,"row":2,"size_x":1,"size_y":1},{"col":1,"row":3,"size_x":1,"size_y":1},{"col":2,"row":3,"size_x":1,"size_y":1},{"col":3,"row":3,"size_x":1,"size_y":1},{"col":4,"row":3,"size_x":1,"size_y":1},{"col":5,"row":1,"size_x":1,"size_y":1},{"col":6,"row":1,"size_x":1,"size_y":1}] -
Django querying user_auth with each request
When I login and visit any page, Django will proceed to do this query everytime: SELECT ••• FROM "auth_user" WHERE "auth_user"."id" = '1' How can I stop it? I am already saving the session in cache, I have also deleted all tags that use request and nothing happens, django will still make the query, only time it does not make the query is when I am an AnonymousUser. Version of django is: 2.0.2 -
how to get all values of primary key related field nested serializer django rest framework
I have the following models: class SearchCity(models.Model): city = models.CharField(max_length=200) class SearchNeighborhood(models.Model): city = models.ForeignKey(SearchCity, on_delete=models.CASCADE) neighborhood = models.CharField(max_length=200) and then the following nested serializer: class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer): searchneighborhood_set = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = SearchCity fields = ('city','searchneighborhood_set') read_only_fields =('city', 'searchneighborhood_set') paired with the view: class CityNeighborhoodView(ListAPIView): queryset = SearchCity.objects.all() serializer_class = CityNeighborhoodReadOnlySerializer when I make the api call I get this: city: "Chicago" searchneighborhood_set: 0: 5 1: 4 2: 3 city: "New York" searchneighborhood_set: 0: 8 1: 7 2: 6 Im just getting the primary keys of the objects related. Which is good I need that, but I also want the neighborhood name how do I get that? -
How to get all coordinates under a boundary in Google maps API and django
I've Coordinate data associated with a post what I want is that, let's say someone posted a post with coordinated of some coffee shop Manhattan, I wanna get that post while querying New York. One way I can think of to tackle this problem is to get all coordinates under New York and search it that way I know it's very stupid but I can't think of any other way. -
Download specific file after submiting key Django
I want to ask user about previously generated key to grand him permission to download a file from the server. The key is being kept in database. My template is supposed to display all available files in the folder, ask for the key and return user to the url with auto download response with specific file, if the validation based on given key succeeded. Unfortunately I struggle with put all things together. # views.py which is supposed to check for everything # ATM it doesn't check anything, just prepared query for the validation def list(request): folder = settings.MEDIA_ROOT file_list = os.listdir(folder) form = KeyForm(request.POST) if request.method == 'POST': if form.is_valid(): secret = form.cleaned_data['secret_key'] obj = Items.objects.get(secret=secret) return render_to_response('list.html', {'form': form, 'file_list': file_list}) return render(request, 'list.html', {'form': form, 'file_list': file_list}) #function which wrapps the file and return response with the file def download_file(request, file_name): file_path = settings.MEDIA_ROOT + file_name wrapper = FileWrapper(open(file_path, 'rb')) response = HttpResponse(wrapper, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=' + file_name return response # list.html <body> {% for file in file_list %} <form action="/download/{{ file }}" method="post">{% csrf_token %} {% endfor %} <select name="file" id="file"><br> {% for file in file_list %} <option value="{{ file }}">{{ file }}</option> {% endfor … -
Django-debug-toolbar shows duplicates in sql queries, how bad is it to have duplicates?
django-debug-toolbar showed this message: 392.81 ms (263 queries including 255 duplicates ) how bad is it to have a lot of duplicates, and how can i prevent it? Thank you -
paging through cql query on django
I have two queries. One that gives me the first page from a cassandra table, and another one that retrieves the successive pages. The fist one is like : select * from images_by_user where token(iduser) = token(5) limit 10 allow filtering; The successive ones are : select * from images_by_user where token(iduser) = token(5) and imagekey > 90b18881-ccd3-4ed4-8cdf-d71eb99b3505 limit 10 allow filtering; where the image key is the last one on the first page. I have 13 rows in the table. The first query returns 10 both on the cqlsh and the application (consistency level ONE just for development). The second query only retrieves results on clash. Below is the cassandra database engine configuration I have on the django application : 'ENGINE': 'django_cassandra_engine', 'NAME': 'xekmypic', 'HOST': 'localhost', 'OPTIONS': { 'replication': { 'strategy_class': 'SimpleStrategy', 'replication_factor': 1 }, 'connection': { 'consistency': ConsistencyLevel.LOCAL_ONE, 'retry_connect': True # + All connection options for cassandra.cluster.Cluster() } } The cassandra version I am using is doc-3.0.9 and below is my virtual env pip list : cassandra-driver (3.9.0) Cython (0.25) Django (1.11) django-cassandra-engine (1.1.0) mysqlclient (1.3.10) olefile (0.44) Pillow (4.1.0) pip (7.1.2) python-memcached (1.58) pytz (2017.2) setuptools (18.2) six (1.10.0) Why does the second page does not return … -
Django create multy file field
Sorry for my english. I need create multy file field for upload pdf and images. I dont know, i correct did it or not. Please give me some i have not model, it my serializer: class MultyFieldSerializer(serializers.Serializer): attachments = serializers.ListField( child=serializers.FileField(max_length=100000, allow_empty_file=False, use_url=False) ) my question. Is this correct fileld for upload file in server? -
Random HTTP 500 error Django
Ive been having an issue with a HTTP 500 error , doesn't seem to cause any real problems until a few hours after the error has showed, the script begins to act abnormally when trying to toggle a relay( which is one of its functions) i checked my logs both in the pi and the server side these are what i found On the pi: tail applocation/errors.log 2018-03-05 06:38:33 [HTTP Error] While sending data to remote Server: HTTP Error 500: Internal Server Error 2018-03-05 09:08:50 [HTTP Error] While sending data to remote Server: HTTP Error 500: Internal Server Error on the server: This is where it gets weird because most of the time it returns 200 but like i said every so often i gives a 500 error cat /var/log/ngnix/access.log | grep 9:0 47.176.12.130 - - [05/Mar/2018:09:08:29 -0800] "POST /api/1.0/access/add/ HTTP/1.1" 200 43 "-" "Python-urllib/3.4" 47.176.12.130 - - [05/Mar/2018:09:08:50 -0800] "POST /api/1.0/access/add/ HTTP/1.1" 500 38 "-" "Python-urllib/3.4" 47.176.12.130 - - [05/Mar/2018:09:09:28 -0800] "POST /api/1.0/access/add/ HTTP/1.1" 200 43 "-" "Python-urllib/3.4" cat /var/log/ngnix/access.log | grep 500 raspberry.pi.ip - - [05/Mar/2018:06:38:33 -0800] "POST /api/1.0/access/add/ HTTP/1.1" 500 38 "-" "Python-urllib/3.4" raspberry.pi.ip - - [05/Mar/2018:09:08:50 -0800] "POST /api/1.0/access/add/ HTTP/1.1" 500 38 "-" "Python-urllib/3.4" in my … -
Setup Nginx as a proxy to Nuxtjs and Django
I have a web project working locally in my machine. I am using Django for the backend, and Nuxtjs (vuejs server side rendering framework). Nuxtjs communicate to Django with the API. Django is running on a Vagrant machine on port 0:80, and Nuxtjs is running on my localhost:3000. Both are working fine. Now I would like to deploy it on a VPS, and would like to setup Nginx as the reverse proxy for the app. I know how to run Django with Gunicorn and Nginx as the proxy. But, how can I configure Nginx to run Nuxtjs (node server) on the front-end, and Django as its backend. I hope I was clear, and if not please ask. Thank you. -
Do all tables need to be built as models?
I am new to Django and trying to figure out models. I have a question that I just cannot find the answer to. I am designing an equipment checkout app. I would like to have a data entry page (/Admin) where we can enter the equipment names and types...no problem (I think). However, I also need a Checkout table that will be updated as equipment is checked in and out and an Employee table that would hopefully pull from AD. My question is, do these two tables that will not be updated manually on the Admin page still need to be defined as models? Is this where the 'EDITABLE' field option comes in? Thanks! -
django ajax return more than one piece of html and mount
Because of a limitation in bootstrap modals that they need to be outside a postion: fixed, I need to return 2 separate pieces of html in django after an ajax response (a list of items and their modals) Is there a way in django to return 2 pieces of redendered html? Currently I have in the ajax view I return a single piece of html with: return render(request, 'pages/quotes_results.html', context) which I mount with: $.ajax({ url: '/users/some_ajax_view/', data: { 'filters': filters }, success: function (data) { $('.ajax-block').html(data) } }) -
Django executing tests for app not in INSTALLED_APPS
Under my Django project there are a few apps and all of them have unit tests. One of them that I'm working right now is supposed to be included only in dev/stage environments, so I'm enabling it using a environment variable. When this variable is present it is added to INSTALLED_APPS and it is working just fine, the problem is that Django is executing the tests for this app even when it is not in INSTALLED_APPS, and it fails with the following message: ImportError: Failed to import test module: debug.tests.unit.test_services` ...(traceback information)... RuntimeError: Model class debug.models.Email doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. When I define the app_label in the class Meta of models in this app the error is different, it says it can't find a table, I assume that this is because the app is not in INSTALLED_APPS, so it's migrations are not executed. OperationalError: no such table: debug_email I'm not sure why Django executes the tests for all apps, but not it's migrations. Am I missing something from Django configuration for tests? -
Celery and Django, queries cause ProgrammingError
I'm building a small Django project with cookiecutter-django and I need to run tasks in the background. Even though I set up the project with cookiecutter I'm facing some issues with Celery. Let's say I have a model class called Job with three fields: a default primary key, a UUID and a date: class Job(models.Model): access_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) date = models.DateTimeField(auto_now_add=True) Now if I do the following in a Django view everything works fine: job1 = Job() job1.save() logger.info("Created job {}".format(job1.access_id)) job2 = Job.objects.get(access_id=job1.access_id) logger.info("Rertieved job {}".format(job2.access_id)) If I create a Celery task that does exactly the same, I get an error: django.db.utils.ProgrammingError: relation "metagrabber_job" does not exist LINE 1: INSERT INTO "metagrabber_job" ("access_id", "date") VALUES ('e8a2... Similarly this is what my Postgres docker container says at that moment: postgres_1 | 2018-03-05 18:23:23.008 UTC [85] STATEMENT: INSERT INTO "metagrabber_job" ("access_id", "date") VALUES ('e8a26945-67c7-4c66-afd1-bbf77cc7ff6d'::uuid, '2018-03-05T18:23:23.008085+00:00'::timestamptz) RETURNING "metagrabber_job"."id" Interestingly enough, if I look into my Django admin I do see that a Job object is created, but it carries a different UUID as the logs say.. If I then set CELERY_ALWAYS_EAGER = False to make Django execute the task and not Celery: voila, it works again without error. But running …