Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a PDF downloadable on a click of a button in Django?
I've tried this as a View: def download_file(request, filename): fl = open(filename, 'r') response = HttpResponse(fl, content_type='pdf') response['Content-Disposition'] = "attachment; filename=%s" % filename return redirect(reverse('index.html')) and in my HTML I just give the file's name to the url but it says no ReverseMatch at /. Is there a solution for this? -
E-Commerce Django View that will find an object by its id and redirect to an html with the '/id'
I am looking to implement a Django view function that will redirect me to a standard "products.html", however I want it to go to "products/" depending on which product I want to view in my e-commerce website. I understand that each product gets an id but how do you use that to get an object and send that context to a new page with the field attributes. Would appreciate some advice. Thankyou -
Django Database Duplicates
I don't exactly know how to diagnose this issue of mine, but I believe I have duplicate tables in my Postgres database. The reason I say this, is because When I go to my admin page, I see entries from my projects table that are also part of the blog post table. I want to separate these. I also found issues when trying to search through my blog. Here are the error messages: Exception Type: VariableDoesNotExist Exception Value: Failed lookup for key [username] in '' This leads me to believe the search algorithm is having trouble looking through duplicates, especially since the blog posts aren't even being found in my search results. Only project objects are found. How can I take a look into the Postgres database or further diagnose my issue? -
Django - how to prevent a user to access url if not superuser?
How can I check if a User that is already logged is superuser and prevent to access some urls or views if he's not a superuser? Is it also possible to prevent a user of adding/removing a data from a model? -
Django - One model divided in two forms, how can I relate the two with the ID?
I have a Locatario model that has two main attributes: one one them concerns to the personal attributes of the person (first form - LocatarioPfForm) and the second one the details about the civil contract we have (the second form - ContratForm). class LocatarioPfForm(ModelForm): class Meta: model = Locatario fields = ['unidade', 'locatario_nome', 'locatario_genero', 'locatario_rg', 'locatario_cpf', 'locatario_estado_civil', 'locatario_bens', 'locatario_conjuge', 'fiador_boolean', 'fiador_genero', 'fiador_nome', 'fiador_rg', 'fiador_cpf', 'fiador_estado_civil', 'fiador_bens', 'fiador_conjuge'] class ContratoForm(ModelForm): class Meta: model = Locatario fields = ['data_de_inicio', 'data_de_termino', 'valor_bruto', 'valor', 'epoca_pagamento', 'vencimento', 'multa_compensatoria', 'carencia_multa', 'pdf_contrato'] widgets = { 'data_de_inicio': DateInput(), 'data_de_termino': DateInput(), 'carencia_multa': DateInput(), } help_texts = { 'multa_compensatoria': '<span class="text-muted">O Valor da multa pode ser tanto em número absoluto, como aluguéis inteiros (ex: 1300 ou 3900), ou pode ser em porcentagem. No último caso, coloca-se a porcentagem em números decimais. 10% é 0.10, por exemplo.</span>', } In views.py, I created two views to reference the two forms: def pessoaFisicaCadastro(request, pk): loc = locatario_pk(pk) form = LocatarioPfForm() if request.method == 'POST': form = LocatarioPfForm(request.POST) if form.is_valid(): form.save() return redirect('contrato-cadastro', pk=pk) context = { 'form': form, def contratoCadastro(request): c_form = ContratoForm() if request.method == 'POST': c_form = ContratoForm(request.POST, request.FILES) if c_form.is_valid(): c_form.save() return redirect('condominio') context = { 'c_form': c_form, } return … -
Django: Combine multiple saves into one database action
I have a function like this– is there a way to wrap this function so that both saves are combined into one? def foobar(self, created_at=None): changed = False if created_at: changed = True self. created_at = created_at self.save() if self.active: changed = True self.active = False self.save() return self The reason I don't unindent self.save() is to avoid updating the updated_at field on my object if no change occurred. -
How to manually unmount volumes after recovering files in Azure?
In Azure portal "File Recovery" functionality provides us a simple 3-step process: Select the restore point (date) Generate the password and download the script to mount the restore point drives. Unmount the drives after file recovery. We perform the steps to mount the volumes and take some time to review the backup, and at the same time we are working in azure portal and for any reason (accidentally or deliberately) we close this tab and lose the unmount button. How to execute step 3 manually? (to unmount the volumes). This is a temporary volume mount but how can we do it any time manually? -
Django and the import error after OSX update
After some major update on MacOSX I have some problem with doing almost anything with my django project that previously ran well. Even my python version was downgraded to 2.7. I installed python 3.8 and try to run project and I have such error: Error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Everything is activated venv. Can't install djagno with pip because I have message that "Requirement already satisfied" - so it is installed. sys.path: /Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8 /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages What's going on? -
Proper way to do a robust search in Django models via REST framework
I'm writing a web application (DRF + Vue.js) where frontend should have an ability to narrow down GET request results via different filters. For example, I have a model like this: class Human(models.Model): first_name = models.CharField(_('first name'), max_length=50, null=True, blank=True) last_name = models.CharField(_('last name'), max_length=50, null=True, blank=True) birth_date = models.DateField(_('birth date'), blank=True, null=True) city = models.ForeignKey('City', on_delete=models.SET_NULL, blank=True, null=True) phone_number = models.ForeignKey('Contact' on_delete=models.SET_NULL, blank=True, null=True) @property def full_name(self): # Last name + First name return ' '.join(str(x) for x in (self.last_name, self.first_name) if x) @property def is_adult(self): now = timezone.now() if self.birth_date: if now.year - self.birth_date.year - \ ((now.month, now.day) < (self.birth_date.month, self.birth_date.day)) >= 18: return True return False Now I have simple CRUD ViewSet where I can use a list of search_fields to search by all needed fields (in my case that's birth_date, city, phone_number and full_name/is_adult). But here next problems arise: Using search_fields I can do a search only by all fields specified in the ViewSet's search_fields (frontend can't search only by city or other distinct fields if it wants to) - other way I'll need to create a separate ViewSet (and separate URL?) for every combination of fields to filter by. Terrific. So it looks like the … -
how i can get number of customer for each hour django rest framework
i would get number of customer for each hour in day . this my model: class Client(models.Model): id_track=models.IntegerField(default=0) temps_attente=models.CharField(max_length=50) date_entree = models.DateTimeField(auto_now_add=True) camera = models.ForeignKey("Camera", on_delete=models.CASCADE) class Meta: verbose_name = "Client" ordering = ['camera'] def __str__(self): return self.temps_attente i want something like this : [ {date:02/09/2020 , hour:"09" ,nbrCustumer:30} {date:02/09/2020 , hour:"10" ,nbrCustumer:22 } {date:02/09/2020 , hour:"11" ,nbrCustumer:10} {date:02/09/2020 , hour:"12h,nbrCustumer:12} ] -
How do I add a column in pre existing model? getting this error:
Im getting this error after I run migrations= django.db.utils.OperationalError: no such column: pdfReports_files.category here is my model: I added category field later. from django.db import models class files(models.Model): pdf = models.FileField(upload_to='media') menu_name=models.TextField(default='SOME STRING') href=models.TextField(default='#') category=models.TextField(default='') objects = models.Manager() -
Customise JSON string display in Django admin
I'm working on a custom online market project. I've made a simple Order model: class Order(models.Model): cart = models.CharField(max_length=1000) user = models.ForeignKey(User, on_delete=models.CASCADE) The cart field stores the whole order in one JSON string which can look something like this: {"8": 6, "5": 1} Where the key is an ID of a product and value is it's quantity. The problem is that standard Django admin displays this as a string and it's completely not friendly for humans to read. Is there a way I can unpack this string using json.load, then filter the instances of Product objects and render it in a certain way the same way it can be done with a regluar view and a custom template, but within the admin interface? -
Django isn't recognizing crispy forms
my pip is showing that crispy forms is installed but for some reason when I run manage.py it's saying that it doesn't exist. Here is some history from my terminal that I annotated over for clarity. [ec2-user@ip-172-26-0-126 bd_website]$ pip list DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Package Version ---------------------------- -------- (elements ommitted for brevity...) Django 1.11.29 django-crispy-forms 1.9.0 <<Crispy forms is installed, right? (elements ommitted for brevity...) [ec2-user@ip-172-26-0-126 bd_website]$ pip install django-crispy-forms DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: django-crispy-forms in /home/ec2-user/.local/lib/python2.7/site-packages (1.9.0) [ec2-user@ip-172-26-0-126 bd_website]$ python --version Python 3.6.11 <<Version is compatible with Django [ec2-user@ip-172-26-0-126 bd_website]$ python manage.py runserver Watching for file changes with … -
local variable 'direct1' referenced before assignment
I am writing a simple program where I enter an employee ID number and it renders the data for that employee. Here is my code on the backend: def emp1(request): import requests import json if request.method == 'POST': quote = request.POST['quote'] # or None if quote == "10001401": employee1 = requests.get("the api url") direct1 = json.loads(employee1.content) return render(request, 'home.html', {'quote': quote, 'direct1': direct1}) Now this works. It's only when I enter another employee, that I am told that 'direct1' is referenced before assignment. I tried to make the variable (direct1) global. But I don't think I am grasping how to do that in django views. -
SAML 2.0 + Keycloak + Django
Hello I'm trying to implement Keycloak SAML 2.0 authentication with Django application. I'm using django_saml2_auth and I configured my project as I was instructed in the django_saml2_auth repo. My configuration of django_saml2_auth is: SAML2_AUTH = { 'METADATA_AUTO_CONF_URL': 'http://localhost/keycloak/auth/realms/master/protocol/saml/descriptor' } when I start the development server on localhost:8000 and go to /accounts/login I'm redirected to Keycloak and I have the following error: We are sorry... Unknown login requester Do you know how to fix that? Do you know some well documented examples of Keycloak SAML 2.0 configuration with Django? -
Form submission not working in Django 1.11 with python 2.7
Am new to Django . I have python2.7 and django 1.11 version , I was able to display a home page etc. But when trying to create a form and submitting its not redirecting to any page url.py from django.conf.urls import include from . import views from django.conf.urls import url urlpatterns = [ url("",views.home, name="home"), url("add",views.add,name="add") ] home.html {%extends 'base.html' %} {%block content %} <H1> hello world 2 {{name}} </H2> <form action="/add"> Enter 1st number : <input type="text" name = "num1"><br> Enter 2nd number : <input type="text" name = "num2"><br> <input type = "submit"> </form> views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): x = ' Hello World' return render(request,'home.html',{'name' : 'Test Name'} ) # return HttpResponse(x) def add(request): print('testing') val1 = request.GET['num1'] val2 = request.GET['num2'] res = val1 + val2 print(res) return render(request,"results.html",{'result' : res}) results.html is a test page. Once I click submit its not displaying any thing on the results page . Is there anything wrong in url.py -
how can I avoid the third pattern slug gets overwritten?
I got an overwrite from the last part of my URL similar to this. how can I improve the way I am using the slug from models to urls.py, and avoid getting overwrite my lesson module URI? models def get_absolute_url(self): return reverse('lesson-module',kwargs={ 'lesson_slug': self.lesson.slug, 'lesson_module': self.slug }) urls.py urlpatterns = [ path('', CourseListView.as_view(), name='university'), path('<slug>', CourseDetailView.as_view(), name='detail'), path('<course_slug>/<lesson_slug>', LessonDetailView.as_view(), name='lesson-detail'), path('<course_slug>/<lesson_slug>/<lesson_module>', LessonModuleDetailView.as_view(), name="lesson-module"), ] views class LessonDetailView(LoginRequiredMixin, View): def get(self, request, course_slug, lesson_slug, *args, **kwargs): class LessonModuleDetailView(LoginRequiredMixin, View): def get(self, request, course_slug, lesson_slug, lesson_module, *args, **kwargs): uris http://localhost:8000/university/ http://localhost:8000/university/javascript http://localhost:8000/university/javascript/lesson-1 http://localhost:8000/university/javascript/hello-world # this gives me , but I I want http://localhost:8000/university/javascript/lesson-1/hello-world (edited) -
Django: ImportError at/ "doesn't look like a module path
** How can I solve this problem? ** Exception Type: ImportError at /enter code here Exception Value: first_app doesn't look like a module pathenter code here Request Method: GETenter code here Request URL: http://127.0.0.1:8000/`enter code here` Django Version: 3.0.3enter code here Python Version: 3.8.5enter code here Installed Applications:enter code here ['django.contrib.admin',enter code here 'django.contrib.auth',enter code here 'django.contrib.contenttypes',enter code here 'django.contrib.sessions',enter code here 'django.contrib.messages',enter code here 'django.contrib.staticfiles',enter code here 'first_app'] Installed Middleware:enter code here ['django.middleware.security.SecurityMiddleware',enter code here 'django.contrib.sessions.middleware.SessionMiddleware',enter code here 'django.middleware.common.CommonMiddleware',enter code here 'django.middleware.csrf.CsrfViewMiddleware',enter code here 'django.contrib.auth.middleware.AuthenticationMiddleware',enter code here 'django.contrib.messages.middleware.MessageMiddleware',enter code here 'django.middleware.clickjacking.XFrameOptionsMiddleware']enter code here -
migrations for djstripe subscription payment api integration not working
bellow error i am facing while running this command python3 manage.py djstripe_sync_plans_from_stripe Error: djstripe.UsageRecord.livemode: (fields.W903) NullBooleanField is deprecated. Support for it (except in historical migrations) will be removed in Django 4.0. HINT: Use BooleanField(null=True) instead. -
how to specify a url for a default image in django
I am using this code for assinging a default image for a post if user doesn't upload any. It works fine for home page. But when I go to detailed view of this post django looks image in 'domain/post/id/media/default-book.jpg' address. This is my code {% else %} <img class="cover-img" src="media/default-book.jpg" alt=""> {% endif %} instead of address for the default image, how can i assign a url like {{ default.url }} this for the source file. -
Django form for list of values
Is it possible to somehow process a list of values using standard Django classes and without using a for loop to create a form for each value? models.py class Warehouse(models.Model): name = models.CharField(max_length=128) class Shift(models.Model): warehouse = models.ForeignKey("Warehouse", blank=False, null=False, on_delete=models.CASCADE) number = models.IntegerField() start_time = models.TimeField(blank=True, null=True) end_time = models.TimeField(blank=True, null=True) JSON data { "name":"Warehouse", "shifts":[ { "start_time":"09:00", "end_time":"18:00", "number":"1" }, { "start_time":"10:00", "end_time":"18:00", "number":"2" } ] } I'm trying formset_factory. But with list it wont working. With one object raise ['ManagementForm data is missing or has been tampered with'] What i'm trying: forms.py class ShiftForm(forms.Form): id = forms.IntegerField(required=False) number = forms.IntegerField(required=True) start = forms.TimeField(required=False) end = forms.TimeField(required=False) def save(self): ... class WarehouseForm(forms.Form): name = forms.CharField(required=True, max_length=128) def save(self): ... views.py def post(self, request): form = WarehouseForm(json.loads(request.body)) Formset = formset_factory(ShiftForm) formset = Formset(json.loads(request.body)["shifts"]) if form.is_valid() and formset.is_valid(): # here formset raise error ... return HttpResponse(status=200) else: return JsonResponse(form.errors, status=400) -
Django: Get UTC Timezone
This seems extremely simple, but I cannot find a simple explanation: How can I get the UTC timezone to pass here? I want to pass GMT / UTC specifically. from django.utils import timezone timezone.make_aware(datetime.fromtimestamp(sometimestamp), timezone=???) -
Can't "activate" virtualenv
New to running Python in virtual environments, messing with Django, and can't activate a virtual environment. Spent the last 4 hrs trying to activate a virtual env (venv) on local terminal/VS Code with no luck. Avoided "sudo pip install virtualenv" as I was trying to avoid installing as root and having different directory path, etc. "pip install virtualenv" output: Collecting virtualenv Using cached virtualenv-20.0.31-py2.py3-none-any.whl (4.9 MB) Requirement already satisfied: six<2,>=1.9.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.15.0) Requirement already satisfied: appdirs<2,>=1.4.3 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (1.4.4) Requirement already satisfied: filelock<4,>=3.0.0 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (3.0.12) Requirement already satisfied: distlib<1,>=0.3.1 in /Users/garrettpinto/Library/Python/3.8/lib/python/site-packages (from virtualenv) (0.3.1) Installing collected packages: virtualenv Successfully installed virtualenv-20.0.31 "virtualenv venv" output: created virtual environment CPython3.8.5.final.0-64 in 416ms creator CPython3Posix(dest=/Users/garrettpinto/Desktop/rp-portfolio/distribution/venv, clear=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/Users/garrettpinto/Library/Application Support/virtualenv) added seed packages: pip==20.2.2, setuptools==49.6.0, wheel==0.35.1 activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator "source venv/bin/activate" returns nothing "./venv/bin/activate" output: zsh: permission denied: ./venv/bin/activate "sudo ./venv/bin/activate" output: sudo: ./venv/bin/activate: command not found Thoughts? -
how can I avoid getting the last part of the url overwrite?
I am trying to do the following, but however I got an overwrite from the last part of my url similar to this. how can I improve the way I am using the slug from models to urls.py , and avoid getting overwrite my lesson module uri ? models def get_absolute_url(self): return reverse('lesson-module',kwargs={ 'lesson_slug': self.lesson.slug, 'lesson_module': self.slug }) urls.py urlpatterns = [ path('', CourseListView.as_view(), name='university'), path('<slug>', CourseDetailView.as_view(), name='detail'), path('<course_slug>/<lesson_slug>', LessonDetailView.as_view(), name='lesson-detail'), path('<course_slug>/<lesson_slug>/<lesson_module>', LessonModuleDetailView.as_view(), name="lesson-module"), ] views class LessonDetailView(LoginRequiredMixin, View): def get(self, request, course_slug, lesson_slug, *args, **kwargs): class LessonModuleDetailView(LoginRequiredMixin, View): def get(self, request, course_slug, lesson_slug, lesson_module, *args, **kwargs): uris http://localhost:8000/university/ http://localhost:8000/university/javascript http://localhost:8000/university/javascript/lesson-1 http://localhost:8000/university/javascript/hello-world # this gives me , but I I want http://localhost:8000/university/javascript/lesson-1/hello-world (edited) -
ODBC Error with Django Configuration - "Invalid value specified for connection string attribute 'encrypt' "
I have done quite a bit of searching on the error below and I have been hitting all around it, not finding where my configuration may be off. When configuring django 3.x with a Microsoft SQL Server, I get the following error when running my application. The error seems to point to some encryption parameter but in my testing, I have yet to determine which parameter. I have tried a number of different security-based settings in the "OPTIONS" but no luck. Can anyone point me in the right direction? Error: django.db.utils.OperationalError: ('08001', "[08001] [Microsoft][ODBC Driver 17 for SQL Server]Invalid value specified for connection string attribute 'encrypt' (0) (SQLDriverConnect)") Libraries installed django-mssql-backend==2.8.1 pyodbc==4.0.30 Connection String DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'testDB', 'HOST': 'testserver.test.net', 'PORT': '1433', 'USER': 'username', 'PASSWORD': 'password', 'AUTOCOMMIT': True, "OPTIONS": { 'driver': 'ODBC Driver 17 for SQL Server', 'host_is_server': True, 'connection_timeout': 30, 'collation': 'SQL_Latin1_General_CP1_CI_AS', 'extra_params': 'Trusted_Connection=yes;Encrypt=yes', } } }