Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
502 Bad getway error connect() to unix:/pathToProjectFolder/sample.sock failed (2: No such file or directory)
I am following this link to https://www.linode.com/docs/websites/nginx/deploy-django-applications-using-uwsgi-and-nginx-on-ubuntu-14-04 to host django application on nginx server. I followed all steps mention in link but it show error while browsing site :502 Bad gateway. I checked nginx error log file, it displays below error: 2017/03/04 07:09:21 [crit] 5131#0: *1 connect() to unix:/pathToMyProjectFolder/sample.sock failed (2: No such file or directory) while connecting to upstream, client: 127.0.0.1, server: localhost, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:/pathToMyProjectFolder/sample.sock:", host: "localhost:8087" And sample.sock file is not actually present in my project folder. I don't understand how this file will get created. -
Database Design for Company and Sub-Contractors and Product Management
I'm trying to wrap my head around the best way to design my database to facilitate the following: Company and Sub-Companies (sub-contractors): Master (creates) -> Company “A” Master (creates) -> Company “B” (creates) -> Company “C” Master (creates) -> Company “D” (creates) -> Company “F” (creates) -> Company “G” Company and Product Assignment: Master (Add Product) -> Show all products Master (assign products to top levels) -> Company “A”, Company “B” and Company ”D” Sub-Company Product Assignment (management): Company “B” (assign products only to sub-level) -> Company “C” Company “D” (assign products only to sub-level) -> Company “F” Company “F” (assign products only to sub-level) -> Company “G” However, if Company D removes a product from a sub-level, this will also remove from all sub-level products recursively. I hope this description makes sense. If you need any more info from me, please comment below. -
no such column: blog_post.title
I cant figure out what is wrong, I am getting the following error: {% extends "personal/header.html" %} {% block content %} {% for post in object_list %} {{ post.date|date:"Y-m-d" }} {{ post.title }} {% endfor %} {% endblock %} enter image description here -
Unexpected behavior using Bootstrap-Table and Javascript in Django (inline editable)
I'm using bootstrap-table with inline editable plugin to create a bootstrap table for a list of laptop. My goal was to apply changes to my csv file after users make changes to the table. I have created a javascript function below to send Ajax data to my Django server. // ajax to server $(function () { var target_elem; $( "#table" ).on("click" , 'a',function(e){ target_elem = $(e.target); }); $( "#table" ).on("click" , 'button',function(event){ var selected_item = getSelectedRow(); //this will return selected row object console.log(selected_item); $.ajax({ type: "post", url: '/update/', data: { 'item': JSON.stringify(selected_item) }, success: function (data) { alert('success'); } }); }); }); Below is the output from my console log (pcategory has been changed to Laptop2) However, when I try to get the data from Django. It gave me the output below, which (pcategory was not changed to Laptop2) {'webcam': 'WebCam', 'lannum': '2', 'condition': 'Refurbished', 'video2': 'GM204M [GeForce GTX 970M]', 'memorybanks': '8G 2133MHz/8G 2133MHz/', 'cpus': '1', 'customernotes': '', 'lanmodels': 'Killer E2400 Gigabit Ethernet Controller/WLAN QCA6174 802.11ac Wireless Network Adapter/', 'internalnotes': '', 'pline': 'Alienware', 'sku': 'LEN-LT-TPEdge-03BV001', 'cddvd': '', 'hddcapacity': '0.0G', 'coresthreads': '4 | 8', 'sound': 'Sound-Yes', 'pmodel': '15 R2', 'resolution': '1230x1000', 'ptype': 'Minitower', 'grade': 'GradeB:R2-Ready for Resale', 'touchscreen': 'Yes', 'hddqty': '0', … -
Selenium with geckodriver: assertion not working after getting browser instance
I am following TDD with Python book by Harry Percival, everything is set up correctly, but after getting some url through webdriver, assertion is not throwing error (it should throw error, browser title is "Welcome to Django" but I gave "To-Do" for assertion). Actually even if I put some wrong syntax after browser.get(...) it is working. Here is my code: from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') # some wrong syntax assert 'To-Do' in browser.title -
Iframe'd page in Django template can't find it's Javascript or CSS files, 404 error
In my views.py, I have one path render an html file: def interactive(request): if request.session.get('interactiveID') == None: t= get_template('blank-interactive.html') else: interactive_template= 'interactive-' + str(request.session['id']) + '/index.html' t= get_template(interactive_template) return HttpResponse(t.render()) So form.html has an <iframe> that requests /interactive, and request.session['id'] is set to 1. When the iframe requests /interactive, it loads interactive-1/index.html. The iframe loads the HTML from that page, but cannot get the JS file at interactive-1/scripts/main.js. When I check the terminal, I see this 404 error: GET /interactive/scripts/main.js. If it would just load /interactive-1/scripts/main.js, there would be no problem. But Django loads /interactive-1/index.html, but not /interactive-1/scripts/main.js. Same goes for the CSS and image assets, which are in CSS and image folders. What do I need to change in Django for it to correctly load the JS, CSS, images and other assets? -
django mongoengine and firebase user authentication?
I would like use part of firebase authentication (email, google, facebook, twitter) and join with my app make in mongoengine and django. I think connect firebase authentication with my app by token but i don't know make. When user logged with firebase in web, ios, android, I would like connect with my app by token or wherever.It's posible this ?. Help me. This is my authentication user in firebase, it's possible connect with any app by token or wherever and be secured. -
How can I track all SQL query timings and counts in Django?
I'd like to have a Django application record how much time each SQL query took. The first problem is that SQL queries differ, even when they originate from the same code. That can be solved by normalizing them, so that SELECT first_name, last_name FROM people WHERE NOW() - birth_date < interval '20' years; would become something like SELECT $ FROM people WHERE $ - birth_date < $; After getting that done, we could just log the normalized query and the query timing to a file, syslog or statsd (for statsd, I'd probably also use a hash of the query as a key, and keep an index of hash->query relations elsewhere). The bigger problem, however, is figuring out where that action can be performed. The best place for that I could find is this: https://github.com/django/django/blob/b5bacdea00c8ca980ff5885e15f7cd7b26b4dbb9/django/db/backends/util.py#L46 (note: we do use that ancient version of Django, but I'm fine with suggestions that are relevant only to newer versions). Ideally, I'd like to make this a Django extension, rather than modifying Django source code. Sounds like I can make another backend, inheriting from the one we currently use, and make its CursorWrapper's class execute method record the timing and counter. Is that the right … -
django- nginx: [emerg] open() "/etc/nginx/proxy_params" failed (2: No such file or directory) in /etc/nginx/sites-enabled/myproject:11
i try to deploy a django project with Nginx and Gunicorn with this tutorial. i did all to-dos but, when i create /etc/nginx/sites-available/myproject file with below code: server { listen 80; server_name server_domain_or_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/sammy/myproject/myproject.sock; } } and then run sudo nginx -t for find errors, i get this error: nginx: [emerg] open() "/etc/nginx/proxy_params" failed (2: No such file or directory) in /etc/nginx/sites-enabled/myproject:11 nginx: configuration file /etc/nginx/nginx.conf test failed what's the problem?? and how to solve it? tanx -
Why Django registration-redux custom form field not showing up in the form?
I'm trying to build a custom user registration form in Django which will do two things 1) use email field as username field 2) add an extra company_name field to show up in the form. I can successfully achieve first goal of using email as username but the second field is not showing up in the form when I do /accounts/register. Models.py: from django.db import models from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.utils.translation import ugettext_lazy as _ from django.conf import settings from phonenumber_field.modelfields import PhoneNumberField from django_countries.fields import CountryField from datetime import datetime class MyUserManager(BaseUserManager): def _create_user(self, email, password, company_name, **extra_fields): if not email: raise ValueError('The Email must be set') email = self.normalize_email(email) user = self.model(email=email, company_name=company_name, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, company_name, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, company_name, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null=True) date_joined = models.DateTimeField(default=datetime.now) company_name = models.CharField(max_length=300, null=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this site.'), ) is_active = models.BooleanField( _('active'), … -
Django query created object in tests not working
I have this code in a django test: stockitem_retailer = StockItem.objects.filter(retailer=test_retailer).first() test_subcategory = SubCategory.objects.create(category=test_category, name="outdoors") stockitem_retailer.product.subcategory = test_subcategory stockitem_retailer.save() pdb.set_trace() self.assertTrue(StockItem.objects.filter(product__subcategory=test_subcategory, retailer=test_retailer).exists()) I is simple, it gets a StockItem object with retailer=test_retailer, then id adds a created subcategory "outdoors" to the stockitem.product.subcategory relation. Why then the test does not pass? This is what I get from pdb: (Pdb) test_subcategory <SubCategory: outdoors> (Pdb) test_retailer <Retailer: mi-super> (Pdb) stockitem_retailer.product.subcategory <SubCategory: outdoors> (Pdb) stockitem_retailer.retailer <Retailer: mi-super> (Pdb) self.assertTrue(StockItem.objects.filter(product__subcategory=test_subcategory, retailer=test_retailer).exists()) *** AssertionError: False is not true I've being looking at this code for hours now, I can't se the bug. Please help. -
How to run django on my VPS server without port
I have a problem with lauching my django's app on my VPS server. I've added ip of the server to alllowed host and I can run it with the port, for example http://44.55.66.777:443/ and it works! But I would like to run my app without port, ( just http://44.55.66.777 ) How can I do this? Thank you for your help in advance -
Can you update a django model by passing object?
I want to update the classroom information in my django object by passing an object to it. Is this the correct way to go about this? if request.method == 'POST': data = request.POST # query to see if class relation exists with class_id and logged in user id class_ = UserClasses.objects.get(user=request.user, class_id=class_id) # if in class and teacher if class_ and request.user.is_staff: class_ = Class.objects.get(id=class_id) # pass data here and save context_dict = {"class": class_} return render(request, 'classes/view-settings.html', context_dict) -
Django DRF CSRF token missing - DRF deleted request.POST data?
I am using Django Rest's browsable API to POST using Session Authentication, and am getting CSRF token missing, even though it was supplied. I am seeking advice on configuring my ModelViewSet subclass so that this works. Here's my viewset: class TreeAPI(ModelViewSet): authentication_classes = (SessionAuthentication,) queryset = Tree.objects.get_roots() permission_classes = (IsAdminUser,) throttle_classes = (TreeThrottle,) serializer_class = TreeSerializer I am able to use the DRF Browsable API to GET this endpoint, but when I use it to POST to this endpoint, I get a 403 with the message CSRF token missing or incorrect. When I set a breakpoint in the constructor to rest_framework.request.Request, I can see that the request passed in contains the needed csrfmiddleware token: In Django Rest's Request class, POST is actually a property: @property def POST(self): if not _hasattr(self, '_data'): self._load_data_and_files() if is_form_media_type(self.content_type): # self.data is an empty QueryDict! return self.data return QueryDict('', encoding=self._request._encoding) request.POST no longer contains the csrfmiddlewaretoken key; it is stripped of all keys supplied with the form: As a result, the parameter passed to rest_framework.authentication.SessionAuthentication.enforce_csrf(request) which is then passed to django.middleware.csrf.CsrfViewMiddleware.process_view does not find the csrfmiddlewaretoken token: if request.method == "POST": request_csrf_token = request.POST.get('csrfmiddlewaretoken', '') What can I check? What are the possible sources of … -
Access a specific index input from interactive shell
When I execute django shell on the shell, I could get access interactive python. After executing many input, I would like to get access In [58] without using keyboard arrows. Is there an easy way to do such thing? P.S. I know the question how do you see the entire command history in interactive python? exists, but this not exactly what I want. I want to use the content of 'In [58]' later on during my work. -
Create bulk of model objects unit testing django
For testing the pagination behavior of a search view, I have to create a bulk of dummy objects. Is there a more elegant way to create a bulk of objects? create_question('First question.', -1, [Choice(choice_text='First choice.')]) create_question('Second question.', -1, [Choice(choice_text='First choice.')]) # ... -
Django Rest Framework: How to do custom pagination with non-orm model
I'm using Django Rest Framework 3 and I've run into some issues. I've gotten custom pagination working following this example and I've gotten a non-orm model working following this example. However, I cannot get custom pagination (or any pagination, for that matter) working on a non-orm model. The custom pagination is set to default in settings.py and it works on all my viewsets with models. The JSON output for endpoints with models includes the meta information and nests the objects within 'objects:'. The JSON output for endpoints without models just gives a list of the objects. My code is posted below. Any ideas on how to get this to work? Custom Pagination: from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response class CustomPagination(LimitOffsetPagination): def get_paginated_response(self, data): return Response({ 'meta': { 'limit': self.get_limit(self.request), 'next': self.get_next_link(), 'offset': self.get_offset(self.request), 'previous': self.get_previous_link(), 'total_count': self.count }, 'objects': data }) Object: class EMSEvent(object): def __init__(self, id, name, start, end): self.id = id self.name = name self.start = start self.end = end Serializer: class EMSEventSerializer(serializers.Serializer): id = serializers.IntegerField() name = serializers.CharField() start = serializers.CharField() end = serializers.CharField() class Meta: fields = '__all__' ViewSet: class EMSEventViewSet(viewsets.ViewSet): serializer_class = EMSEventSerializer(many=True) http_method_names = ['get'] def list(self, request): results = [] """ … -
Django Rest Framework module drf-chunked-upload - upload chunk does not work
I'm trying to send large files in chunks using Django Rest Framework module drf-chunked-upload. But following Typical Usage section and trying a variety of ways the past two days I can't find a way to do that. The first thing that I did was to make the ChunkedUpload model concrete to use it in my project and then, make and run migration associated with that. After that I set the url to make the requests for in urls.py: url(r'^uploadchunks/$', ChunkedUploadView.as_view()) Now, I can make the request to the API following the Typical Usage section in Github project home page, item 1: An initial PUT request is sent to the url linked to ChunkedUploadView (or any subclass) with the first chunk of the file. The name of the chunk file can be overriden in the view (class attribute field_name) Using httpie to make the request I run (the whole file has 32095676 bytes and I'm sendint 10000000 at time): http -a <username>:<password> -f PUT http://127.0.0.1:8000/uploadchunks/ file@~/<first_filechunk> filename='file' 'Content-Range: bytes 0-10000000/32095676' After that I get the error: django.urls.exceptions.NoReverseMatch: Reverse for 'chunkedupload-detail' with arguments '()' and keyword arguments '{'pk': UUID('a6b2f690-1653-4821-bcfd-b0edce60948a')}' not found. 0 pattern(s) tried: [] although the item 2 of Typical Usage … -
Adding robots.txt to django project
I'm having issues added a robots file to my django project. I have tried the three methods out there, but neither want to work. I believe this has something to do with this project using docker to serve files. In my latest attempt I tried to add the link to where the file should be in the nginx-app.config file # robots location /robots.txt { alias /home/docker/code/static/robots.txt; } and I have places the robot.txt at the root of the project and inside a few other folders I thought might grab it. Any help would be appreciated! -
Django: How to query objects where manytomany fields ALL exist in a list?
I would like to grab the programs where ALL the related prereq_courses exist in a provided list (called course_codes). So I do not want the programs that contain prereq_courses that do not exist in that list. How do I do that? models.py class Course(models.Model): name = models.CharField(max_length=255, blank=True) code = models.CharField(max_length=64, blank=True, unique=True) class Prerequisite(models.Model): program = models.ForeignKey('Program', on_delete=models.CASCADE) course = models.ForeignKey('Course', on_delete=models.CASCADE, null=True) group = models.IntegerField(null=True, default=0) class Program(models.Model): name = models.CharField(max_length=255) prereq_courses = models.ManyToManyField(Course, through=Prerequisite) I tried the following, but it also gave me programs that include prereq_courses that do not exist in the course_codes list. for code in course_codes: eligible_progs = eligible_progs.filter(prereq_courses__code=code) -
Django - How to show all fields of model with ListView and Template?
I'd like to create HTML template likes the followings. ・models.py class Client(Model): name = CharField(max_length=50) email = EmailField(max_length=100, verbose_name="E-mail") title = CharField(max_length=50) department = CharField(max_length=50) ・Data | Name | Mail | Title | Department | | John | john@mailaddress.com | engineer | development | | Bob | bob@mailaddress.com | engineer | development | | Sam | sam@mailaddress.com | engineer | development | ・views.py class myListView(, ListView): model = Client template_name = "template.html" ・template.html <table> <tbody> {% for item in object_list %} <tr> <td>{{ item }}</td> </tr> {% endfor %} <!--- table items end --> </tbody> </table> ・Expectation(table) | John | john@mailaddress.com | engineer | development | | Bob | bob@mailaddress.com | engineer | development | | Sam | sam@mailaddress.com | engineer | development | I don't want to write all keys in template file, because my product data has too many columns. Could you tell me how to make a template please ? -
Using nested Django transaction.atomic() to handle exceptions?
Django's docs say this about transaction.atomic() and exceptions: https://docs.djangoproject.com/en/1.10/topics/db/transactions/#django.db.transaction.atomic Avoid catching exceptions inside atomic! ... The correct way to catch database errors is around an atomic block as shown above. If necessary, add an extra atomic block for this purpose. This pattern has another advantage: it delimits explicitly which operations will be rolled back if an exception occurs. ... What does "If necessary, add an extra atomic block for this purpose." look like? Can I do this or does this cause "unexpected behavior"? valid = True errors = [] objects = MyModel.objects.all() try: with transaction.atomic(): for obj in objects: try: # Update and save obj here... except: errors.append("obj {} had errors".format(obj.pk)) valid = False if not valid: raise Exception('batch update failed.') except Exception as ex: # Handle it.. Do they mean to write it like this? If so, why is this different? valid = True errors = [] objects = MyModel.objects.all() try: with transaction.atomic(): for obj in objects: try: with transaction.atomic(): # Here's my 'extra atomic block' # Update and save obj here... except: errors.append("obj {} had errors".format(obj.pk)) valid = False if not valid: raise Exception('batch update failed.') except Exception as ex: # Handle it.. -
Nginx ssl configuration seems to forward to IP
Dear wonderful ladies and gents, Currently, I am trying to configure Nginx and Django to encrypt my traffic. I have gotten an ssl certificate and followed the instructions found on teh net, but to no avail. I checked with the domain service and all is well [no forwarding] on their end, and the ip matches the domain properly. Below is my default nginx as edited. [note I replaced my domain ip and keys with generic names] The site is forwarded properly, but it shows up as untrusted because it returns the domain. Thank you for your help!! server { server_name mydomain.com 104.196.165.3; listen 80; return 301 https://104.196.165.3$request_uri; } server { # the port your site will be served on listen 443; # the domain name it will serve for server_name mydomain.com 104.196.165.3; # substitute by your FQDN and machine's IP address charset utf-8; ssl on; ssl_certificate /etc/ssl/bleepbloop_cert_chain.crt; ssl_certificate_key /etc/ssl/bleepbloop.key; #Max upload size client_max_body_size 75M; # adjust to taste # Django media # location /media { # alias /var/www/path/to/your/project/media; # your Django project's media files #} location /assets { alias /home/myuser/djangoproj/website/static/; # your Django project's static files } # Finally, send all non-media requests to the Django server. location / { … -
Is it ok to catch and reraise an exception inside Django transaction.atomic()?
Django's docs say this about transaction.atomic() and exceptions: https://docs.djangoproject.com/en/1.10/topics/db/transactions/#django.db.transaction.atomic Avoid catching exceptions inside atomic! When exiting an atomic block, Django looks at whether it’s exited normally or with an exception to determine whether to commit or roll back. If you catch and handle exceptions inside an atomic block, you may hide from Django the fact that a problem has happened. This can result in unexpected behavior. This is mostly a concern for DatabaseError and its subclasses such as IntegrityError. After such an error, the transaction is broken and Django will perform a rollback at the end of the atomic block. If you attempt to run database queries before the rollback happens, Django will raise a TransactionManagementError. You may also encounter this behavior when an ORM-related signal handler raises an exception. The correct way to catch database errors is around an atomic block as shown above. If necessary, add an extra atomic block for this purpose. This pattern has another advantage: it delimits explicitly which operations will be rolled back if an exception occurs. If you catch exceptions raised by raw SQL queries, Django’s behavior is unspecified and database-dependent. Is it okay to do this or does this cause "unexpected behavior"? … -
No reverse match for 'zinnia_entry_add' after rewriting entry’s URL
Ok, i am running Django 1.10.6, Django-cms 3.4.2, Django-blog-zinnia 0.18.1 and cmsplugin-zinnia==0.8.1 (downloaded from github fork, where django 1.10 compatability is implemented) I'm stuck with this problem for too long and by brain is melting I've done everything like the manual says I created a custom app zinnia_integration in my project: zinnia_integration/models.py from django.db import models from zinnia.models_bases.entry import AbstractEntry class EntryWithNewUrl(AbstractEntry): """Entry with '/blog/<slug>/' URL""" @models.permalink def get_absolute_url(self): return ('zinnia:entry_detail', (), {'slug': self.slug}) class Meta(AbstractEntry.Meta): abstract = True zinnia_integration/views.py from django.views.generic.detail import DetailView from zinnia.models.entry import Entry from zinnia.views.mixins.entry_preview import EntryPreviewMixin from zinnia.views.mixins.entry_protection import EntryProtectionMixin class EntryDetail(EntryPreviewMixin, EntryProtectionMixin, DetailView): queryset = Entry.published.on_site() template_name_field = 'template' zinnia_integration/urls.py from django.conf.urls import url from zinnia_integration.views import EntryDetail urlpatterns = [ url(r'^(?P<slug>[-\w]+)/$', EntryDetail.as_view(), name='entry_detail'), ] And I include this urlpatterns in my project's urls.py blog_urls = ([ ... url(r'^blog/comments/', include('zinnia.urls.comments')), url(r'^blog/', include('zinnia_integration.urls')), #url(r'^blog/', include('zinnia.urls.entries')), url(r'^blog/', include('zinnia.urls.archives')), .... ], 'zinnia') urlpatterns = [ ... url(r'^', include(blog_urls)), ... ] and in my settings.py ZINNIA_ENTRY_BASE_MODEL = 'zinnia_integration.models.EntryWithNewUrl' After that, I restart my server and get the NoReverseMatch at / Reverse for 'zinnia_entry_add' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Even if I don't change anything in subclass model (EntryWithNewUrl) I …