Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to handle an extremely big table in a search?
I'm looking for suggestions on how to go about handling the following use case scenario with python django framework, i'm also open to using javascript libraries/ajax. I'm working with pre-existing table/model called revenue_code with over 600 million rows of data. The user will need to search three fields within one search (code, description, room) and be able to select multiple search results similar to kendo controls multi select. I first started off by combining the codes in django-filters as shown below, but my application became unresponsive, after waiting 10-15 minutes i was able to view the search results but couldn't select anything. https://simpleisbetterthancomplex.com/tutorial/2016/11/28/how-to-filter-querysets-dynamically.html I've also tried to use kendo controls, select2, and chosen because i need the user to be able to select as many rev codes as they need upward to 10-20, but all gave the same unresponsive page when it attempted to load the data into the control/multi-select. Essentially what I'm looking for is something like this below, which allows the user to select multiple selections and will handle a massive amount of data without becoming unresponsive? Ideally i'd like to be able to query my search without displaying all the data. https://petercuret.com/add-ajax-to-django-without-writing-javascript/ Is Django framework meant to … -
Django: Reusable App Code
Can anyone share the reusable app one is supposed to get after completing the official Django tutorial? 2.0 would be ideal! I tried searching on Github but wasn't able to find working projects. Alternatively, can you perhaps recommend some other starter project templates written in Django? Thank you! -
Django - Create a User instance from another model that uses User as a OneToOne
I think an example will explain it better. Lets say I am making an application for various Libraries to show what books they have available. The site will have Users that are registered through the built-in user registration system and User model. These Users (think of it like library members) can visit the Libraries and browse and checkout the available books. The site will also allow Libraries to register themselves, and part of that registration is declaring a "Librarian," a person who controls what books are available in their particular Library. I want to create a Library Registration Form that takes the information of this Library and its Librarian and not only creates an instance of the Library model, but also an instance of the User model. The Librarian automatically becomes a User. This is my current models.py: class Library(models.Model): name = models.CharField(max_length=200) website = models.URLField() street = models.CharField(max_length=200) city = models.CharField(max_length=200) state_or_province = models.CharField(max_length=200) postal_code = models.CharField(max_length=200) date_registered = models.DateField(auto_now_add=True) librarian = models.OneToOneField(User, on_delete=models.CASCADE) @receiver(post_save, sender=Library) def create_user(sender, instance, created, **kwargs): if created: User.objects.create(user=instance) instance.user.save() I am currently lost as to how to build views.py and forms.py. I am not even sure that model is built correctly, since I … -
TypeError at /en/ Object of type '__proxy__' is not JSON serializable
I'm trying to implement a breadcrumb in my django project. To archieve that, I've created a mixin which is inherited by every view I have. Here is the code: class BreadcrumbMixin(object): index = False url_name = None verbose_name = None def breadcrumbUpdate(self, breadcrumb, new_value): for i in range(len(breadcrumb)): if breadcrumb[i]['url_name'] == new_value['url_name']: breadcrumb = breadcrumb[:i + 1] return breadcrumb breadcrumb.append(new_value) return breadcrumb def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) new_value = { 'url_name' : self.url_name, 'verbose_name' : self.verbose_name, 'url' : reverse_lazy(self.url_name, **kwargs) } if self.index: self.request.session['breadcrumb'] = [new_value,] else: self.request.session['breadcrumb'] = self.breadcrumbUpdate(self.request.session['breadcrumb'], new_value) return context The attributes index, url_name and verbose_name are set in each view that inherits it. For instance: class Index(BreadcrumbMixin, TemplateView): template_name = 'crud/index.html' index = True url_name = 'index' # Name argument used in urls.py verbose_name = _('Index') It basically use these informations to make a list of dicts, which is passed to the template using the session dictionary. In the template, it is being called like this: <div style="margin-left: 10px;"> {% for element in request.session.breadcrumb %} <a href="{{ element.url }}" class="breadcrumb"> {{ element.verbose_name }} </a> {% endfor %} </div> The problem is, it's giving me the error mentioned in the title. Here is the traceback: Environment: … -
How references fields that are foreignkey in another table
Documents models.py ERD-Restaurants python3.6.4, django 2.0 Hello django pals, I need some help. Only business_id is not generated automatically (user_id and dish_id are generated automatically by django API) This is the Rating class(Rating Table) in model.py class Rating(models.Model): business = models.? r1 dish = models.? r2 user = models.ForeignKey(User, on_delete=models.CASCADE, primary_key=True) rating = models.IntegerField() comment = models.TextField() How can I references r1 with Price.restaurant, r2 with Price.dish? and set these 2 fields as primary key so that the 3 fields (business, dish and user) can form a composite key. Is valid use the argument , primary_key=True in ForeignKey fields as I am using there? Because I need to set that fields as primary key too. -
How to access the a reverse relation of a reverse relation django
I am determined to try get all the other users that replied to the same comment as a given reply. I have come up with the following python, however I am concerned this will do more than one DB call. other_repliers = [other_reply.user for other_reply in my_reply.comment.replies.filter()] I'm looking for a one-db-call fix. The Psuedo-SQL logic would be something like: SELECT u.* FROM users AS u INNER JOIN replies AS r ON r.user = user.id WHERE r.comment = {my_reply.comment} AND r.user != {my_reply.user} Does anyone know a way that I can do the above SQL in a single query? -
"Invalid HTTP_HOST header" from unknown domain
I am using Nginx and Gunicorn to host a Django project. I need to secure this site, and as a test I set up Let's encrypt to an unused domain of mine. While tailing the Django access log, I noticed the following entry from time to time: Invalid HTTP_HOST header: 'aydinfatih.com'. You may need to add u'aydinfatih.com' to ALLOWED_HOSTS. This is an unknown domain to me, and while trying to access the domain (it got 400 response), I could se more of these log entries on my server. What is this? Is it related to my SSL-setup, and an indication that it's not secure? server { server_name example.com example.com; location /static/ { root /home/user/project/django-project; } location /media/ { root /home/user/project/django-project; } location / { include proxy_params; proxy_pass http://unix:/home/user/project/project.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot if ($scheme != "https") { return 301 https://$host$request_uri; } # managed by Certbot } server { listen 80; server_name my.server.ip.here example.com; return 301 https://example.com; } I added the following to my server block: if ($host !~* ^(example.com|www.example.com)$ ) { return …