Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Google App Engine / Django - attempt to write a readonly database
How can I give permissions to the db.sqlite3? I can't access the source files using their google shell cloud ... I can't believe google made it so complicated ... OperationalError at /admin/login/ attempt to write a readonly database Request Method: POST Request URL: https://******.appspot.com/admin/login/?next=/admin/ Django Version: 2.2.5 Exception Type: OperationalError Exception Value: attempt to write a readonly database Exception Location: /env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 383 Python Executable: /env/bin/python3.7 Python Version: 3.7.4 Python Path: ['/srv', '/env/bin', '/opt/python3.7/lib/python37.zip', '/opt/python3.7/lib/python3.7', '/opt/python3.7/lib/python3.7/lib-dynload', '/env/lib/python3.7/site-packages'] Server time: Fri, 11 Oct 2019 02:03:43 +0000 -
How many servers do I need when I use Nuxt and back-end separately?
If I want to use nuxt only as the front end and Python as the back end, does it need a total of three servers as the Web server, node server, and backend server? -
React Links in Django/React Project
I am in the process of adding some additional functionality to my Django/React project but am hitting a snag when it comes to Linking. I'm fairly new to React so please forgive my ignorance. I have two separate HTML pages that I am rendering two different React components on. landing/react.html web_app/react.html And I have buttons on landing/react.html that need to redirect users to web_app/react.html while also rendering a different component. But whenever I use the following to link users to a different page, it renders the content of that component but none of the stylesheets. I'm assuming because those stylesheets are referenced on web_app/react.html and not landing/react.html: <Link to="/web_app/"> <button className="btn-fill"> Click This </button> </Link> The following renders the page as designed, but I can't seem to pass props using this method: <a href="/web_app/"> <button className="btn-fill"> Click This </button> </a> I've pasted some relevant code below. Is there a way that I can link users to a new component/new HTML page while also preserving the ability to pass props? App.js import React, {Component} from 'react'; import {BrowserRouter, Route, Switch} from 'react-router-dom' import './App.css'; import Comms from './comm/Comms'; import CommDetail from './comm/CommDetail'; import CommCreate from './comm/CommCreate'; import WebAppDetail from './web_app/WebAppDetail'; import … -
Angular not getting data when browser and postman are
I have an API developed in Django Rest Framework which works when called in my browser and with postman but gives a "(Failed)" response when called in Angular. Doesn't give a response code (eg 404) In the console log it claims its due to CORS but the same browser allows it then called directly. Getting: Access to XMLHttpRequest at 'http://localhost:8000/article/articletype' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. I know from the Django console that a call is being made successfully as it gives a 200 response. I have tried allowing CORS to bypass from both ends by adding headers to the Angular calls. The below is the Access-Control's I have permitted. I've also played with different Content-Types and Accepts (was text/html) but now listing as * 'Accept' : '*/*' , 'Content-Type': '*' , 'Access-Control-Allow-Origin':'*', 'Access-Control-Allow-Headers':'*' For Django I have added the 'corsheaders' plugin with CORS_ORIGIN_ALLOW_ALL = True I have also tried returning HttpResponse of the JSON and JsonResponse in Django. In Django RFW: Currently the code looks like this but I have tried lots of different iterations jresponse = { "id" : 2, "text" : response, … -
Indent json using ujson and django_rest_framework
I have the following code: def get(self, request): with open(INSTANT_ONBOARDING_SCREENS_JSON, 'r') as json_file: return Response(ujson.load(json_file)) It reads my JSON file, and returns a response. However, when I go to this API endpoint. Everything is in 1 line. I see that ujson.dumps has an indent=4 option. I'm not sure how to display the JSON response properly (in a beautiful way) on the API endpoint. I'm using django_rest_framework, APIView to handle the GET request. -
Uncaught (in promise) Error: Request failed with status code 400, How can I solve this error in React.js + Django App?
I am programming an app with a Django rest API and React.js frontend installed in a django app. I am encountering an error when trying to make a post request from react to the rest API. Posting to the Django rest API works in postman. I am trying to set up the component with the useState hook, Redux and axios. Im not totally sure I set up the state correctly. Here is the relevant code: From the form component (I suspect the error is here): import React, { useState } from "react"; import { connect } from "react-redux"; import PropTypes from "prop-types"; import { addLead } from "../../actions/leads"; const Form = ({ addLead }) => { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [message, setMessage] = useState(""); const onSubmit = e => { e.preventDefault(); const lead = { name, email, message }; addLead(lead); // Clear Fields setName(""); setEmail(""); setMessage(""); }; return ( <div className="card card-body mt-4 mb-4"> <h2>Add Lead</h2> <form onSubmit={onSubmit}> <div className="form-group"> <label>Name</label> <input className="form-control" type="text" name="name" onChange={e => setName(e.target.value)} value={name} /> </div> <div className="form-group"> <label>Email</label> <input className="form-control" type="email" name="email" onChange={e => setEmail(e.target.value)} value={email} /> </div> <div className="form-group"> <label>Message</label> <textarea className="form-control" type="text" name="message" onChange={e => … -
Preview webpage at mobile device
I am new to html. I'm currently using django to create a website and wondering is there some way that I can preview my website at phone? For instance, if I set my width to be 1000px, how this will behave in a mobile device? -
Python/Django user detail view
I have problem with Django Rest, about user edit and detail. So this is the code class UserUpdateAPIView(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = UserUpdateSerializer lookup_field = 'username' permission_classes = [IsOwnerOrAdminOrReadOnly] throttle_scope = 'edit_user' and view.py is like path('<slug:username>/edit/', UserUpdateAPIView.as_view(), name='user-update'), What I need to do is to delete this <slug:username> and set it to be only /edit so when I'm calling for example http://localhost:8000/api/user/edit/ I will receive current info about my account in API and can change it if I want. I know this is put method, so is it possible to return current informations in json format about my account? -
update field in model using the same field with the function update() django
I have for many records to update a field, I must do it with the function .update() that already comes with the ORM of Django. I need to update this field concatenating a string with the value of the same field. I have tried using annotate, with F expression and Value. But it didn't work, because in the annotation of a field I can't seem to use the same field. This is what I tried to do: Model.objects.all().annotate(image=Concat(Value("Path/"), F("image"))) I have the next model: +------+-------+ | id | image | +------+-------+ | 1 | image1| | 2 | image2| | 3 | image3| When updating the model, suppose I want to concatenate the string "Path/" with field image, should be something like this +------+------------+ | id | image | +------+------------+ | 1 | Path/image1| | 2 | Path/image2| | 3 | Path/image3| -
NoReverseMatch with keyword arguments not found when the keyword arguments match
I'm getting the error: Reverse for 'search_blog' with keyword arguments '{'search_terms': ''}' not found. 1 pattern(s) tried: ['blog/search/(?P[^/]+)/$'] So, my arguments match and yet I'm getting a NoReverseMatch... I've tried removing the <str:search_terms> pattern from the 'search_blog' path and excluded the kwargs parameter from my reverse call, and that worked. So, the problem must lie solely in the url pattern. I tried renaming the pattern to 'terms' but got the same error: Reverse for 'search_blog' with keyword arguments '{'terms': ''}' not found. 1 pattern(s) tried: ['blog/search/(?P[^/]+)/$'] Here are the relevant snippets: urls.py path('search/', views.nav_search_input, name='nav_search_input'), path('search/<str:search_terms>/', views.search_blog, name='search_blog'), views.py def nav_search_input(request): if request.method == 'POST': form = SearchBlog(request.POST) if form.is_valid(): return HttpResponseRedirect(reverse('search_blog', kwargs={'search_terms': form.cleaned_data['search_terms']})) else: form = SearchBlog() context = { 'form': form } return render(request, 'index.html', context) def search_blog(request, search_terms=''): posts = Post.objects.all() form = SearchBlog() if form.is_valid(): posts = Post.objects.all().filter(title__contains=search_terms) context = { 'form': form, 'posts': posts } return render(request, 'blog/search_blog.html', context) -
Django Selenium Chromedriver Saving Scraped Files to S3 Bucket
I created a scraping script with Selenium and Chromedriver. This is the header in sel.py. I used the example here: Downloading a file at a specified location through python and selenium using Chrome driver options = webdriver.ChromeOptions() prefs = {"profile.default_content_settings.popups": 0, "download.default_directory": DEFAULT_FILE_STORAGE, "directory_upgrade": True} options.add_experimental_option("prefs", prefs) driver = webdriver.Chrome(options=options) driver.get('https://unsplash.com/s/photos/download') I want to save the downloaded file into my S3 Bucket. I followed these tutorials: How to Setup Amazon S3 in a Django Project & Serve Django Static & Media files on AWS S3 | Part 2 Settings.py AWS_ACCESS_KEY_ID = 'xxxxxxxx' AWS_SECRET_ACCESS_KEY = 'xxxxxxxxx' AWS_STORAGE_BUCKET_NAME = 'xxxxxxx' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) DEFAULT_FILE_STORAGE = 'MyProject.storage_backends.MediaStorage' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' AWS_DEFAULT_ACL = None The "download.default_directory": DEFAULT_FILE_STORAGE in the sel.py is not working, because it keeps saving the photos in the downloads folder instead of S3. How can I make my S3 folder the download default directory? -
Does Django have the capability of sharing a field value between a pair of users such as a symmetric key?
I want a user to be able to take plaintext and paste it into a form to submit using a symmetric key and then receive the ciphertext. Then using the ciphertext another user who shares the symmetric key can use that key to decrypt that ciphertext. I'm new to Django and believe I need to setup a user model and use that model somehow to solve the problem but I'm not sure how and cannot find any information to help. I believe I need a special model because that's how you store and retrieve user information but I could be wrong. from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) key = models.?????? The actual results should be as follows: A user logs in and chooses from a list of users that they have "befriended" so to speak where they both share the same symmetric key(<--the topic of question). That user then takes plaintext such as a sentence or paragraph and pastes this information into an HTML form where they can click submit. Upon submission the plaintext is encrypted using the key respective of the intended recipient. Then that information runs through a encryption algorithm … -
Django/Apache Server Down but 403
i have a Django Site running on Debian server. The thing is that it crushed out and is giving now a 403 Forbidden error. The site run for 2 years without an issue. I shutdown the apache2 server and while was not running I could still see the 403 error. Normal trick was to see 500 while was down. Can someone pls advise? Why is this caching? I've followed all the steps from other past 403 questions. Options FollowSymLinks AllowOverride None Require all denied <Directory /usr/share> AllowOverride None Require all granted </Directory> <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> #<Directory /srv/> # Options Indexes FollowSymLinks # AllowOverride None # Require all granted #</Directory> # AccessFileName: The name of the file to look for in each directory # for additional configuration directives. See also the AllowOverride # directive. # AccessFileName .htaccess # # The following lines prevent .htaccess and .htpasswd files from being # viewed by Web clients. # <FilesMatch "^\.ht"> Require all denied </FilesMatch> -
Disable {% debug %} tag in Django template
Is there a way to prevent Django template from outputting a bunch of debug output? I tried setting DEBUG = False and setting my TEMPLATES option like so: TEMPLATES = [ { ... 'OPTIONS': { 'debug': False, 'context_processors': [ 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], } } ] Despite the above settings, whenever I put {% debug %} into my template, it still outputs a lot of debug information. -
Randomizing again in Django
When I generate a quiz in django, the question value before if request.method == 'POST': is one and then changed. Follow the screenshots. views.py questao = Questao.objects.annotate(resp_count=models.Count(models.Case(models.When(resposta__usuario=request.user, then=1),output_field=models.IntegerField()))).filter(resp_count=0,tipoQuestao=1).order_by("?").first() print (questao) if request.method == 'POST': print (questao) respostaform = RespostaForm(request.POST or None) if respostaform.is_valid(): resp = respostaform.save(commit=False) resp.idQuestao = questao if resp.resposta == questao.respostaQuestao: resp.certaresposta = 1 else: resp.certaresposta = 0 resp.save() return HttpResponseRedirect(request.path_info) -
How to access the human-readable name using get_FOO_display
Hello I have the next code to show to my participants the text of the response that the gave me in a anterior session. J12 = models.IntegerField( choices=[ [-2, 'Muy moralmente inapropiado'], [-1, 'Moralmente inapropiado'], [0, 'No aplica'], [1, 'Moralmente apropiado'], [2, 'Muy moralmente apropiado'], ], widget=widgets.RadioSelect ) TJ12 = models.CharField(max_length=20, choices=J12) When I try to prove this code I get the next error: File "C:\Users\diese\iat\incentivos\models.py", line 140, in <module> class Player(BasePlayer): File "C:\Users\diese\iat\incentivos\models.py", line 216, in Player TJ11 = models.CharField(max_length=2, choices=J11) File "c:\users\diese\appdata\local\programs\python\python37\lib\site-packages\otree\db\models.py", line 386, in __init__super().__init__(max_length=max_length, **kwargs) File "c:\users\diese\appdata\local\programs\python\python37\lib\site-packages\otree\db\models.py", line 217, in __init__ fix_choices_arg(kwargs) File "c:\users\diese\appdata\local\programs\python\python37\lib\site-packages\otree\db\models.py", line 195, in fix_choices_arg choices = expand_choice_tuples(choices) File "c:\users\diese\appdata\local\programs\python\python37\lib\site- packages\otree\common_internal.py", line 118, in expand_choice_tuples if not isinstance(choices[0], (list, tuple)): TypeError: 'IntegerField' object is not subscriptable What Can I do? Someone has experienced the same ? Thanks in advance -
Serialize model with foreign key Django
I have the following json: The problem with it is the 'tipo_envase' field, whose id is being returned in my json, but I do not want the id, but the whole object that is linked to tipo_envase, which is basically this json: I tried to serialize the models this way class TipoEnvaseSerializer(serializers.ModelSerializer): class Meta: model = Tipoenvase fields = ('id','nombre') class PresentationSerializer(serializers.ModelSerializer): class Meta: model = Presentation fields = ('nombre','capacidad','tipo_envase') And the models are these: class Presentation(models.Model): nombre = models.CharField(max_length=100) capacidad = models.CharField(max_length=100) tipo_envase = models.ForeignKey('Tipoenvase', on_delete=models.CASCADE) def __str__(self): return self.nombre + " " + self.capacidad + " " + self.tipo_envase.nombre class Tipoenvase(models.Model): nombre = models.CharField(max_length=100) def __str__(self): return self.nombre In summary the following json structure is required: `{ "nombre":"Frasco" "capacidad":"410 gr" "tipo_envase":{ "id":"1" "nombre":"vidrio" } }` -
Mezzanine Fabric deployment, PSQL issue - "Error: role "project" already exists"
Having huge troubles deploying Mezzanine on digitalocean, and I'm taking it step by step to figure out all the small issues individually. Running "fab create" results in successfully (I guess?) setting up the virtualenv, but when it comes to setting up the PSQL database, it errors with the following (full output): [1xx.xx.xxx.xxx] Executing task 'create' ←[1;32m------ create ------←[0m ←[1;34m$ ←[0m←[1;33mlocale -a←[0m←[1;31m ->←[0m [1xx.xx.xxx.xxx] Login password for 'adm': ←[1;34m$ ←[0m←[1;33mmkdir -p /home/adm/mezzanine/project←[0m←[1;31m ->←[0m ←[1;34m$ ←[0m←[1;33mmkdir -p /home/adm/.virtualenvs←[0m←[1;31m ->←[0m Virtualenv already exists in host server: project Would you like to replace it? [Y/n] y ←[1;34m$ ←[0m←[1;33mrm -rf project←[0m←[1;31m ->←[0m ←[1;34m$ ←[0m←[1;33mvirtualenv project←[0m←[1;31m ->←[0m [1xx.xx.xxx.xxx] out: Using base prefix '/usr' [1xx.xx.xxx.xxx] out: New python executable in /home/adm/.virtualenvs/project/bin/python3 [1xx.xx.xxx.xxx] out: Also creating executable in /home/adm/.virtualenvs/project/bin/python [1xx.xx.xxx.xxx] out: Installing setuptools, pip, wheel... [1xx.xx.xxx.xxx] out: done. [1xx.xx.xxx.xxx] out: [localhost] local: git push -f ssh://adm@1xx.xx.xxx.xxx/home/adm/git/project.git master adm@1xx.xx.xxx.xxx's password: Everything up-to-date ←[1;34m$ ←[0m←[1;33mGIT_WORK_TREE=/home/adm/mezzanine/project git checkout -f master←[0m←[1;31m ->←[0m [1xx.xx.xxx.xxx] out: Already on 'master' [1xx.xx.xxx.xxx] out: ←[1;34m$ ←[0m←[1;33mGIT_WORK_TREE=/home/adm/mezzanine/project git reset --hard←[0m←[1;31m ->←[0m [1xx.xx.xxx.xxx] out: HEAD is now at a1fe1de Droplet reset [1xx.xx.xxx.xxx] out: [1xx.xx.xxx.xxx] out: sudo password: [1xx.xx.xxx.xxx] out: ERROR: role "project" already exists [1xx.xx.xxx.xxx] out: Fatal error: sudo() received nonzero return code 1 while executing! Requested: psql -c … -
How to change a field in parent class while creating chiled class fields in forms.py and views.py?
I'm was creating ModelForm I try to make change the parent class while saving child class fields to the database, in the views.py I made but it didn't save to the database. here is my model.py class Table(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) book = models.BooleanField(default=False) class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) taple = models.OneToOneField(Table, on_delete=models.CASCADE, null=True, blank=True) @receiver(post_save, sender=User) def update_people_profile(sender, instance, created, **kwargs): try: instance.people.save() except ObjectDoesNotExist: People.objects.create(user=instance) Class People is the child class and Table is the parent class so I'm using People class for making forms. here is my forms.py class Booking(forms.ModelForm): class Meta: model = People fields = [ 'taple', ] So I want to make True book field in Table class and save it to the database when saving Booking form. here is my views.py def booking(request): if request.method == 'POST': try: people_instance = People.objects.get(user=request.user) except Table.DoesNotExist: people_instance = People(user=request.user) form = Booking(request.POST, instance=people_instance) if form.is_valid(): user = form.save(commit=False) user.taple.booking = True user.refresh_from_db() user.user = request.user user.taple = form.cleaned_data.get('taple') user.save() print(user.taple.booking, user.taple.id) return redirect('booked') else: form = Booking() return render(request, 'main/booking.html', {'form': form}) Any Idea? -
How to deploy a wep abb within my work network?
I created an API for the company i work however i would like people having access in the same company network, how can i achieve this? I currently modified the allowed host as follow: ALLOWED_HOSTS = ['127.0.0.1', 'localhost','192.168.6.7', '127.0.1.1', '161.19.109.123'] however only work in my computer under IP: 127.0.0.1:8000, any suggestions? FYI i do not have administrator privilege. -
Set up django-celery-email for local dev
It seems the best way to send emails from the django-allauth app asynchronously is to simply install django-celery-email. But the packages warns that This version requires the following versions:Python 2.7 and Python3.5, Django 1.11, 2.1, and 2.2 Celery 4.0 I've only been using python for several months and never encountered a situation where two python version are needed on a project. And I'm using the official recommendation of pipenv for local development. A quick google shows that it isn't possible to have two python interpreters installed in the virtual environment. Since the plugin seems so popular I wondered how others were setting it up? Apologies if I've missed something major that explains this. A bonus answer would also take into account that I am using docker and the docker image will install the python packages like this. RUN pipenv install --system --deploy --ignore-pipfile Many thanks in advance. -
How do I use Django template tags inside javascript
I am using a library called FullCalendar and I want my model data inside my template inside the javascript which I have seen many people do. But for some reason the template tags won't register as template tags and I get an error. <script> document.addEventListener('DOMContentLoaded', function() { var Calendar = FullCalendar.Calendar; var Draggable = FullCalendarInteraction.Draggable; var containerEl = document.getElementById('external-events'); var calendarEl = document.getElementById('calendar'); var checkbox = document.getElementById('drop-remove'); // initialize the calendar // ----------------------------------------------------------------- var calendar = new Calendar(calendarEl, { plugins: [ 'interaction', 'dayGrid', 'timeGrid', 'bootstrap', 'interaction' ], themeSystem: 'bootstrap', selectable: true, select: function(info) { var titleStr = prompt('Enter Title'); var date = new Date(info.startStr + 'T00:00:00'); // will be in local time if (!isNaN(date.valueOf())) { // valid? calendar.addEvent({ title: titleStr, start: date, allDay: true, }); } }, locale: "sv", header: { left: 'prev,next today', right: 'dayGridMonth,timeGridWeek,timeGridDay' }, customButtons: { }, eventClick: function(info) { alert('Event: ' + info.event.title); }, editable: true, droppable: true, events: [ {% for event in events %} { title: "{{ event.name}}", start: '{{ event.start|date:"Y-m-d" }}', end: '{{ event.end|date:"Y-m-d" }}', }, {% endfor %} ], }); calendar.render(); }); </script> the part that is not working is the {% for event in events %} loop, the view parses the … -
How to save objects en la UpdateView class, returning a Json?
I have 2 related models for an fk and to which I access. But to save the instances of the forms in the UpdateView class, I get the error "AttributeError: type object 'Users_up' has no attribute 'object' [10 / Oct / 2019 15:18:17] "POST / PermissionUpdateView / 3 / HTTP / 1.1" 500 "and don't let me save with the post help method please, what am I wrong? viws.py class PermisoUpdateView(UpdateView): model = Permiso second_model = Users template_name = 'plantillas/permisos_update.html' form_class = Permiso_update second_form_class = Users_up def get_context_data(self,*args,**kwargs): context =super(PermisoUpdateView, self).get_context_data(**kwargs) pk = self.kwargs.get('pk', 0) p = self.model.objects.get(id=pk) u = self.second_model.object.get(id=p.usuario_id) if 'form' not in context: context['form'] = self.form_class(instance=p) if 'form2' not in context: context['form2'] = self.second_form_class(instance=u) context['id'] = pk return context def post(self, request,*args, **kwargs): self.object = self.get_object id_Permiso = kwargs['pk'] per = self.model.objects.get(id=id_Permiso) us = self.second_form_class.object.get(id=per.usuario_id) form = self.form_class(request.POST, instance=per) form2 = self.second_form_class(request.POST, instance=us) if form.is_valid and form2.is_valid and request.is_ajax(): form.save() form2.save() return JsonResponse({'status':'true', 'msg':'Datos procesados correctamente'})#retornando JSon en jsConsole else: return JsonResponse({'status':'false', 'msg':'Datos procesados incorrectamente'})#retornando respuesta en jsConsole -
Add context variable as an aggregate or annotate of 2 cols in CBV's get_context_data()
I want to return total value as revenue variable in get_context_data method of ClassBasedView. I also want to return another operation: total - shipping_cost as revenue_no_shipping_cost variable in context. I've tried: from django.db.models import F, Sum class OrdersListView(PermissionRequiredMixin,ListView): model = Order permission_required = 'is_staff' template_name = "order/revenue.html" paginate_by = 10 def get_queryset(self): filter_month = self.request.GET.get('filtromes', '0') if filter_month == "0": return Order.objects.filter(status = 'recibido_pagado') else: return (Order.objects .filter(created__month=filter_month, status = 'recibido_pagado')) def get_context_data(self, **kwargs): context = super(OrdersListView, self).get_context_data(**kwargs) qs = kwargs.pop('object_list', self.object_list) order = self.request.GET.get('orderby', 'created') context = {} revenue = qs.aggregate(revenue=Sum('total')) revenue_no_shipping = qs.annotate(revenue_no_shipping=F('total') + F('shipping_cost')) context['revenue'] = revenue context['revenue_no_shipping'] = revenue_no_shipping context['filtromes'] = self.request.GET.get('filtromes', '0') context['orderby'] = self.request.GET.get('orderby', 'created') context['category'] = "catalogo" return context But in template, I'm getting: For revenue: {'revenue': Decimal('42')} #is 42.00 For revenue_no_shipping: <QuerySet [<Order: 58>]> #Should be 25.00 -
django.core.exceptions.ValidationError: ["'_auth_user_id' value must be an integer."] error on Django
as for the title I have this problem with validation in Django. This error occours when i Logout, it seems like the system is looking for the user id but, because i clear the session with the log out(not sure anyway if this is right, I use django auth for the login/logout system), it can't find any user with same id in the session and is giving me this error. So I tried removing all the user call i have in the code but it is still not working at all. Here as follow the full error log. Internal Server Error: / Traceback (most recent call last): File "C:\Users\gello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\__init__.py", line 941, in to_python return int(value) ValueError: invalid literal for int() with base 10: '_auth_user_id' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\gello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\gello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\gello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\gello\Desktop\Projects\buyit\home\views.py", line 12, in index return render(request, "index.html", {"products": products, "product_reviews": product_reviews}) File "C:\Users\gello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\gello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader.py", line 62, in render_to_string return …