Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Filter objects which has no specific record on its relational model
Supposed i have this model class Employee(models.Model): name = models.CharField(max_lenght=25) class Attendance(models.Model): employee = ForeignKey(Employee, on_delete=models.CASCADE) is_present = models.BooleanField() This is my implementation: Employee.objects.bulk_create([ Employee(name='Greg'), Employee(name='John'), Employee(name='Lesley'), ]) emp1 = Employee.objects.get(name='Greg') emp1.attendance_set.create(is_present=True) emp1.attendance_set.create(is_present=True) emp1.attendance_set.create(is_present=True) emp2 = Employee.objects.get(name='John') emp2.attendance_set.create(is_present=True) emp2.attendance_set.create(is_present=True) emp2.attendance_set.create(is_present=True) emp3 = Employee.objects.get(name='Lesley') emp3.attendance_set.create(is_present=True) emp3.attendance_set.create(is_present=False) Now how can i filter employees which has no Attendance.is_present=False That will yield the distinct record of Greg and John? -
routes may be wrong
I got an error that, Page not found (404) Request Method: GET Request URL: http://localhost:8000/accounts/registration/accounts/registration/accounts/registration/accounts/profile.html . I think routes are wrong.(I am a beginner,but I think so) But I cannot understand how to fix the routes. In accounts app,I wrote in urls.py from django.conf.urls import url from . import views from django.contrib.auth.views import login, logout urlpatterns = [ url(r'^login/$', login, {'template_name': 'registration/accounts/login.html'}, name='login'), url(r'^logout/$', logout, name='logout'), url(r'^regist/$', views.regist,name='regist' ), url(r'^regist_save/$', views.regist_save, name='regist_save'), url(r'^registration/accounts/registration/accounts/profile.html$', views.regist_save, name='regist_save'), ] in views.py @require_POST def regist_save(request): form = RegisterForm(request.POST) if form.is_valid(): user = form.save() login(request, user) context = { 'user': request.user, } return redirect('registration/accounts/profile.html', context) context = { 'form': form, } return render(request, 'registration/accounts/regist.html', context) in accounts(child app)/templates/registration/accounts/profile.html directory, {% extends "registration/accounts/base.html" %} {% block content %} user.username: {{ user.username }}<hr> user.is_staff: {{ user.is_staff }}<hr> user.is_active: {{ user.is_active }}<hr> user.last_login: {{ user.last_login }}<hr> user.date_joined: {{ user.date_joined }} {% endblock %} Please tell me what is wrong. -
confused about URL files
I simply want to get to another directory than index. What I think Django is doing after I type in "localhost:8000/ysynch/": Checking "ysynch/urls.py" (my root urls.py file) Finding "ytlinks/" including "links.urls" Matching with "ytlinks/" (in file "links.urls") and calling "views.ytlinks" But instead, views.index is called. Where am I doing a mistake? root\urls.py C:\Users\xyron\Desktop\ysynch\ysynch\urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^ytlinks/', include('links.urls')), url(r'^$', include('links.urls')), ] links\urls.py C:\Users\xyron\Desktop\ysynch\links\urls.py urlpatterns = [ url(r'^ytlinks/', views.ytlinks, name='ytlinks'), url(r'^$', views.index, name='index'), ] links\views.py C:\Users\xyron\Desktop\ysynch\links\views.py from django.shortcuts import render, render_to_response from django.http import HttpResponse from django.template import loader from django.views.generic import ListView, DetailView from .models import YTLink def ytlinks(request): print ("coming from views.ytlinks") queryset = YTLink.objects.all() return render(request, 'links/home.html', {'queryset':queryset}, content_type='application/xhtml+xml') def index(request): print ("coming from views.index") return render(request, 'links/home.html') -
heroku local web :error No module named django.core.wsgi
my project was running until i tried to test with heroku for deploy . so i installed virtualenv added a requirements.txt file with `appdirs==1.4.0 packaging==16.8 Django==1.9.7 pyparsing==2.1.10 requests==2.13.0 six==1.10.0 psycopg2==2.6.1 whitenoise==2.0.6` changed django to 1.8.5 thinking it might be version related when i pip installed requirements.txt i got this error Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. -
Django model changes not reflected on Postgres Docker container
I have a Django-Postgres app deployed with Docker. I have two docker containers web and dband one docker volume for persistent storage. My docker-compose.yml file: version: '2' services: db: image: postgres ports: - '5432:5432' volumes: - 'postgres:/var/lib/postgresql/data' env_file: .env web: build: . command: ./start.sh volumes: - .:/app ports: - "8000:8000" depends_on: - db env_file: .env volumes: postgres: I made a change in my django model.py: class Meeting(models.Model): [...] participants = models.CharField(max_length=200) to class Meeting(models.Model): [...] user_participants = models.CharField(max_length=200) However, this change is not reflected on my Django app and I get the following error: column call_meeting.user_participants does not exist I ran: python manage.py makemigrations call python manage.py migrate Then I tried to delete Django migrations and re-run the above commands. I have tried to re-run docker-compose build but none of them worked. Why does this happen? Should I change the column names with raw SQL? -
How to use mysql database with Django? I have connected myslq with django in settings. But how do we use it in views?
How should I register mysql tables to admin panel? How to use data in these tables in HTML views or for apis? -
Django 1.8, Postgis Querying distance between two points
In a tutorial i saw the distance calculation between a given point and points in db. from django.contrib.gis.db.models.functions import Distance But Django 1.8 didn't have above "functions" module. So how can i achieve the same result as the query below in 1.8 qs = qs.annotate(distance=Distance('location', pnt)).order_by('distance') I looked at Geo database api docs. But i got confused. -
How do I apply my formating to a django app form?
I'm trying to apply my own CSS formatting to a Django form from django-registration app. I've taken a copy of the forms.py file and called it registration_forms.py and I am then calling the various views with my version of the forms. This seems to work except it is only applying my widget to the username field. Here is my form: class Meta(UserCreationForm.Meta): fields = [ User.USERNAME_FIELD, 'email', 'password1', 'password2' ] required_css_class = 'required' widgets = { User.USERNAME_FIELD : forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.EmailInput(attrs={'class':'form-control'}), 'password1' : forms.PasswordInput(attrs={'class':'form-control'}), 'password2' : forms.PasswordInput(attrs={'class':'form-control'}), } The only bit I've added it the widgets which works for User.USERNAME_FIELD but for nothing else. -
Django: render a txt file with linebreaks
I need to return a txt file as HTTPResponse in Django. The file needs to contain multiple lines generated from a list (ex. ['line one', 'line two']). If I use DTL and a template, I cannot insert any line breaks except for html-specific ones. So, my current solution is to write lines to response with csv.writer. It works, but isn't there a more elegant way to get a txt file that looks like this? line one line two -
Django deployement partial migrations issues?
I was facing issues to efficiently replicate database changes on production. the best solution I can find is to gitignore migrations files so that I can isolate migration process on production. any better solutions to securely push model changes without deployment problems ? -
Render Django formset as array
I have a model and i need to create form with multiple instances in it. To be more specific: i need to render my ModelForm inside regular form with square brackets next to it's fields names. Something like this in magicworld: forms.py class ManForm(ModelForm): class Meta: model = Man fields = ['name', 'age'] class PeopleForm(forms.Form): # modelless form people = ??? # array of ManForm instances or something form.html <form action="/people/create/"> {{ form }} </form> output <form action="/people/create/"> <input type="text" name="name[0]"/> <input type="text" name="age[0]"/> </form> To tell you the truth, i don't know how to approach this problem at all. I tried modelformset_factory, but all i've got is <input type="text" name="form-0-name"/> -
Reading reports from django report_builder from another domain
I'm trying to use the report_builder in django (http://django-report-builder.readthedocs.io/en/latest/) to read reports in a dashboard. I need to read it from another domain/django installation. I already tried authenticating with a user who can access the reports from the other domain but i keep getting forwarded to the login page. When i try to fill in this page i get a csrf verification failed error. I can't disable the csrf verification because i'm not in control of that domain/django installation. Do i need to implement something like http://www.django-rest-framework.org/ to handle authentication or am i missing something? -
How to send a generate report request from Javascript to Python
I'm noob at javascript and python. Is there an easy way of sending a request by clicking on the download button? This button should send a request (from client) to a python view (to server) and there it will be generated. Currently I'm creating a csv file without any request and it makes the aplication slower. I saw some ways using ajax and sending it to django api by the url, but I would like to know if are the an easiest and better way. On the frontend side <button onclick={this.theFunctionThatSendsDataToPython()} className="btn btn--download btn--color-tecno"><Download className="icon-download"/><span className="btn--download-text">DOWNLOAD</span></button> If I receive any data at python's view it will be great. -
Django ORM: How to filter in an annotation with Count() (subquery) without rawsql
For a list query I want to show how many prices there are for a specific product on a specific site. I have found a way to do this with RawSQL, something I had never ever had to do before. Am I overlooking something? queryset = Price.objects.all() site_annotations = {} for site in Site.objects.all(): site_annotations['num_prices_{}'.format(site.name)] = RawSQL( 'SELECT COUNT(id) ' 'FROM `product_siteprice` ' 'WHERE `product_siteprice`.`price_id` = `product_price`.`id` ' 'AND site_id=%s', [site.pk] ) queryset = queryset.annotate(**site_annotations) -
Not able to authenticate superuser or login into admin site in Django?
Am building a restful API using django rest. I also want took it with the inbuilt django admin functionalities. I created a super user using the ./manage.py createsuperuser command. When I tried to login the created user using the correct credentials I could not. On researching I discovered I did not have AUTHENTICATION_BACKENDin my settings. I added authentication backends and that did not work. my settings.py file: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '1_ebkw5nvkp^=+eaf7njk&wrlmcqj(u)(+#+wf#5kko@4va%am' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', 'rest_framework', 'rest_framework.authtoken', 'api_v1', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'bucketlists.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'bucketlists.wsgi.application' AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',) # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'buckos', 'USER': 'postgres', 'TEST': {'CHARSET': … -
Accessing django session data
While reading the docs I understood that django session is accessed using the request object. What happens when there are multiple views? Should I use the same 'request' object in all views to access the session data? (I'm new to django :) ) -
Passing values back to views from django dynamic fields
I have searched a lot for this answer, and I am sure it is something very basic I am missing. I want to pass an argument into a dynamic form in django. The form dynamically populates the ChoiceField based on the value passed to it but I get a key error for 'location_choice' when I submit the form. The form gets passed a location_choice (which is actually a group), it then picks out a list of relevant locations based on that filter and populates the drop down with the values listed as the PK for each location. What I cannot do is then submit that form and pass that value back to a subsequent view. I cannot pass any data back as I get a key error I have spent hours trying to understand what it is I am doing wrong here, including reading this post, which was helpful but I'm still missing something: https://jacobian.org/writing/dynamic-form-generation/ views.py def test_search(request): form = search_criteria(request.POST or None, location_choice="Group A") return render(request, 'utilisation/util_search_day_theatre.html', { 'form': form }) forms.py class search_criteria(forms.Form): start_date = forms.DateField(label='Start Date', required = False, input_formats=['%d/%m/%y', '%d/%m/%Y'], initial="1/1/16") end_date = forms.DateField(label='End Date', required = False, input_formats=['%d/%m/%y', '%d/%m/%Y'], initial='1/5/16') dayofweek_dataset = dayofweek.objects.all().values_list() dayofweek_choice = … -
Multi-tenant schema with django
I am new to working with multi-tenant schema with django. I have followed the below link https://django-tenant-schemas.readthedocs.io/en/latest/install.html When I creating client object, separate tenant schema is created,it's fine. but followed user is not created in separate tenant schema, it's created only in public schema. and I wanna change the domain url when a user login's in it redirects from the public tenant to their private client tenant account. I am very new to this kind of functionality. Any one can give me some guidelines or solution. -
Django LDAP authentication
Given an username and password, I want to authenticate against a LDAP directoy with these credentials in one of my Django apps. I've been taking a look to this library but I still don't know how to use it properly once I've configured it. On the one hand, I receive a JSON with username and password and I need to add an user to LDAP with these credentials. And, on the other hand, in subsequent request, I need to check that the user who makes the request belongs to LDAP (and only LDAP not the own Django backend, so if there's an user with the same credentials in the Django users database should't be allow to continue). I've tried something like this to add an user: authbackends.py class CustomLDAPBackend(LDAPBackend): def authenticate(self, username, password, **kwargs): # Add user to LDAP user = LDAPBackend.authenticate(self, username, password) return user So I can import it in my view to add the user to LDAP. Could anyone outline a solution? -
What is the easiest way to program website with login as an admin?
what is the simpliest way to make an interface on web? Like I will make home page, a few blank pages and then I need to make a database on which people can login as admins and adjust or change ONLY their page. I have already made html/css website and now need somehow implement database and program how people will login with id and pw I'll give them and change their stuff. Could someone tell me the easiest way to do that and which language would be best to use (I can't use ASP.NET, cuz of the server). I've been thinking of Django, but I am not sure if I can make it. Thanks in advanced -
django, ValueError: could not convert string to float:
i want recover variable by request from my template but return me ValueError: could not convert string to float: ligneFactureTempForm = facture_form() quantite_article = request.GET.get('quantite_article') ligneFactureTempForm.fields['montant'].initial = float(prix_unitaire) -
Sending professional emails through django
from django.core.mail import EmailMultiAlternatives subject, from_email, to = 'hello', 'from@example.com', 'to@example.com' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() I want to be able to sends newsletters or emails that have been designed properly, including images if possible. I was wondering if I could change this html_content = '<p>This is an <strong>important</strong> message.</p>' into an html template file. Like this html_content = 'newsletter/news.html' If not then how do I go about sending emails like that of Quora and other websites.` -
Django rest api Change oauth response error format
I have successfully implemented oauth2 for my django rest api project. I want to change the error response format of the login api. Current error response is { "error_description": "Invalid credentials given.", "error": "invalid_grant" } I want to change the error_description key to detail (detail is the key of all other django error responses). I need to make a standardize all the error responses. Expected result is { "detail": "Invalid credentials given." } This is executing from class OAuth2Error(Exception) in /lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/errors.py file. -
Update request.session variable before function ends
At a Django server, I have a page with a single button that starts a function. This function takes a while to complete, and I tried writing updates on the process to a request.session variable with the intent of checking on its contents from a separate page. It seems however that request.session variables are not updated until the function they are included in are done. At least the variable does not update until then. Am I right, and if so, is there a way to write to request.session variable before the function's completion? The sessions are set up properly, I can write and read variables with other examples. For now I'll also just make a temporary db record to store the status update info and read it from there, but I'm curious as of this request.session thing - is my guess correct, and is there a way around? -
session handling in multi part web application
we wrote a restful application that consists of multiple parts wrote in different languages such as python and node. every part of this application located in an apart server. so we want to manage sessions in this servers. user logged in from one server and redirected to another server. so the question is how to manage sessions for this application in python.