Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Assigning a Global Variable django
Here's my code, def notifications(request): new_data = Answer.objects.all() return render(request, 'base.html', {'new_data': new_data}) I have 2 apps in my project. I wants to use data stored in new_data variable in several templates. I can't extend the template. Is there any other way for doing so? -
imoprt error when I gave source toaster start in morty
I got below error when i run poky/build$ source toaster start. The system will start. Traceback (most recent call last): File "/home/siva/yocto/Morty/poky/bitbake/bin/../lib/toaster/manage.py", line 10, in <module> execute_from_command_line(sys.argv) ...... from .management import update_contenttypes ImportError: cannot import name 'update_contenttypes' I have seen the below link but I believe That is diiferent than this. importerror: cannot import name update _all_content -
Django class view: __init__
Im newcomer to python and django and I need some help with class views. I want to get < Model > value from url, and use it as init parameter in my class. urls.py url(r'^(?P<Model>\w+)/foo/$', views.foo.as_view(), name='foo_class'), views.py class foo(CreateView): def __init__(self, **kwargs): text = kwargs['Model'] #this is not working text = kwargs.get('Model') #nethier this Bar(text) ... Clearly, I'm missing something, or my understanding of Url <> class view is wrong. -
Django/template_block doesn't be operated
Thanks in advance. I have a code below "index.html" <!DOCTYPE html> <html> <head> </head> <body> {% block content %}{% endblock %} </body> </html> and I have another html code("maintab.html") for child of "index.html" {% extends "encyclopeida/index.html" %} {% block content %} <p>Hello world</p> {% endblock %} but it doesn't work.. my contact path is "browser -> "http://localhost/encyclopedia/"(by urls) -> function def("by view.py") -> index.html" and below is my folder structure. enter image description here -
Issue with url returned after login with facebook/google + in an django app
I am building an app using django 1.11 and providing users option to Login with Facebook and Login with Google. For this I am using social-auth-app-django 1.2.0. On successful login, I redirect it to a page – UserProfile.html – setting.py AUTH_PROFILE_MODULE = 'home.UserProfile' where home is an app. urls.py of project (say myProject) url(r'^myProject/',include('home.urls')), url('^complete/facebook/', include('home.urls')), url('^complete/google-oauth2/', include('home.urls')), urls.py in home app url(r'^ UserProfile.html',views. UserProfile,name=' UserProfile ') But the url generated after Login with Facebook is – http://localhost:8000/complete/facebook/UserProfile.html#= which should have been - http://localhost:8000/myProject/UserProfile.html Similar is the issue when user tries Login with Google. URL generated – localhost:8000/complete/google-oauth2/UserProfile.html# which should have been – localhost:8000/myProject/UserProfile.html Please assist and let me if I am missing something. -
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