Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django + nginx + uwsgi how to use one domain to build multiple application?
My question is how can I use one domain (mydomain.com) to build multiple django server? This is my nginx.conf, upstream django_myproject { server unix:///home/frank/myproject/haunyu.sock; # for a file socket } server { listen 80; server_name mydomain.com; # This is my ow charset utf-8; client_max_body_size 75M; # adjust to taste # Django media location /media { alias /home/frank/myproject/media; } location /static { alias /home/frank/myproject/static; } location / { uwsgi_pass django_myproject; include /home/frank/myproject/uwsgi_params; # uwsgi_read_timeout 600; } } I try to let location "/" replace to location "/first_app" like this location /frist_app { uwsgi_pass django_myproject; include /home/frank/myproject/uwsgi_params; # uwsgi_read_timeout 600; } } Then I try to type domain/frist_app to browser, I got 404, My uwsgi also has no contact message. -
Why is Django connection.cursor query failing?
I am getting the following error message when trying to execute a cursor query against a SQLite3 database: My code is as follows: qry = ('select balancer_security.id, balancer_security.name, balancer_security.symbol, ' 'balancer_securityprice.at_dt, balancer_securityprice.price, balancer_securityprice.notes ' 'from balancer_security LEFT OUTER JOIN balancer_securityprice ' 'ON (balancer_security.id = balancer_securityprice.security_id ' 'AND balancer_securityprice.at_dt="?") ' # 'AND balancer_securityprice.at_dt="%s") ' 'ORDER BY balancer_security.name') from django.db import connection cursor = connection.cursor() cursor.execute(qry, [date]) solution = cursor.fetchall() The error occurs on the cursor.execute line. date is a string containing the value 2017-10-05 Also, is the parameter put into the query within django or is it passed to SQLite (i.e. should my parameter placeholder be %s or ?)? Thanks! -
You may need to add 'www.example.com' to ALLOWED_HOSTS (but it is there)
As title shows, I get the You may need to add 'www.example.com' to ALLOWED_HOSTS ... (but it is there) Trying another approach, I simply put ALLOWED_HOSTS = ['*'] which if I am not mistaken allows any host, and should solve the issue for all hosts, but same error is thrown. Is there any other common cause responsible for this that I should check? The only other possible issues I can think of: Domain propagation is still happening since its a new domain (though I can't fathom how it would affect this, since the website is reached) I am using the same app (webfaction) for two sites. Is it favoring one domain over the other? Out of ideas beyond that. Any suggestions? -
Django MPTT Filter Only if No Children Exist
So I am using MPTT for a Category model in Django, and I was wondering if there is a way to filter a Category if there is no child. models.py: class Category(MPTTModel, TimeStampedModel): title = models.CharField(max_length=75) parent = TreeForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL, related_name='children', db_index=True) Categories example in DB: Games > Nintendo > Nintendo 64 Games > Microsoft > Xbox One I want to be able to run a command like this: Category.objects.all().has_no_children() Hoping that it would return [Nintendo 64, Xbox One] -
Django: I have a Profile model, and I want the slug for the profile detail page to be username, which is stored in User model
I'm creating a website where every User has an associated Profile instance, because I want the User model to only handle authentication-related user functions and the Profile model to handle everything else (such as user-uploaded images, etc.) Profile has a User OneToOneField. However, I want to be able to access each profile's detail page using the url pattern site/profile/[username]/. This is impossible without storing the username in both the User and the Profile models, since the slug_field for the Profile DetailView has to be a primary key of Profile, and the username is a field of User. Is there any way to do this without storing the username in two different places? -
possible to group urlpatterns of the same app?django
I know that in each app, we can use our own urlpatterns and include it in the main project / app using include. I am wondering if an app have a few different urls, is there a way to group it? for example urlpatterns = [ url(r'^user/$', hello.asView(), url(r'^user/hello/$', hello.asView(), url(r'^user/there/$', hello.asView(), url(r'^user/here/$', hello.asView(), url(r'^user/that/$', hello.asView(), url(r'^user/mini/$', hello.asView(), url(r'^user/max/$', hello.asView(), url(r'^bb/$', hello.asView(), url(r'^bb/hello/$', hello.asView(), url(r'^bb/there/$', hello.asView(), url(r'^bb/here/$', hello.asView(), url(r'^bb/that/$', hello.asView(), url(r'^bb/mini/$', hello.asView(), url(r'^bb/max/$', hello.asView(), ] please ignore all the hello.asView() but I am wondering if there's a way to group all the user and bb so if there are more url, I don't need to keep on typing user or bb again? thanks in advance for any help. -
Django updating model has broken the admin
I updated my models class called Account. I have removed a field called "user" Removed this line: user = models.ForeignKey(User, unique=True) I then ran makemigration and then migrate successfully. When I goto: http://127.0.0.1:8000/admin/reports/account/ I get the below error message: Account' object has no attribute 'user' My question is, how do I update the admin code easily when making structural changes to my models/migration? -
why isn't celery task asyncing while loading page?
the task runs but my page waits for it to finish the task then loads the page. Pretty much defeats the purpose of async plus I am getting a timedout on heroku--separate issue. So, I am calling the task in views.py and sending it to tasks.py. Not sure what else I need, but logically looks right to me? settings.py BROKER_URL=['amqp://guest@localhost//','cloudamqp'] BROKER_POOL_LIMIT = 1 BROKER_CONNECTION_MAX_RETRIES = None CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' CELERY_ACCEPT_CONTENT = 'pickle', CELERY_TASK_SERIALIZER = 'json', CELERY_RESULT_SERIALIZER = 'json' CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend' CELERY_ALWAYS_EAGER = True views.py def my_page(request): #do something #this is at the end, right before return. #If I put it in the middle, it runs in sequence. So I don't see anything after this until the task is done. get_data.delay(args) return (request, 'home.html') tasks.py from __future__ import absolute_import, unicode_literals import requests import json import time import sys import os import random from os import path from celery import Celery sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) ) from lib import myfiles from django.db import models from .models import mymodels import django django.setup() @task(name="get_myfunction") def get_data(user, items): #runs a bunch of things #saves data #all this and page spinner on the browser tab just keeps spinning until its done -
How to get a list of tuples from a Django RawQuerySet?
I'm doing a complex query with raw SQL within django to solve some annotation issues. The actual query has many left joins that have been converted to subqueries in order to get around a major bug in Django. https://code.djangoproject.com/ticket/10060 Given fields = ['shift__adminFee', 'shift__rosterSlot__adminFee', 'shift__taxi__rosterGroup__adminFee', 'shift__driver__adminFee'] query = `''select table.id, "table_shift"."adminFee" , "table_rosterslot"."adminFee" , "table_rostergroup"."adminFee" , "table_driver"."adminFee" from table left join ( select table_id, sum(amount) amount_sum from related_table group by table_id ) related_table on table.id = related_table.table_id ... ( more inner joins and tables to support the above fields ) ''' rawQuerySet = Table.objects.raw(q) which returns a RawQuerySet. The RawQuerySet works well ... and it populates the related models as well as giving the correct annotated results. The RawQuerySet however doesn't support returning a list of tuples. I've looked through the source file which locally in the project is 'env/lib/python2.7/site-packages/django/db/models/query.py' but I don't understand it yet and I had a result to produce. So instead of doing results_as_list_of_tuples = query.values_list(*fields) I did something like results_as_list_of_tuples = [] for result in query: shift = result.shift eventSchedule = shift.eventSchedule rosterSlot = shift.rosterSlot taxi = shift.taxi rosterGroup = taxi.rosterGroup data = [] ... # the following is one line. I broke it up … -
What's the advantage of using namespace?
General I read about namespace and tried it, but I don't get the point: What's the advantage of using namespaces. What I do with namespaces I include my app in the projects urls.py by url(r'^myapp/', include('myapp.urls', namespace='myapp')), In the apps urls.py I have url(ur'^$', index, name='index'), In the apps templates I can set a link by <a href="{% url 'myapp:index' %}"> Problem If I would share 'myapp' as an reuseable app I would force the user to include the app with the given namespace 'myapp'. Why shouldn't I just name the urls name 'myapp-index' instead of 'index' in urls.py? url(ur'^$', index, name='myapp-index'), and in the template <a href="{% url 'myapp-index' %}"> -
How can I view the JSON array as a list in Django
I am rendering a queryset on views.py like this: person = MyDict.objects.filter(search_description = name) return render(request,'myPage/find.html',{'person':person}) Its rendering like this: person={ gender: male, description: ['24', 'Student', 'NY'] } If i apply the following code on my html: {% for item in person %} {{ item.description }} {% endfor %} It returns as ['24', 'Student', 'NY'] But I want to view as like this: 24 Student NY How to do it??? -
Creating separate views for related data in Django
Hello all I am attempting allow a user to use a electronic medical records software to create a patient instance using a form and have the instance created displayed on a seperate page that can be accessed via the see patient link. This is code for my views.py I created the Identity_view class based view that is rendered via the nesting.html I used both the GET and POST methods to get the unbounded form and post the bounded form to the server and save to the database. from django.shortcuts import render, redirect from django.views.generic import TemplateView from nesting.forms import Identity_Form from nesting.models import Identity_unique class Identity_view(TemplateView): template_name = 'nesting/nesting.html' def get(self, request): form = Identity_Form() Identities = Identity_unique.objects.filter(user = request.user) var = {'form': form, 'Identities': Identities} return render(request, self.template_name, var) def post(self, request): form = Identity_Form(request.POST or None) content = None if form.is_valid(): NIS = form.save(commit = False) NIS.user = request.user NIS.save() content = form.cleaned_data['NIS'] form = Identity_Form() return redirect('nesting:nesting') var = {'form': form, 'content': content} return render(request,self.template_name, var) This is the nesting.html document Currently this section of my code is on the same page as the form that is used to create the patient instances. {% block body %} … -
Simple way to fill django form with stored information - Django
I have a django template that I want to display for the user. Now I am working on an editable version of an html template. I wanted to know if there is a way to prefill a django form with relative information that is grabbed from the database or query set. I know how to display and work with forms, but not prefilling a form with information. Here is a simple form and queryset. I want to fill the UserSettingsTwoForm() with info from the currentProfile queryset. currentProfile = Profile.objects.get(user = currentUser) userSettingTwo = UserSettingsTwoForm() parameters = { 'userSettingTwo':userSettingTwo, } return render(request, 'tabs/user_settings.html', parameters) Here is a sample html file: {% extends "base.html" %} {% block content %} <h1>Settings</h1> <form action="." method="POST"> {% csrf_token %} {{ userSettingTwo.as_p }} <input type="submit" name="submit" value="submit"> </form> {% endblock %} -
SMTPDataError in Django
I am using django-allauth for my upcoming website for the purpose of registration and sign in. I have signed up with Sparkpost for sending verification emails. Below are my settings for the purpose EMAIL_HOST = "smtp.sparkpostmail.com" EMAIL_HOST_USER = "SMTP_Injection" EMAIL_MAIN = "hello@0miles.org" EMAIL_HOST_PASSWORD = "67c7c73fdfbde47fee5bfcf3ccb7386334a16b6a" EMAIL_PORT = 587 EMAIL_USE_TLS = True I have already completed the TXT record verification for the EMAIL_MAIN as mentioned above. However, I still get "SMTPDataError at /account/signup/". Here you will find the Snapshot of the error . The email domain that Django is using is "localhost". However It should be using the EMAIL_MAIN as I have mentioned in the 'settings.py' of my project. -
Django: Heroku buildpacks error?
My Django App is being rejected by Heroku. It says: App not compatible with buildpack. And gives a url for more info. After visiting this URL and applying the "solution": heroku buildpacks:set heroku/python The problem continues. Had you similar problems? This is my app: https://github.com/OmarGonD/direlim27 -
Webpack: Generate index.html for use with Django
I have an Angular 4/Django application, all of the angular code in a Django application. The angular app is built using webpack. I would like webpack to output the .js bundles into the "static" folder and an "index.html" file into the "templates" folder. The <script></script> tags that are injected will also need to be updated to use Django's "static files" notation: {% load static %} <script type="text/javascript" src="{% static 'dist/polyfills.js' %}"></script> Here is my directory structure (some files omitted for brevity), where project is the top-level holding the Django project. project + angular + app (angular application root) + config + node_modules + src - webpack.config.js + static + dist ( webpack output folder) - app.[hash].js - vendor.[hash].js - polyfills.[hash.js - index.html Note: I know I can copy/move the index.html quite easily, but I need the tags to also use Django's static files. -
Django: Assigning a Universal Variable in View
Here's my view, def index(request): data = Model.objects.all() context = {'data': data} return render(request, 'my_app/index.html', context) I have 2 apps in my school project. I wants to use data carried in "data" variable in several templates in both apps, not in one specific template as we can see here. How can I do that? Thank You :) -
Reverse for 'search' with no arguments not found. 1 pattern(s) tried: ['$search/']
Making a simple web scrapper but stuck is this problem. At initial looks everything looks fine at my side as I've just started this project. I've checked the app mentioning and other common mistakes. Please point me out if I'm missing something. I'm getting this error NoReverseMatch at / Reverse for 'search' with no arguments not found. 1 pattern(s) tried: ['$search/'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.11.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'search' with no arguments not found. 1 pattern(s) tried: ['$search/'] Exception Location: C:\Program Files (x86)\Python36-32\lib\site- packages\django\urls\resolvers.py in _reverse_with_prefix, line 497 Python Executable: C:\Program Files (x86)\Python36-32\python.exe Python Version: 3.6.3 My urls.py is: from django.conf.urls import url from . import views app_name = 'main' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^search/', views.search, name="search") ] My Views.py is: from __future__ import unicode_literals from django.http import HttpResponse from django.template import loader def index(request): template = loader.get_template('index.html') return HttpResponse(template.render({}, request)) def search(request): return HttpResponse('Hi There!') And My form goes like this <form action="{% url 'main:search' %}" method="POST" class="form-horizontal"> {% csrf_token %} <div class="form-group"> <input type="url" id="input" class="form-control" name="iurl" placeholder="Enter Your Query" autocomplete="off" required><br> <input type="submit" value="SUBMIT" class="btn btn-primary btn-lg"> </div> </form> -
How to dynamically change inline form choices fields in django admin
class CourseAdmissionDetailInline(admin.StackedInline): model = DomesticCourseAdmissionDetail form = CourseAdmissionDetailForm extra = 1 fields = ( 'entrance_exam', ('category', 'edu_level', 'course', 'degree',) ) def formfield_for_choice_field(self, db_field, request=None, **kwargs): print '+++----------------------', db_field return super(CourseAdmissionDetailInline, self).formfield_for_choice_field(db_field, request, **kwargs) Here category and degree fields are only in my form not in my model so i can not access these in my formfield_for_choice_field function. Now my ques. is >> how i can dynamically change these fields choices in inline when they are exist in form only ? -
How to make user verify password again (Just Password)?
How can I make my user verify password whenever they want to change their bio. Or simple can anyone please tell me how too extract the password for self.request.user like User.password or something. I'm writing this from my mobile phone and I've very simple model so I think no one would need code for it -
Unit testing in Django with flexible url patterns
I was using the following test to check whether page resolves to correct template: from django.test import TestCase class HomePageTest(TestCase): def test_landing_page_returns_correct_html(self): response = self.client.get('/') self.assertIn(member='Go to the', container=response.content.decode()) def test_uses_test_home_template(self): response = self.client.get('/test/') self.assertTemplateUsed(response=response, template_name='myapp/home.html') I used many variations of self.client.get('/test/') or self.client.get('/test/dashboard/') etc. in many many tests. All of which are in my myapp.urlpatterns. Then one day I decided to get rid of /test/. Or simply change the url pattern. All of the tests failed because, well, I hardcoded the urls. I would like to use flexible url's in my tests. I assume it involves something like: from myapp.urls import urlpatterns as myapp_urls and using myapp_urls throughout the tests. I have two questions: How can I implement it? Will there be any (negative) side affects of this approach that I don't foresee? -
How to build a custom widget like django-filter's BaseCSVWidget but with a different divider (using spaces (' ') instead of commas (','))
I was looking for something like django_filters.MultipleChoiceFilter but without the need to provide choices. For now I use a custom Filter like this: class MultiValueCharFilter(django_filters.BaseCSVFilter, django_filters.CharFilter): def filter(self, qs, value): # value is either a list or an 'empty' value values = value or [] for value in values: qs = super(MultiValueCharFilter, self).filter(qs, value) return qs and then use it in my FilterSet like this: class MainFilter(django_filters.FilterSet): titre = MultiValueCharFilter(name="titre", label='Titre', lookup_expr='icontains') It work well but I need to separate the value with commas and I want to use a different divider (space) so I'm trying to built a custom widget but I don't quite find how to make it work. Can anyone could give me cues on how to proceed, I have a hard time finding documentation on this topic. Thanks -
Django Block URL by Username
Excuse me if I'm not very direct about what I'm talking about or need, I'm fairly new to django/python and am still in the process of understanding things. I am creating a webapp with Django where a user will sign up, log in, create a new entry, save it, and view/edit it. Think of it as a personal diary that should be only accessible to the user who wrote it. I've gotten pretty far in this and am using filtering in the ListView, but someone could easily use url manipulation to find other users entries. Such that User A posts entry 4 at site.com/entry/4 and then user B is able to type that in and see the entry. How can I go about restricting the url to only the user who posted it? Thanks for any help, and again sorry if I'm not giving enough information or I'm not clear on what I am talking about! -
Django fails to use the django version in virutalenv
I am using django 1.11 on Ubuntu but the non-virtual python has 1.6. There are other apps using 1.6. When I run my application through apache mod_wsgi, it uses 1.6 instead of 1.11 and I get stack trace. Apache conf: WSGIPythonPath /home/wondi/envs/my_app <VirtualHost *:80> ServerName server.com ServerAdmin admin@server.com ErrorLog /var/log/apache2/error.log LogLevel warn CustomLog /var/log/apache2/access.log combined WSGIDaemonProcess server.com processes=2 threads=15 display-name=%{GROUP} WSGIProcessGroup server.com WSGIPassAuthorization On WSGIScriptAlias /my_app /home/wondi/envs/my_app/my_app/wsgi.py <Directory "/home/wondi/envs/my_app/my_app/"> <Files wsgi.py> Order deny,allow Require all granted </Files> </Directory> <Directory /home/wondi/envs/my_app/app/static/> Options Indexes FollowSymLinks AllowOverride None Require all granted IndexOptions FancyIndexing </Directory> ... </VirtualHost> my_app\wsgi.py: import os import sys from django.core.wsgi import get_wsgi_application import site env_path = '/home/wondi/envs/lib/python2.7/site-packages' # we add currently directory to path and change to it working_dir = os.path.dirname(os.path.abspath(__file__)) os.chdir(working_dir) sys.path = [working_dir] + sys.path # Append paths site.addsitedir(env_path) sys.path.append('/home/wondi/envs/') sys.path.append('/home/wondi/envs/my_app/') os.environ["DJANGO_SETTINGS_MODULE"] = "my_app.settings" activate_this = "/home/wondi/envs/bin/activate_this.py" execfile(activate_this, dict(__file__=activate_this)) application = get_wsgi_application() Stack trace: Django Version: 1.6.1 Python Version: 2.7.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.gis', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_gis', 'corsheaders', 'my_app'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') Traceback: File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 99. resolver_match = resolver.resolve(request.path_info) File "/usr/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve 337. for pattern in self.url_patterns: File "/usr/lib/python2.7/dist-packages/django/core/urlresolvers.py" in url_patterns 365. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) … -
Quora Like Notification Tab
I'm trying to make a Notification system similar to Quora or Stack overflow. Whenever user clicks a button, notifications should show up in a small window no matter at which page the user is. But I couldn't do it. Since notifications are connected to a view & a url then firstly I need to go to the url & then click on notification button, and only then the notifications show up in smaller window. How can I prevent myself from going to a URL connected to the view linked with Notifications & then click on notification button so that notifications will appear in smaller tab? Is there any way to create a Universal view or something else? Here's the url, url(r'^$', views.notifs, name='notifs') In View, def notifs(request): answers = Notifs.objects.filter(user=request.user) # not the actual method context = {'answers': answers} return render(request, 'base.html', context) In between base.html I have this "Notifications" link. Note: Here I have used jQuery to load the div that will display the Notifications in smaller tab when it's clicked. <a href="{% url 'notifications:notifs' %}" class="a">Notifications</a> Here's that div on base.html page, <div class="b messMess myTab" hidden="hidden"> {% if answers %} {% for answer in answers %} Answer …