Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
best way for deployment of django-channels in real server
I have a website written with django and use django-channels. I can test this with "manage.py runserver" and it's work fine. But in real world you can't use this method to run your website. Apache and Nginx are not serving django-channels (Websocket) and you should use alongside server s.a. Daphne but it's very complicated to config this approach. and i can do this for one time and forget that :( I'm locking for the best approach to deployment django-channels app in real world. thanks. -
Can't heroku open
When I do heroku open I have "application error" in my browser so I check my logs with "heroku logs --tail --app " and get the following: 2017-07-29T11:06:06.000000+00:00 app[api]: Build succeeded 2017-07-29T11:06:41.268744+00:00 heroku[web.1]: Starting process with command `gunicorn harrispierceDjango.wsgi --log-file -` 2017-07-29T11:06:43.032101+00:00 app[web.1]: bash: gunicorn: command not found ... 2017-07-29T11:20:08.108114+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=harrispierce.herokuapp.com request_id=6617f7a2-6599-41aa-9708-846828430bad fwd="82.229.220.87" dyno= connect= service= status=503 bytes= protocol=https I followed the step by step procedure but never did anything related to the databases: could it be related? Thanks, -
Pyton/django LDAP authentication fails with invalid requirement
I have a problem with implementing ldap in ralph3 application written in python/django. I've installed all the prerequisities and successfully connected to ldap server with ldapsearch -H ldap://10.202.206.30 -b dc=bod,dc=local -x but when I try to follow the steps in this official tutorial and create prod_ldap.txt (template): import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType AUTH_LDAP_SERVER_URI = "ldap://activedirectory.domain:389" AUTH_LDAP_BIND_DN = "secret" AUTH_LDAP_BIND_PASSWORD = "secret" AUTH_LDAP_PROTOCOL_VERSION = 3 AUTH_LDAP_USER_USERNAME_ATTR = "sAMAccountName" AUTH_LDAP_USER_SEARCH_BASE = "DC=allegrogroup,DC=internal" AUTH_LDAP_USER_SEARCH_FILTER = '(&(objectClass=*)({0}=%(user)s))'.format( AUTH_LDAP_USER_USERNAME_ATTR) AUTH_LDAP_USER_SEARCH = LDAPSearch(AUTH_LDAP_USER_SEARCH_BASE, ldap.SCOPE_SUBTREE, AUTH_LDAP_USER_SEARCH_FILTER) AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", "company": "company", "manager": "manager", "department": "department", "employee_id": "employeeID", "location": "officeName", "country": "ISO-country-code", } and try to install it with pip: root@ubuntur:/home/marcel/ralph3# pip install -r requirements/prod_ldap.txt: I get this error: Invalid requirement: 'import ldap' Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 82, in __init__ req = Requirement(req) File "/usr/local/lib/python2.7/dist- packages/pip/_vendor/packaging/requirements.py", line 96, in __init__ requirement_string[e.loc:e.loc + 8])) InvalidRequirement: Invalid requirement, parse error at "u'ldap'" I also tried to delete all the lines in prod_ldap.txt except these two: import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType and the error was the same, so I think the problem is with the import of ldap, not with the settings. OS is Ubuntu 14.04 64 … -
Django models: Is object descendant of another object?
I have a model Category. Category can have one supercategory and multiple subcategories - like tree structure. All of them are Category objects. I'm trying to create a method which tells me if self is a descendant of given category. For now, it can say if it's a child but I want to detect grandchild, grandgrandchild etc. too. Do you know how to make it work? Is there some built-in tool for this? class Category(models.Model): name = models.CharField(max_length=1000) url = models.URLField(max_length=1000) supercategory = models.ForeignKey('Category',null=True,blank=True) def is_subcategory(self,category): if self.supercategory == category: return True def __unicode__(self): return self.name -
gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' django heroku
How to run django app in heroku? I trying run in heroku console gunicorn xxx:application 0.0.0.0:8000 error: ModuleNotFoundError: No module named xxx In Procfile (path app/xxx/xxx/wsgi.py) web: gunicorn xxx.wsgi --pythonpath ./xxx --log-file - -
how to create a date that doesn't change on a Django webpage
I created a webpage in Django that shows a list of items from a database. I would like to create a feature where when a user first generates that page, the current date (not time) appears on the page. The hard part is that when the user shares a link to that page on social media or wherever, the original date should remain unchanged. In other words, it should not change each time a subsequent user views the page through the link shared by the first user. The date is only created once when the first user generates the page. The purpose is to show subsequent viewers of that page all the relevant database items as of the date the first user accessed them. But then I will also provide information about the number of additional relevant entries that have been made to the database since the date the first user accessed them. Subsequent users would then have the option of going to a new page that shows all database items as of today. How can I implement this? -
Store results of django databse textfield in a string list
I have a django model that contains a textfield with a large amount of text. I would like to be able to query the database for this textfield and store the results in a string list. How can I do this? something like... views.py: queryset = Words.object.filter(id='1') wordArray = [] wordArray = queryset.split() # obviously this doesn't work -
Angular 2 Error while fetching data from Django Rest API
I'm new to Angular and I'm creating a test Application to accelerate my understanding of the topic. Recently I encountered a challenge to integrate Angular2(FrontEnd) with Django(Backend) by fetching the data using REST APIs. File: library.service.ts import 'rxjs/add/operator/map'; import { Observable } from 'rxjs/Rx'; import { Injectable } from '@angular/core'; import { Headers, Http } from '@angular/http'; // Project Modules import { Library } from '../models'; @Injectable() export class LibraryService { private librariesUrl = 'http://127.0.0.1:8000/api/library/create-library/'; constructor(private http: Http) { } private headers = new Headers({'Content-Type': 'application/json'}); private extractData(res: Response) { return res.json(); } private handleError (error: any) { return Observable.throw(error.message || 'Server error'); } getAll(): Observable<Library[]> { return this.http.get(this.librariesUrl, {headers: this.headers}) .map((res) => this.extractData(res.json())).catch((err) => this.handleError(err)); } } File: libraries.component.ts import { Component, OnInit} from '@angular/core'; import {HttpClient} from '@angular/common/http'; // Project Modules import { Library } from '../models'; import { LibraryService } from './library.service'; @Component({ selector: 'app-libraries', templateUrl: './libraries.component.html', styleUrls: ['./libraries.component.css'], }) export class LibrariesComponent implements OnInit { libraries: Library[]; personalLibraries: Library[]; collaborativeLibraries: Library[]; constructor(private libraryService: LibraryService, private http: HttpClient) { } ngOnInit(): void { /*this.http.get('http://127.0.0.1:8000/api/library/create-library/').subscribe((data: Library[]) => { console.log(data); this.personalLibraries = data; });*/ this.libraryService.getAll().subscribe(response => this.personalLibraries = response); } } JSON I'm Expecting [ { "slug": "tech-stack", "title": … -
Django 1.11 not recognising Foreign Key model assignments
I am having an issue with 2 Foreign Key assignments in my django model. See models.py below: from django.db import models from django.contrib.auth.models import User class userData(models.Model): user = models.ForeignKey(User) house = models.CharField(max_length=100) address = models.CharField(max_length=100, blank=True, null=True) street = models.CharField(max_length=150) state = models.CharField(max_length=100) postcode = models.CharField(max_length=20) country = models.CharField(max_length=100) telephone = models.CharField(max_length=20) subscription = models.IntegerField(default=0) active = models.IntegerField(default=0) class area(models.Model): area_name = models.CharField(max_length=100) longitude = models.CharField(max_length=100) latitude = models.CharField(max_length=100) class country(models.Model): area_name = models.CharField(max_length=100) longitude = models.CharField(max_length=100) latitude = models.CharField(max_length=100) class city(models.Model): area_name = models.CharField(max_length=100) longitude = models.CharField(max_length=100) latitude = models.CharField(max_length=100) class foodType(models.Model): food_type_name = models.CharField(max_length=100) class restaurant(models.Model): restaurant_name = models.CharField(max_length=100) food_type = models.ForeignKey(foodType) area = models.ForeignKey(area) country = models.ForeignKey(country) city = models.ForeignKey(city) date_added = models.DateField() main_image = models.ImageField(blank=True, null=True) website = models.URLField(blank=True, null=True) summary = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True) featured = models.IntegerField(default=0) class restaurantFeature(models.Model): feature_name = models.CharField(max_length=100) restaurant_id = models.ForeignKey(restaurant) Django Foreign Key not working correctly The image shows the Country and City, not showing correctly, like the FoodType and Area does. Theses show with the + buttons for adding, the mysql database is showing the key next to the fields. I have also tried renaming country and City adding Location after, thinking it could be … -
Get all the related object based on the models filter query
Trying to get all the list of loan along with the related its addresses linked to that particular loan. Models: class LoanDetail(models.Model): job_no = models.AutoField('Job No', primary_key=True) loan_account_no = models.CharField('Loan account No', blank=True, max_length=128) job_status = models.IntegerField('Job Status', choices=JOB_STATUS, default=1, db_index=True) applicant_type = models.IntegerField('Applicant type', choices=APPLICANT_TYPE, default=1, db_index=True) customer_name = models.CharField('Customer Name', max_length=128) class LoanUserAddress(models.Model): loan = models.ForeignKey(LoanDetail, on_delete=models.CASCADE, related_name="loanuser") address_type = models.ForeignKey(AddressType) house_name = models.CharField('House/Flat/Name', max_length=128) street = models.CharField('Street', max_length=128) area = models.CharField('Area/Location', max_length=128) views: class SearchLoan(APIView, ResponseViewMixin): def get(self, request, *args, **kwargs): loan = kwargs['loan']; address = LoanDetail.objects.filter(loan_account_no__in=[loan]) This is returning only the loan details how can I get all the Address along with the loandetails. -
Ajax Post Request Error using django 1.10.5
Over the last week or so I have been struggling to successfully implement a jQuery ajax request to pass data from a javascript function within my annualgoals.html to a django view in order to save data to my database. Currently I am just trying to test the data transfer by printing the data on the django end. I have already checked out the following threads but cannot see any that show the same error as I can see (I am almost certainly missing something obvious). Forbidden (CSRF token missing or incorrect) Django error "CSRF token missing or incorrect" while post parameter via AJAX in Django While a missing CSRF token was my first problem, the answers on StackOverflow and the django docs do a good job of explaining what must be done to ensure the csrf token is included. However, when following the recommended steps I receive the following django error: response.set_cookie(settings.CSRF_COOKIE_NAME, AttributeError: 'NoneType' object has no attribute 'set_cookie' My code is as follows: annualgoals.html function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this … -
Suggest me some good python packages [on hold]
I am developing an analytics application for which the data has been stored in a database which I am yet to decide among sql and no-sql choices that are available. Note: The application has been started in Django. -
How to handle a Django serialized JSON object array in Jquery?
{comment: "[{"model": "writers_block.comment", "pk": 49, "fields": {"user": 43, "rant": "dsf"}}]"} I have an object with a serialized JSON array. This is Django model instance serialised by the django serializer. How do I go about accessing this in jQuery? -
Django SuspiciousOperation after upgrade to 1.10
Recently I have upgraded my apps from 1.8 to 1.10 and now I get flooded by this error: Exception Type: SuspiciousOperation at << VARIOUS_PAGES >> Exception Value: The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. I can't figure out why this happen but it seems that the session expires prematurely for some strange reason. -
How can i have a django custom authentication with out using user model. i have two apps in my project
i am totally new to django. i am a java developer. Recently i came to use of django. i need to know how do custom authentication without using user model. and i have two apps in my project. so i need to two custom authentications and which should be i use two different tables or models. and also need to know how can i give permissions to them. i need clear and concept base explanation in step by step process. please welcome me to python family. Thank you in advance. -
Check if current URL pattern exist in another language in Django
I'm trying to start of my new website in Django with a lot of settings which down the road will be tougher to implement. One of these things is website internationalization, but also url pattern internationalization. What I am trying to achieve is having urls like this: www.example.com/news [en] [news] www.example.com/en/news [en] [news] www.example.com/no/nyheter [no] [news] www.example.com/en/top-articles [en] [top articles] and on every page I visit, I want the website navigation to have a dropdown menu, which contains website languages, and which language is currently selected. Similar to this: <ul class="dropdown"> <li><a href="/en/news" hreflang="en" class="active">English</a></li> <li><a href="/no/nyheter" hreflang="no">Norsk</a></li> </ul> Now as for changing to another language, is there any way to see if the current page exists in the language the users can pick from? If the current page does not exist in the language of choice, I want the user to be returned to the frontpage of the selected language. So the dropdown would look like this: <ul class="dropdown"> <li><a href="/en/top-articles" hreflang="en" class="active">English</a></li> <li><a href="/no" hreflang="no">Norsk</a></li> </ul> -
Handling votes through forms
I installed django-vote which has a simple API: review = ArticleReview.objects.get(pk=1) # Up vote to the object review.votes.up(user_id) # Down vote to the object review.votes.down(user_id) I've got a Car page with multiple reviews that I wish to vote. I tried: <form action="{% url 'reviews:review-vote' review.id %}" method="GET"> <button type="submit" name="vote-up"></button> <button type="submit" name="vote-down"></button> </form> URL: url(r'^(?P<review_id>\d+)/vote/$', views.review_vote, name="review-vote"), View: def review_vote(request, review_id): if request.GET.get("vote-up"): review = Review.objects.get(id=review_id) review.votes.up(request.user.id) return redirect("car", {"make": review.car.make, "years": review.car.years}) This doesn't execute the vote and doesn't redirect to the Car page. I'd like to implement the voting API in my template, without reloading the page if possible. Any suggestion or feedback will be welcomed and greatly appreciated. Thank you. -
Django staticfiles 404 in Deploy to Digital Ocean
The server is launched on Ubuntu 16.04.2 x64 on the local server all works with the same settings as only started here, can not find them! settings STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), #'/var/www/static/', ] STATIC_ROOT = os.path.join(BASE_DIR, "static_cdn") MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media_cdn") urls from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^chart/', include("charts.urls", namespace='charts')), url(r'^comments/', include("comments.urls", namespace='comments')), url(r'^im/', include("messenger.urls", namespace='im')), url(r'^accounts/', include("accounts.urls", namespace='accounts')), url(r'^series/', include("serials.urls", namespace='series')), url(r'^', include("serials.urls", namespace='homeview')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) on local server everything works great, but when i launch it in live staticfiles not found > [29/Jul/2017 07:54:38] "GET /static/css/bootstrap.min.css HTTP/1.1" > 404 102 [29/Jul/2017 07:54:38] "GET /static/js/bootstrap.min.js > HTTP/1.1" 404 100 [29/Jul/2017 07:54:38] "GET > /static/min_css/base.min.css HTTP/1.1" 404 101 [29/Jul/2017 07:54:38] > "GET /static/js/Chart.min.js HTTP/1.1" 404 96 [29/Jul/2017 07:54:38] > "GET /static/js/smooth-scroll.js HTTP/1.1" 404 100 [29/Jul/2017 > 07:54:38] "GET /static/js/script.js HTTP/1.1" 404 93 [29/Jul/2017 > 07:54:39] "GET /static/js/bootstrap.min.js HTTP/1.1" 404 100 > [29/Jul/2017 07:54:39] "GET /static/js/Chart.min.js HTTP/1.1" 404 96 > [29/Jul/2017 07:54:39] "GET /static/js/smooth-scroll.js HTTP/1.1" 404 > 100 [29/Jul/2017 07:54:39] "GET /static/js/script.js HTTP/1.1" 404 93 -
Django (drf) dynamic permissions from BasePermission
I want to have easy way to check if somebody is owner or admin of post, proposal and so on he's trying to edit \ delete. So, every time I use IsAuthenticated permission and in the method of ModelViewSet I get instance and check if instance.author or sometimes instance.owner is the user who requested it (request.user == instance.owner on some objects it's request.user == instance.author). Question The main question is: how can I create permission class that can check this kind of ownership with dynamic user attribute name on instance? One of mine solutions (not the best, i think) I've created function that take user attribute instance name returns permission class: def is_owner_or_admin_permission_factory(owner_prop_name): class IsOwnerOrAdmin(BasePermission): def has_permission(self, request, view, *args, **kwargs): instance = view.get_object() try: owner = getattr(instance, owner_prop_name) except AttributeError: return False return ( request.user and request.user.id and (owner == request.user or request.user.is_staff) ) return IsOwnerOrAdmin -
Django: redirect user two pages back
I have a list of multiple objects from my database (named "plp's"), arranged in a table. Next to each "plp" element I have a button "Edit" to modify that particular entry. Next, I redirect the user to a new url, where I pass the id of that "plp", and show the form to edit it, with a "save" button. After pressing the "save", which is request.POST, I want to redirect the user back to the first url, with the list of all the "plp" objects in one list. That means to the site, where he first pressed "Edit". Can I somehow save the url of where the "Edit" was clicked, and pass it to my views.py? Thank you -
django filter with two relativity attributes to each other
in Django i want to filter one model with two relativity attribute to each other? model.objaect.filter(some__model__attribute<another__model__attribute)?? Is there a way to do this? -
Django couldn't run in xampp apache in port 80 - ImportError: cannot import name signals
I am trying to run django in apache xampp using mod_wsgi. This is the closest I have reached. Django project structure in c:/xampp/envs/myproject - where manage.py is located. Setting path c:/xampp/envs/myproject/myproject I created a folder in virtualenv folder named apache and added two files. wsgi.conf listen 80 <VirtualHost *:80> #WSGIPythonPath C:/xampp/htdocs/envs/Lib/site-packages #WSGIPythonPath "C:/xampp/htdocs/envs/Lib/site-packages" Alias /static/ c:/xampp/htdocs/envs/myproject/myapp/static/ WSGIScriptAlias / "c:/xampp/htdocs/envs/apache/myproject.wsgi" #WSGIPythonHome "C:/xampp/htdocs/envs" DocumentRoot "c:/xampp/htdocs/envs/myproject" ServerName localhost <Directory "c:/xampp/htdocs/envs/apache"> Allow from all </Directory> </VirtualHost> myproject.wsgi import os, sys sys.path.append('c:/xampp/htdocs/envs/myproject') sys.path.append('C:/xampp/htdocs/envs/myproject/myproject') sys.path.append('C:/xampp/htdocs/envs/Lib/site-packages') venv_path = "C:/xampp/htdocs/envs" activate_this = os.path.join(venv_path, "C:/xampp/htdocs/envs/Scripts/activate_this.py") execfile(activate_this, dict(__file__=activate_this)) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() In apache/conf/httpd.conf I added the following. LoadModule wsgi_module modules/mod_wsgi.so Include C:/xampp/htdocs/envs/apache/wsgi.conf I have two problems. I couldn't access other applications in htdocs by typing localhost/my_other_web_app Import error. I got the following error in apache/logs/error.log ImportError: cannot import name signals mod_wsgi (pid=8672): Target WSGI script 'C:/xampp/htdocs/envs/apache/myproject.wsgi' cannot be loaded as Python module. mod_wsgi (pid=8672): Exception occurred processing WSGI script 'C:/xampp/htdocs/envs/apache/myproject.wsgi'. Traceback (most recent call last): File "C:/xampp/htdocs/envs/apache/myproject.wsgi", line 11, in <module> from django.core.wsgi import get_wsgi_application File "C:/xampp/htdocs/envs/Lib/site-packages\\django\\core\\wsgi.py", line 2, in <module> from django.core.handlers.wsgi import WSGIHandler File "C:/xampp/htdocs/envs/Lib/site-packages\\django\\core\\handlers\\wsgi.py", line 8, in <module> from django import http File "C:/xampp/htdocs/envs/Lib/site-packages\\django\\http\\__init__.py", line 5, in <module> from django.http.response import … -
Django Update Multiple Object error
i found some problem when i try to update multiple object in my models. here is my models: class NumberSequence(models.Model): code = models.CharField(max_length=12) name = models.CharField(max_length=60) prefix = models.CharField(max_length=3) length = models.IntegerField() last = models.IntegerField(verbose_name='Last Number Used') def getNumberSequence(): ns = NumberSequence.objects.filter(code='REQ') letter = ns[0].prefix lastNumber = ns[0].last+1 l = '{0}-{1:0'+str(ns[0].length)+'d}' for num in ns: num.last = lastNumber num.save() return l.format(letter,lastNumber+1) class Requisitions(models.Model): number = models.CharField(max_length=20, default=getNumberSequence()) transDate = models.DateField(verbose_name='Date') businessUnit = models.ForeignKey(BusinessUnit, verbose_name='Unit') division = models.ForeignKey(Division, verbose_name='Division') remarks = models.TextField status = models.IntegerField(verbose_name='Status') when i create new record in Requisition, the table Number Sequence does not update. but if i restart the service, the number sequence table updated automatically. what's happened with my code? any suggestion, please.. -
Changing database structure of Django in server
When we work with Django in local environment, we change the structure of the Data Base using Command Prompt through migration. But for using Django in server, i don't now how can i apply such changes? How can i type commands to change Data Base structure? Is it a good way to upload site files every time that i do some change again. -
Decoding non standard characters to UTF 8 in Python
I have a program that takes in byte-encoded text via a webhook in Django (written in Python). I have decoding from byte -> utf-8 working for normal letters, but it breaks when an apostrophe ( ' ) is sent in. I have this written to decode the text: encoded = request.body decoded = parse_qs(encoded) body = decoded[b'body'][0].decode("utf-8") And this is the error: UnicodeEncodeError: 'ascii' codec can't encode character '\u2019' in position 5: ordinal not in range(128) I'd like for it to successfully decode apostrophes. I'm also concerned it might break if an emoji is sent in, so I'd like to be able to escape emoji and random chars like ∫, but still preserve the real words in the message.