Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best data structure for one to many relation on Django?
For instance, let's suppose we have a webapp with Pizza and Toppings. One pizza can have many toppings but a topping cannot have many pizzas, which seems logical so far. I'm using a structure like this one below but I am not sure wether I should use ManyToMany Field or ForeignKey since OneToMany doesn't exist on Django. class Pizza(models.Model): created_at = models.DateTimeField(auto_now_add=True) order_id = models.CharField(max_length=255) def __str__(self): return self.order_id class Topping(models.Model): created_at = models.DateTimeField(auto_now_add=True) topping_name = models.(max_length=255) pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE) #if a pizza is deleted, delete its toppings. def __str__(self): return self.topping_name If I'm doing this right, should I access a pizza and all its toppings like this ? pizzas = Pizza.topping_set.filter(order_id=my_order_id) Is there a better way or is it optimal to keep it like this? -
Upstream prematurely closed connection while reading response header from upstream. NGINX, uWSGI, supervisor
I am trying to deploy django on ubuntu 16.04 on a DO droplet using uWSGI, NGINX and supervisor. I am successfully running the app with python manage.py runserver [ip]:8000 and uwsgi --http-socket :8080 --module saleor.wsgi When I try to run the app with supervisor I am getting: 502 Bad Gateway in the browser. In the ngxinx logs I am getting: upstream prematurely closed connection while reading response header from upstream my nginx conf file: saleor_nginx.conf # the upstream component nginx needs to connect to upstream saleor { server unix:///etc/uwsgi/saleor.sock; # for a file socket #server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { listen 80 default_server; server_name example.com; # IP removed from post on purpose charset utf-8; # max upload size client_max_body_size 4G; # adjust to taste access_log /webapps/saleor/saleor/logs/nginx-access.log; error_log /webapps/saleor/saleor/logs/nginx-error.log; # Django media location /media { alias /webapps/saleor/saleor/media; # your Django project's media files - amend as required } location /static { alias /webapps/saleor/saleor/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass unix:///etc/uwsgi/saleor.sock; include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed … -
How to make testing cache storage (Redis) in Django with Pytest?
I'm using Django 1.11.9 with django-pytest library for testing my apps. Also, I use Redis as cache storage. My question is — how to make testing cache storage and setting up his with test data before run test? Like database do it. I want to add some key: value data to testing cache storage (in Redis), run tests and then delete all of this test data (clear test cache). -
Django rest framework api response add-on
So i have a table call Book. I am using modelviewset but i wanted my response to have an add on response. In my Book table : class Book(models.Model): book = models.CharField(max_length=10, blank=True, null=True) author = models.CharField(max_length=10, blank=True, null=True) serializer class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('id', 'book', 'author') view class BookViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = Book.objects.all() serializer_class = BookSerializer the return result after post or update method will return the data/field which user have create/update. But i wanted to add on to it for example. current result { "id": 1, "book": "hello", "author": "helloauth", } result i want { "id": 1, "book": "hello", "author": "helloauth", "message": "You have successfully create a book", "status": "200", } The custom code i have now is just showing the message only: custom views class BookViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = Book.objects.all() serializer_class = BookSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response({"message": "You have successfully create a book", "status": "200"}, headers=headers) How to i make it combine/display together ? -
Django API modify JSON response
I'm trying to make an API with Django rest framework but I'm struggling to modify the JSON response as I want. If you need anything else, just ask, Thanks for your help! models.py class Feature(models.Model): name = models.CharField(max_length=255, unique=True, null=True) def __str__(self): return "{}" .format(self.name) def save(self, *args, **kwargs): super(Feature, self).save(*args, **kwargs) class Opponent(models.Model): name = models.CharField(max_length=255, unique=True, null=True) features = models.ManyToManyField(Feature, blank=True, null=True) def __str__(self): return "{}" .format(self.name) def save(self, *args, **kwargs): super(Opponent, self).save(*args, **kwargs) serializers.py class FeatureSerializer(serializers.ModelSerializer): opponents = serializers.RelatedField(many=True) class Meta: model = Feature views.py @csrf_exempt @jsonify def get_opponents(request): if request.method == 'OPTIONS': return HttpResponse() opponents = list(Opponent.objects.all().values('id', 'features')) return opponents JSON response [ { "id": 1, "features__name": "feature1" }, { "id": 1, "features__name": "feature2" } ] What I want [ { "id": 1, "features": ["feature1", "feature2"] } ] -
How to produce upwards compatible Django (for Django and apache unattended security updates)
I am writing (my first) Django application, which will run on a (public accessible) Ubuntu LTS server (apache) where users (just a very small number, not "the public") can, amongst other things, upload files. Ideally this application should run for many years to come; there will be no need for any feature upgrades or updates in the interface etc; I would just like to get necessary security updates with as little future effort as possible. So I use the current standard ubuntu LTS packages: python 3.5 and Django 1.8. This way, any future security vulnerabilities will be fixed "automatically" (i.e., by the ubuntu security team). To clarify: With security I mean I want to make sure that the server isn't hacked and used to serve some illegal crap, or delete the data. I am much less concerned about availability: If evil hackers bring the server down by DOS attacks or similar so be it. (Actually, I wouldn't even be a catastrophe if hackers stole all the data). Anyways, for reasons of automatic, unattended security updates I do not want to use backports or pip. Django 1.8 is supported only till mid 2018 (according to https://www.djangoproject.com/download/). I assume it will eventually … -
Django how to get the id of already created item in file rename
def file_directory_path(instance, filename): filename_tr = filename name = os.path.splitext(filename)[0] ext = os.path.splitext(filename)[1] filename_tr = str(instance.pk) + "_" + name + ext return 'files/%s' % (filename_tr) here the instance.pk is set to None when a the model object is not yet created, is there a way to somehow get the id after it is created? or the only way is to rename it again in the save_model handler? -
How can I set the token expiration with social-auth-app-django to last for a given amount of seconds?
Currently I call convert_token to signup a social user, then I send my social (facebook, google) token in each drf request using header: Authorization: Bearer facebook|google-oauth2 ya29.***** (Google plus access token) but after a while the token expires, is there a global configuration key that I can set the token_expiry to None or custom number of seconds ? Which will work for all the oauth backends I need, I use Twitter, Google and Facebook. I tried: FACEBOOK_EXTENDED_PERMISSIONS = {'access_type': 'offline'} GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = {'access_type': 'offline'} But I don't found any for Twitter. 1) Can I set the token_expiry in the dictionaries above 2) Can I have a more global config that will affect all backends ? -
centOS install mysqlclient fail (via pip3)
I am trying to run Django2.0 on centOS server, I have installed python3 and pip3, django2.0 also installed under virtualenv, but an error pop out when I tried to install mysqlclient under virturlenv, error msg below: Collecting mysqlclient Using cached mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-7hd8p93o/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/tmp/pip-build-7hd8p93o/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/tmp/pip-build-7hd8p93o/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-7hd8p93o/mysqlclient/ Any idea please -
Nested ModelSerializer
I am trying to provide a nested json file through Django Rest Framework. I have been reading up on different way to nest my serializers but I am not getting it to work. I don't know how to create a modelserializer by myself, instead of directly pulling the data from my model... My error: AttributeError at /listings.json Got AttributeError when attempting to get a value for field coordinates on serializer TestSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Test instance. Original exception text was: 'Test' object has no attribute 'coordinates'. My serializer code: from rest_framework import serializers from rentlistings.models import Test class coordinatesSerializer(serializers.ModelSerializer): class Meta: model = Test fields = ('latitude', 'longitude') class propertiesSerializer(serializers.ModelSerializer): class Meta: model = Test fields = ('price', 'price', 'yields', 'num_floor', 'num_rooms', 'elevator', 'garage', 'balcony_size', 'garden_area', 'parking', 'terass', 'loggia', 'cellar', 'hash_id') class TestSerializer(serializers.Serializer): coordinates = coordinatesSerializer() properties = propertiesSerializer() class Meta: model = Test fields = ('coordinates', 'properties') My views.py from rentlistings.models import Test from rentlistings.serializers import TestSerializer from rest_framework import generics # Create your views here. class test_list(generics.ListCreateAPIView): queryset = Test.objects.all() serializer_class = TestSerializer -
Django REST Framework move all urls to router
I have little experience in python. Please could you help me. There is an old project which has the following structure # -*- coding: utf-8 -*- import re from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.views.static import serve from rest_framework import routers # i added it import home.views router = routers.DefaultRouter() # i added it urlpatterns = [ url(r'^$', home.views.HomeView.as_view()), url(r'^api/v2/', include('api.v2.urls', namespace='api-v2')), url(r'^help/', include('helps.urls', namespace='helps')), url(r'^admin/', include(admin.site.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), # i added it url(r'^', include(router.urls)) # i added it ] I would like to make REST API so that you can see all possible routes. So i try to add rest_framework.urls. As I understood it is necessary to use VeiwSet to add it to router. I do not quite understand how I can use what I already have to see links in a REST API? Or for each link i need to create a Veiwset? For example api.v2.urls contains next: (similar in helps.urls, etc) # -*- coding: utf-8 -*- from django.conf.urls import url import api.v2.views urlpatterns = [ url(r'^data/info', api.v2.views.info_data), url(r'^visits$', api.v2.views.visits), url(r'^highlevel/', api.v2.views.highlevel), url(r'^additional_info/', api.v2.views.additional_info), ] -
Django, best way to print a field key
I want to print fields of a model differently than by first_name I want to print something like "key: value" but it prints "first_name: Georges", I would prefer that it's looks like "First name: Georges" Currently i'm using a file named form.html that I include in every form template: {% load widget_tweaks %} {% for field in form %} <div class="form-group"> {{ field.label_tag }} {% if form.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% else %} {% render_field field class="form-control is-valid" %} {% endif %} {% else %} {% render_field field class="form-control" %} {% endif %} {% if field.help_text %} <small class="form-text text-muted"> {{ field.help_text }} </small> {% endif %} </div> {% endfor %} And a model that looks like this: from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) What is the best way to print first_name as "First name"?: Is it by setting verbose_name for every fields in the models.py? Or by setting label in the forms.py for every fields in each form? Or by not using a dynamic template and hardcode it in my … -
How do I load image from Django uploaded image binary file and use face_recognition(dlib)
This is the same question I posted here: https://github.com/ageitgey/face_recognition/issues/324 I am using face_recognition dlib module. I have a Django app that I want the user to upload the face image or pass it through web rest based API. The problem is how do I load this image ? In the current example is load_image_file("my_picture.jpg") but i believe this will take it from the file system. How do I load an image that is uploaded binary (without saving it to the filesystem) ? What I Did I have uploaded an image (jpg/png) through a browse button from Django web app just like this https://imgur.com/a/fVKuF From the code I will obtain the face_image_obj object and then try to pass it the face_locations function. However the face_image_obj is not compatible. In the example, I believe load_image_file is from the file system, but with web based api, we are to get it from an uploaded source. face_image_obj = employeefaceimageupload_form.cleaned_data["face_image"] logging.debug("face_image_obj type: %s" % type(face_image_obj)) face_location_unknown = face_recognition.face_locations(face_image_obj) face_recognition.face_locations will cause this exception: Exception Value: | Unsupported image type, must be 8bit gray or RGB image. i check the image type using this type(face_image_obj is <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> My environment: face_recognition version: face-recognition==1.0.0 face-recognition-models==0.3.0 Python version: … -
using Geodjango with oracle database
when working with GeoDjango i have a problem: when i make migrations then migrate new models the log said "no migrations to apply" and the oracle database still have no new table . my settings.py is DATABASES = { "default": { "ENGINE": "django.contrib.gis.db.backends.oracle", "NAME":, "USER":, "PASSWORD":, } } I need some help -
Django Appurl and Root url
I am not able to understand the difference between the Root URL and the App url and how to construct those. Its confusing when I need to use the Root url and App url. Example: When I need the extension of the website like www.test.com/users then I need to go for the app url? But what confusing is these extensions I can create in the Root url also. Please clarify. -
Django and ManyToMany fields
I have a database in mysql and I am setting up a django project. I have some entities with many-to-many relations, which are handled through association tables. With django, I have understood that I can use ManyToMany entity to achieve many-to-many relations BUT how do I do when the association table holds more information besides just the many-to-many relation? See the example below. CREATE TABLE `products` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` char(150) DEFAULT NULL ...) CREATE TABLE `pictures` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `filename` char(100) NOT NULL ... ) CREATE TABLE `products_pictures` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `fk_products_id` int(11) unsigned NOT NULL, `fk_pictures_id` int(11) unsigned NOT NULL, `priority` tinyint(4) unsigned DEFAULT NULL, `relation` varchar(25) DEFAULT 'same product family' ... ) -
Need a minimal Django file download example
I'm facing difficulty to download (the already uploaded) files as I am a newbie in django. Also I could not find a way to do that (the uploaded files are of different formats). May someone post a minimal but complete (Model, View, Template) example code to do so? -
Django with multiple Apps and reusing the same database tables
I am quite new to Django. Right now I am working on a prototype with ~30 database tables. I have understood that with Django you preferably want to have quite small Apps, with limited number of Models. I want to use the same Models (i.e. database tables) in several different Apps. What is the best practice to achieve this? I am using mysql. -
How to load block by ajax in backgroud?
:) I have tree structure in my template which created by Nestable2 plugin. I render tree structure with next html which you can see below. It works but render some heavy pages with a lot of data too slow. By default when user open the page tree is collapse. I show top level nodes first and then check if they have descendants. You can see it in html. The main load to database happens when I check all descendants of the node in this line: node.get_children. Question: Is it possible to load this part {% if node.get_children %} *** {% endif %} by ajax in backgroud when page is opened? I want to know your ideas, I would be grateful for examples. My aim is to speed up page loading. main.html: <ol class="dd-list"> {% for node in nodes %} {% include "tree_template.html" %} {% endfor %} </ol> tree_template.html: <li class="dd-item dd3-item" data-id="{{node.id}}"> <div class="dd-handle dd3-handle"></div> <div class="dd-content dd3-content">***</div> {% if node.get_children %} <ol class="dd-list"> {% for child in node.get_children %} {% with node=child template_name="tree_template.html" %} {% include template_name %} {% endwith %} {% endfor %} </ol> {% endif %} </li> -
How to replace data value(js) with a datatable value?
Python 3.6.3 django==1.11.3 bootstrap4 I am trying to create a bar chart with data retrieved from a datatable. how to map data(lables, data) values to datatable in a chart js file. Assuming that hard-coded data exists as a datatable, how do you write a js file? Please tell me how. html <div class="col-lg-6"> <div class="card bar-chart-example"> <div class="card-header d-flex align-items-center"> <h4>Bar Chart Example</h4> </div> <div class="card-body"> <canvas id="barChartExample"></canvas> </div> </div> </div> chart js var barChartExample = new Chart(BARCHARTEXMPLE, { type: 'bar', data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [ { label: "Data Set 1", backgroundColor: [ 'rgba(51, 179, 90, 0.6)', 'rgba(51, 179, 90, 0.6)', 'rgba(51, 179, 90, 0.6)', 'rgba(51, 179, 90, 0.6)', 'rgba(51, 179, 90, 0.6)', 'rgba(51, 179, 90, 0.6)', 'rgba(51, 179, 90, 0.6)' ], borderColor: [ 'rgba(51, 179, 90, 1)', 'rgba(51, 179, 90, 1)', 'rgba(51, 179, 90, 1)', 'rgba(51, 179, 90, 1)', 'rgba(51, 179, 90, 1)', 'rgba(51, 179, 90, 1)', 'rgba(51, 179, 90, 1)' ], borderWidth: 1, data: [65, 59, 80, 81, 56, 55, 40], } ] } }); -
How to install django in windows 10
I'm using anaconda interpreter, can you please tell me how to install django by creating conda environment in different drive (other than C drive). Thank you -
Reverse for Model with Slug in URL not working
I have a parts.html page that references the model Part, the page I am having issue with is the Part List view Generic Model view. The purpose of it is to lists all of the parts on a page and show the category next to it. Each part has a foreignkey "category". I am trying to create a Slug URL from the Part list view to the Category detail page, but I receive this error when I go to the partlistview page. I can access the Category page with portal/category/category where the second category at the end is a category in the database. django.urls.exceptions.NoReverseMatch: Reverse for 'category-detail' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['portal/category/(?P<slug>[-\\w]+)/$'] Views.py class PartDetailView(LoginRequiredMixin, generic.DetailView): model = Part template_name = 'portal/part.html' # Option - Specify your own template name/location class PartListView(LoginRequiredMixin, generic.ListView): model = Part #queryset = Part.objects.filter(is_active=True) #.prefetch_related('user') #hos paginate_by = 100 https://simpleisbetterthancomplex.com/tutorial/2017/03/13/how-to-create-infinite-scroll-with-django.html template_name = 'portal/parts.html' # Option - Specify your own template name/location context_object_name = 'part_list' #def get_queryset(self): #return Category.objects.all() def get_context_data(self, **kwargs): context = super(PartListView, self).get_context_data(**kwargs) context['category'] = Category.objects.all() return context class CategoryDetailView(LoginRequiredMixin, generic.DetailView): model = Category template_name = 'portal/category.html' # Option - Specify your own template name/location … -
You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path
I have gone through every other answer and cannot seem to get anything to work for me. I am following a tutorial and trying to push my master branch to heroku and get the error You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. I am using Django 2.0 and python 3.6.3. The full traceback: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 15, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect remote: handler(path, prefixed_path, storage) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 344, in copy_file remote: if not self.delete_file(path, prefixed_path, source_storage): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 250, in delete_file remote: if self.storage.exists(prefixed_path): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 308, in exists remote: return os.path.exists(self.path(name)) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 43, in path remote: raise ImproperlyConfigured("You're using the staticfiles app " remote: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app … -
Append query string if user logged in
Is there a way to add a query string such as ?preview to all URLs for a particular view in Django only if a user is logged in? The purpose of this is to bypass caching on cloudflare. -
django 2.0 - including urls file from an app to the root urls file
I'm interested in have for each app their own urls.py file and then, include them in the root urls.py file using the include django function like this include('myapp.urls'). So, in root urls.py it is like this: from django.url import include, path urlpatterns = [ path('folio/', include('folio.urls')) ] and now in the folio urls.py it is like the following which didn't find solution in the django url documentation: from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home') ] After some tryings all I get is page not found. What am I missing?