Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why am I getting the error local variable 'user_form' referenced before assignment
In the code, why am I getting "local variable 'user_form' referenced before assignment" error? from django.shortcuts import render from basic_app.forms import UserForm,UserProfileInfoForm def index(request): return render(request,'basic_app/index.html') def register(request): registered=False if request.method=="POST": user_form=UserForm(data=request.POST) profile_form=UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user=user_form.save() user.set_password(user.password) #Hashing the password user.save() profile=profile_form.save(commit=False) profile.user=user #Sets up one to one relationship if 'profile_pic' in request.FILES: profile.profile_pic=request.FILES['profile_pic'] profile.save() registered=True else: print(user_form.errors,profile_form.errors) else: user_form=UserForm() profile_form=UserProfileInfoForm() return render(request,'basic_app/registration.html',{'user_form':user_form,'profile_form':profile_form,'registered':registered}) This is in the views.py file. Have been stuck on this project since a while. Please help? -
Service Provider initiated Single Logout in Django
I work on a project with SAML authentication implemented using python-social-auth. I am trying to implement a view that initiates Single Logout (i.e. logout from all Service providers and Identity provider) on Service provider side. Currently, being logged in via SAML, I can access specific Identity provider page (ADFS, if that matters) and initiate Single Logout from there. So at the end there should be two options for logout - Django normal logout and the view that initiates Single Logout. I was able to extract name_id and session_index, and put it in request.session because, if I understand correctly, they are required for Single Logout. Also, the code from https://github.com/python-social-auth/social-core/issues/199 looks very similar to what I need, but I didn't manage to get solution with it. Particularly, I don't know where and how I should use process_logout(). What is correct approach to this problem? Is the code by the link above related to my problem. And if so, should I add some more code to make it work? -
MultiValueDictKeyError request.POST request.FILES
this is my problem: I have a form that allows to post a part in the database and another part that allows to upload a file to a folder in my hard drive, my problem is that I only valid the first part I have an error : MultiValueDictKeyError at/newrelease/ I do not know at all how to do the else or the return!! :s Thank you for your help def newrelease(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = UploadFileForm(request.POST, request.FILES) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required project = form.cleaned_data['project'] manufacturer = form.cleaned_data['manufacturer'] model = form.cleaned_data['model'] version = form.cleaned_data['version'] date = form.cleaned_data['date'] file = form.cleaned_data['file'] #upload files uploaded_file = (request.FILES['document']) fs = FileSystemStorage('/home/voirinj/workspace/uploads') print(project, manufacturer, model, version, date, file, uploaded_file) #importer une release dans Release new_release = Release( project = project, manufacturer = manufacturer, model = model, version = version, date = date, file_name = '', file_id = '', ) #save a release new_release.save() #save a file "obligation : (uploaded_file.name, uploaded_file)" fs.save(uploaded_file.name, uploaded_file) #message release … -
After getting the data from ajax POST method open another window in django
I want to pass data in views and open another html file in window.open("{% url 'view_detail' %}", "_self"), when i use ajax it post data successfully in views, Now i have to open this url, when i use this syntax window.open("{% url 'view_detail' %}", "_self"), it goes to same function and return nothing, How should i avoid this, .js file <script> function myFunction() { console.log("======") $('#NextButton').on('click', function () { console.log('After Clicking Next Buttton') $.ajax({ url : "/analytics/show_analytics/", type : "POST", async: true, data : { industry: $("input[name='analyticsindustry']:checked").val(), domain: $("input[class='analyticsdomain']:checked").val(), functions: $("input[class='analyticsfunctions']:checked").val(), csrfmiddlewaretoken: '{{ csrf_token }}', }, success : function(data) { var c = document.getElementById('domaincheckbox2').value; alert(data) window.open("{% url 'show_analytics', '_self' %)}") show_a(data) } }) return false; }) } </script> views.py def show_analytics(request): cursor = connection.cursor() #posts = analyticsreport.objects.values('Domain', 'Analytics').distinct() #print('POSTS', posts) total_analytics = [] if request.method == 'POST': industry = request.POST.get('industry') domain = request.POST.get('domain') functions = request.POST.get('functions') print("Industry", industry) print("Domain", domain) print("Functions", functions) #total_analytics = [] query = ('select id, Analytics from analytics_analyticsreport where Industry = ' + "'" + industry + "'") result = analyticsreport.objects.raw(query) print(len(result)) print(result) for i in range(len(result)): analytics = result[i].Analytics print('Analytics', analytics) if analytics not in total_analytics: total_analytics.append(analytics) print('Total_Analytics', total_analytics) return render_to_response('analytics/demo.html', {'posts': total_analytics}) -
Trying to save a PDF string results in UnicodeDecodeError with WeasyPrint
So far this is my code: from django.template import (Context, Template) # v1.11 from weasyprint import HTML # v0.42 import codecs template = Template(codecs.open("/path/to/my/template.html", mode="r", encoding="utf-8").read()) context = Context({}) html = HTML(string=template.render(context)) self.pdf_file = html.write_pdf() Actually it works via web request (returning the PDF as response) and via shell (manually writting the code). The code is tested and never gaves me problems. The files are saved with correct encoding, and setting the encoding kwarg in HTML doesn't help; also, the mode value of the template is correct, because I've seen other questions whose problem could be that. However, I was adding a management command to use it periodically (for bigger PDFs I cannot do it via web request because the server's timeout could activate before finishing), and when I try to call it, I only get a UnicodeDecodeError saying 'utf8' codec can't decode byte 0xe2 in position 10: invalid continuation byte. The PDF (at least from what I see) renders initially with this characters: %PDF-1.3\n%\xe2\xe3\xcf\xd3\n1 0 which translates into this: %PDF-1.3 %âãÏÓ 1 0 obj So the problem is all about the character â. But it's a trap! Instead, the problem is this line of code: self.pdf_file = html.write_pdf() Changing … -
Django problem, Exception Value: Friend matching query does not exist
I'm doing a Django blog website project. One of my feature is when you login, you can click on the tab Other member to show you a list of other members like in this picture. However, this feature only works when I login as the admin, when I log in as other members (not the admin), click the tab Other Member it will display errors Friend matching query does not exist. I'm really confused and getting stuck on this one. Here is my code: list_users.html {% extends "blog/base.html" %} {% block content %} <div class="container"> <div class="col-sm-6"> <h2>Other People</h2> {% for user in users %} <a href="{% url 'view_profile_with_pk' pk=user.pk %}"> <h3>{{ user.username }}</h3> </a> {% if not user in friends %} <a href="{% url 'change_friends' operation='add' pk=user.pk %}"> <button type="button" class="btn btn-success">Add Friend</button> </a> {% endif %} {% endfor %} </div> <br> <div class="col-sm-6"> <h2>Friends</h2> {% for friend in friends %} <a href="{% url 'view_profile_with_pk' pk=friend.pk %}"> <h3>{{ friend.username }}</h3> </a> <a href="{% url 'change_friends' operation='remove' pk=friend.pk %}"> <button type="button" class="btn btn-default">Remove Friend</button> </a> {% endfor %} </div> </div> {% endblock content %} views.py function listusers def listusers(request): posts = Post.objects.all().order_by() users = User.objects.exclude(id=request.user.id) friend = Friend.objects.get(current_user=request.user) friends = … -
custom template loader Django
i am trying to write a custom template loader in django which serves index.html which is present in a s3 bucket. Following is my loader file from django.conf import settings from django.template import Origin, Engine from django.template.loader import TemplateDoesNotExist from django.template.loaders.base import Loader from boto3.session import Session ACCESS_KEY_NAME = getattr(settings, 'AWS_TEMPLATE_LOADING_ACCESS_KEY_ID', getattr(settings, 'AWS_TEMPLATE_LOADING_ACCESS_KEY_ID', None)) SECRET_KEY_NAME = getattr(settings, 'AWS_TEMPLATE_LOADING_SECRET_ACCESS_KEY', getattr(settings, 'AWS_TEMPLATE_LOADING_SECRET_ACCESS_KEY', None)) TEMPLATE_BUCKET = getattr(settings, 'AWS_TEMPLATE_BUCKET_NAME') class Loader(Loader): is_usable = True def __init__(self, *args, **kwargs): params = args[0] options = params.pop('OPTIONS').copy() options.setdefault('autoescape', True) options.setdefault('debug', settings.DEBUG) options.setdefault('file_charset', settings.FILE_CHARSET) libraries = options.get('libraries', {}) session = Session(aws_access_key_id=ACCESS_KEY_NAME, aws_secret_access_key=SECRET_KEY_NAME) s3 = session.resource('s3') self.bucket = s3.Bucket(TEMPLATE_BUCKET) super(Loader, self).__init__(*args, **kwargs) self.engine = Engine(dirs=params['DIRS'], context_processors=options, loaders=Loader) def getKeys(self): keys_objects = [] for obj in self.bucket.objects.all(): key = obj.key keys_objects.append({ 'key': key, 'object': obj }) return keys_objects def get_contents(self, origin): try: keys_objects = self.getKeys() for key_object in keys_objects: if key_object['key'] == origin: return key_object['object'].get()['Body'].read() except FileNotFoundError: raise TemplateDoesNotExist(origin) def get_template_sources(self, template_name, template_dirs=None): tried = [] yield Origin( name=template_name, template_name=template_name, loader=self, ) tried.append('/index.html') if tried: error_msg = "Tried Keys %s" % tried else: error_msg = "Your TEMPLATE_DIRS setting is empty. Change it to point to at least one template directory." raise TemplateDoesNotExist(error_msg) get_template_sources.is_usable = True and in my settings i … -
Datetime in django with template filter will show different value
I'm using Django Template Filters to format datetime, looks like its value differs from raw date in Datebase. I used datetime.now() in Python to create and then {{ modeltest.date }} will show "Jan. 3, 2019, 5:27 a.m." on the page. {{ modeltest.date | date:"Y-m-d H:m:s" }} displays "2019-01-03 05:01:19" I'm getting a little confused here. Does anyone know this? Thanks. -
Appendix text to a reference in django template
I am trying to prepend my domain name to an image url passed to sorl-thumbnail, to prevent a SuspiciousFile Error, as the source images are located in my static folder and sorl-thumbnail creates stuff in my media dir. Prepending a domain name to the url passed to sorl-thumbnail is the advice given in a bug report, so I thought I would try it. I am trying like so: {% for instance in prods %} {% thumbnail "https://mydomainname.com/"instance.image_url "300x300" crop="smart" as im %} <img src="{{ im.url }}" > {% endthumbnail %} {% endfor %} However, putting a string before instance.image_url does not work. What is the correct way to do this? -
upload file in djago using FormData in jquery & ajax
Upload image beside other data when user submit the form. using formData in jquery. I added picture field to the model added picture element in the form added the input tag in the html send the data through AJAX to the view getting the data from ajax request and added to the view function the system display error : File "C:\Users\LT GM\Desktop\Final new\djangoWeb\views.py", line 160 request.session['idTe2chira']=id TabError: inconsistent use of tabs and spaces in indentation models.py picture = models.ImageField(upload_to = 'pictures/%d/%m/%Y/',null=True, blank=True) form.py from django import forms from blog.models import te2chira, destination class SaveTe2chira(forms.ModelForm): class Meta: model = te2chira fields = ['title', 'description','picture' ] html <form method="POST" class="form-style-9" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <li> <input type="file" id="img" name="img"/> </li> <li> <input type="submit" class="field-style field-full align-none" id="save" value="save" /> <script type="text/javascript"> $(function(){ $('#save').on('click',function(e){ e.preventDefault() var formData = new FormData(); formData.append('num',$('#num').val()) formData.append('title',$('#title').val()) formData.append('text',$('#text').val()) formData.append('issent', 0) formData.append('img', document.getElementById('img').files[0]) $.ajax({ url:'/create/te2chira', method:'POST', data:formData, processData:false, contentType:false, headers:{ 'X-CSRFToken':'{{csrf_token}}' } }).done(function(msg) { document.location = "/creativePageSend.html" alert('data saved') }).fail(function(err){ alert('no data was saved') }) }) }) </script> </li> </ul> </form> views.py def post_new(request): if request.method =='POST': form = SaveTe2chira(data = request.POST, files = request.FILES) if form.is_valid(): form.save() id=form.te2chira_id request.session['idTe2chira']=id return render(request,'./creativePageSend.html',{'id':id}) print("valid form") else: print("invalid … -
How to fix 'Django: table doesn't exist' when migrating from someone else's project?
I get the following error while trying to run python manage.py makemigrations invigilators: django.db.utils.ProgrammingError: (1146, "Table 'mydatabase.invigilators_shift' doesn't exist") class Shift(models.Model): shiftName = models.CharField(max_length=255,blank=False,unique=True) exam = models.ForeignKey(Exam,on_delete=models.CASCADE,related_name="shifts") startTime = models.TimeField() endTime = models.TimeField() def __str__(self): return self.shiftName I have already cleared all previous migrations and empty database is already created. -
Dango login, next url redirect to external links
One application was allowing redirection to external links after login using the next parameter, for instance if I'm login with https://myawesomeapp.com/en/auth/login?next=http://google.be I would be redirected to Google. The issue is fixed using is_safe_url function (from django.utils.http) and I also should use built-in LoginView from Django. My question is: Is it a security security breach ? What an hacker can achieve with that breach ? -
django decorator_from_middleware settings
I'm trying to avoid adding corsheaders middleware from django-cors-headers to my MIDDLEWARE_CLASSES variables cause this project is in production and damn fragile. So basically question is - is there any method to do setup for middleware used like this? Seems middlware variables in settings.py not working for this method -
How do I protect a password stored on server?
So, I set up a Django project and I'm done with it. Anyway, there's a function in the views.py script that is meant to send an email. I'm using the smtplib library and of course I need to login to send the email through my email address, so in that script my email and my password are written. I'll publish this project (hosted by Heroku) so I'm worring about the password protection. What do you think? Is the password protected or do I need to protect it in some way? I don't think it could be possible to access the views.py script but I'm not sure. -
how to skip an existing object instance when creating resources in bulk python
I am trying to create a resources in bulk, while the resources are created i have the matric_no has to be unique ,if the value of an existing matric_no is uploaded together with the some new entries , i get an integrity error 500 because the value already exists and it stops the rest value from being created. How can i loop through these values and then check if the value exist then skip so that the others can be populated. Here is my code: **models.py** from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Undergraduate(models.Model): id = models.AutoField(primary_key=True) surname = models.CharField(max_length=100) firstname = models.CharField(max_length=100) other_names = models.CharField(max_length=100, null=True, blank=True) card = models.CharField(max_length=100, null=True, blank=True) matric_no = models.CharField(max_length=20, unique=True) faculty = models.CharField(max_length=250) department_name = models.CharField(max_length=250) sex = models.CharField(max_length=8) graduation_year = models.CharField(max_length=100) mobile_no = models.CharField(max_length=150, null=True, blank=True) email_address = models.CharField(max_length=100) residential_address = models.TextField(null=True, blank=True) image = models.CharField(max_length=250, default='media/undergraduate/default.png', null=True, blank=True) def __str__(self): return "Request: {}".format(self.matric_no) ***serializers.py*** from .models import Undergraduate from .models import Undergraduate class UndergraduateSerializer(serializers.ModelSerializer): class Meta: model = Undergraduate fields ='__all__' class CreateListMixin: """Allows bulk creation of a resource.""" def get_serializer(self, *args, **kwargs): if isinstance(kwargs.get('data', {}), list): print(list) kwargs['many'] = True return super().get_serializer(*args, **kwargs) **api.py** from .models import … -
Timestamp with time zone, unknown using django ORM
After shifting from MariaDB to postgres-10 i am getting below error I am using Django-orm function date_format(timestamp with time zone, unknown) does not exist LINE 1: SELECT (DATE_FORMAT(created_at,'%h %p')) AS "in_hours", SUM(... HINT: No function matches the given name and argument types. You might need to add explicit type casts. Model.objects.filter(franchise=franchise)\ .filter(created_at__date=date)\ .extra(select={'in_hours': "DATE_FORMAT(created_at,'%%h %%p')"}) \ .values('in_hours')\ .order_by('created_at__hour')\ .annotate(total_amount=Sum('amount')) Can anyone please explain where its going wrong. Thank you -
Wrong configuration for database in seetings.py or docker
I'm learning how to work with Compose + Django using this manual https://docs.docker.com/compose/django/ Here are my configuration files docker-compose.yml version: '3' services: db: image: postgres web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } When I run using docker-compose up everything is fine. But when I run using python manage.py runserver I got this error psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known Guess, I have wrong cofiguration -
DRF polymorphic many-to-many with extra fields
I'm tinkering around with Django Rest Framework to build an api that can handle Bills of Materials (BoM) of electronic components. I'm using django-polymorphic and django-rest-polymorphic so I can use polymorphic models for the components (they have shared attributes, but I still want to handle them in much the same way. The polymorphic models are great for this purpose). All is well and good until I introduce many-to-many relations with a 'through' attribute. What I would like is a BoM that has several different components, each with a quantity, e.g. BoM1 has 2x470k resistor & 3x 100uF capacitor. models.py: (pruned a bit to keep this post from being an epic novel) class BoM(models.Model): """Bill of Materials: a list of all parts and their quantities for a given pedal""" pedal = models.ForeignKey(Pedal, on_delete=models.CASCADE) variant = models.CharField(max_length=100, blank=True) electronic_components = models.ManyToManyField( 'ElectronicComponent', through='ElectronicComponentQty', blank=True) class Meta: verbose_name = 'Bill of materials' verbose_name_plural = 'Bills of materials' def __str__(self): return str(self.pedal) class ElectronicComponent(PolymorphicModel): """Shared data model for electronic components""" value = models.CharField(max_length=20) datasheet = models.FileField(upload_to='uploads/components', blank=True) def __str__(self): return self.value class ElectronicComponentQty(models.Model): """Combination of resistor and quantity""" bom = models.ForeignKey(BoM, on_delete=models.CASCADE) component = models.ForeignKey( ElectronicComponent, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) class Meta: verbose_name = … -
Django: Problem in doing complex annotation
This is model: class Purchase(models.Model): date = models.DateField(default=datetime.date.today,blank=False, null=True) total_purchase = models.DecimalField(max_digits=10,decimal_places=2,blank=True, null=True) I want to perform a month wise calculation of "total_purchase" within a specific daterange in such a way that if there is no purchase in a month the total purchase should be the previous month purchase value And if there is purchase in two months then total purchase will the addition of those two... Example: If there is a Purchase of $2800 in month of April and $5000 in month of August and $6000 in month of October.. Then the output will be like this: April 2800 May 2800 June 2800 July 2800 August 7800 #(2800 + 5000) September 7800 October 13800 #(7800 + 6000) Any idea how to perform this in django queries? Thank you -
How do I reduce the amount of queries of my Django app?
My app is currently making over 1000 SQL queries and taking around 20s to load the page. I can't seem to find a way to come up with a solution to get the same data displayed on a table in my template faster. I wan't to display 100 results so that's way my pagination is set to 100. these are the methods in my my models.py used to get the count and sum of the orders, these two are in my Company model and the get_order_count is also in my Contact model def get_order_count(self): orders = 0 for order in self.orders.all(): orders += 1 return orders def get_order_sum(self): total_sum = 0 for contact in self.contacts.all(): for order in contact.orders.all(): total_sum += order.total return total_sum views.py class IndexView(ListView): template_name = "mailer/index.html" model = Company paginate_by = 100 and here is the table body in my template {% for company in company_list %} <tr id="company-row"> <th id="company-name" scope="row">{{ company.name }}</th> <td>{{ company.get_order_count }}</td> <td id="order-sum">{{ company.get_order_sum|floatformat:2 }}</td> <td class="text-center"> <input type="checkbox" name="select{{company.pk}}" id=""> </td> </tr> {% for contact in company.contacts.all %} <tr id="contact-row"> <th scope="row">&nbsp;</th> <td>{{ contact.first_name }} {{ contact.last_name }}</td> <td id="contact-orders"> Orders: {{ contact.get_order_count }} </td> <td></td> </tr> {% endfor … -
Configuring Traefik, Caddy, and Gunicorn inside Docker using docker-compose
I'm a beginner. I have gone through the tutorial on Docker and have been searching and reading online for a way to use Traefik as a reverse proxy for the web server Caddy to serve my static files and web application using Gunicorn. My problem is coming up with a working solution. Currently, I have a docker-compose file for Traefik; port forwarding from 80 and 443, to default to 443 (https with ACME SSL, etc.). My other docker-compose is for the web application and Caddy. I'm using abiosoft/Caddy image on Docker Hub. This is my current docker-compose file the web app and Caddy. Also, how do I do static content as well? I've been trying, and no luck. version: '3' services: unipgdb: image: postgres restart: always container_name: unipgdb environment: POSTGRES_USER: xxxx POSTGRES_PASSWORD: xxxx PGDATA: /var/lib/postgresql/data/pgdata volumes: - ./db-data:/var/lib/postgresql/data/pgdata ports: - "5432:5432" networks: - internal djangoapi: build: context: . dockerfile: Dockerfile image: unicausal/backend:latest command: > sh -c "python manage.py makemigrations && python manage.py migrate && python manage.py collectstatic --noinput && gunicorn --preload --chdir api --bind 0.0.0.0:8000 -w 4 api.wsgi:application" container_name: djangoapi volumes: - .:/unicausalapi - static_volume:/home/roycea/project_five/static networks: - unicausalnetwork - internal depends_on: - unipgdb - caddyproxy restart: always labels: - "traefik.enabled=true" … -
how to use models in django for a query
Assume that i have a table usr with feilds name and age table usr id|name |age| 1 |dinkan | 12| my query is select id from usr where name="dinkan" or age="20"; the corresponding output should be 1 so , my question is how to implement this in django 2.1 using models Thanks in advance -
How to binding data that get from Stored Procedure and display the result as a data grid
How to map result from Stored Procedure to each column on html datagrid -
Where I should filter data? Server side or front side?
Imagine I have array of reviews like this: [{title: '...', text: '...'}, {title: '...', text: '...'}]. And I have an text input. If user type some text I want filter reviews using that text. I can do it on both sides: front end and back end. What I know is: front end may be faster if array of reviews is small may be done offline back end may be faster if array of reviews is big I want to know what should I prefer and when (I appreciate complete overview). Taking in consideration such things as: UX, mobile devices, requests to server, server may be overloaded because of too much requests, user mobile may be overloaded because data is too big, array may be either big and small, array items may be either big or small (not only text and title), and what is "big" and "small". -
How to give database name in runtime and migrate all changes to it
i am making one API which will create database. I want to migrate changes in that database. How to migrate changes in database whose name is user defined.