Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Wagtail return HTTP 500 Internal server error
I'm deploying my Wagtail application to production but could not get it to work. I'm following this tutorial https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04. The website is work as expected on my server when using development settings, as soon as I changed to production it won't work. On production, I'm only able to access the admin and sitemap URL. production.py from .base import * with open('/etc/secret_key.txt') as f: SECRET_KEY = f.read().strip() DEBUG = False try: from .local import * except ImportError: pass DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'name', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', } } # SECURITY WARNING: define the correct hosts in production! INTERNAL_IPS = ("127.0.0.1") ALLOWED_HOSTS = ['*'] nginx # Redirect unencrypted traffic to the encrypted site server { listen 80; server_name domain www.domain IP; return 301 https://domain$request_uri; } server { client_max_body_size 20M; listen 443 default ssl; server_name domain.com IP; keepalive_timeout 70; ssl on; ssl_certificate /etc/nginx/certs.pem; ssl_certificate_key /etc/nginx/privkey.pem; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/projectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sherpa Group=www-data WorkingDirectory=/home/user/projectdir ExecStart=/home/user/projectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ project.wsgi_production:application [Install] WantedBy=multi-user.target urls.py … -
How to read a compressed string value from mysql table using django orm?
I got a field in mysql table which stores compressed string value, so when i tried using objects.all from django it throws DjangoUnicodeDecodeError exception as it cannot decode the compressed string, so i used the objects.raw('select uncompress(field') it executes fine, but when i access the queryset object using object.field it still throws the same DjangoUnicodeDecodeError error, why the queryset is not storing the uncompressed values ? I'm using Python 2.7.5 Django 1.11.14 Mysql Server version: 5.5.60-MariaDB MariaDB Server -
Django mail not sending the email in proper format?
I want to send the email from the Django framework to the user. I design the following script. when I run this script on the local system on python ide it is sending the mail to a user with SUBJECT and message body. But same code is not working in the django framework. it is not sending SUBJECT and the message body it is sending only last line of the massage. import sys import calendar import smtplib import shutil import os import re from datetime import datetime, timedelta import mysql.connector from string import Template import smtplib sender = 'mywebsite@organization.com' receivers = ['vishal.jadhav@autodesk.com'] message = """From: From Person <from@fromdomain.com> To: To Person <myemail@organization.com> Subject: Virus arm attack on SMTP e-mail test This is a test e-mail message. """ try: smtpObj = smtplib.SMTP('email.organization.com') smtpObj.sendmail(sender, receivers, message) print("Successfully sent email") except SMTPException: print("Error: unable to send email") EXPECTED RESULT which is getting when email sends from the local system. Subject Showing as : SMTP e-mail test Massage body showing as: This is a test e-mail message. Thanks Actual RESULT when mail sends from Django framework *subject is missing and message body printing only Thanks Massage body showing as: Thanks -
How to get ChoiceField data based on current user
I have a model StaffProfile.while creating a form for Visiti want to get staff_user data(Based on current user) to that ChoiceField (to_meet). models.py class StaffProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_profile") staff_user = models.ManyToManyField(User, null=True, blank=True, related_name="staff_user") class Visit(models.Model): name = models.CharField(max_length=200, name="name") gender = models.CharField(choices=GENDER_CHOICE, max_length=1, name="gender") mobile = models.CharField(max_length=18, default="", name="mobile") to_meet = models.ForeignKey(User, on_delete=models.CASCADE) forms.py class VisitForm(forms.ModelForm): to_meet = forms.ChoiceField() class Meta: model = Visit fields = ("__all__") -
Middleware presence couldn't block request from hitting the routes
I have written the middleware for Session Management, What I observe is that the Middleware is working fine up to the expectations when it comes to redirection to the desired page as per the session state. But the problem is that the routes which I have written only to be hit when the session is active, are still getting hit irrespective of session state even after the redirection. E.g: The secure home route should only be accessible when the session is set, Middleware doing their job by redirecting the page to Login, But In the server, I can see the Home route was still hit I could write again the block of code like if sessionActive: // Code Goes Here Which Should Run For Active Session State else: // Return with Forbidden Message I'm assuming Why should I write above piece of code when the middleware is in place? PFB, the code of Middleware: # Middleware Class to Handle Session & JWT default operations # Usage: Protect Function by mentioning @SessionHandler over the secured functions # Written By: Thrinadh <thrinadh@wominternal.com> # Date Written: Jan 1, 2019 from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import redirect, render from libraries.PostgreSQLConnector import PostgreSQLConnector … -
'Not Found: /' error when linking app urls.py to project's urls.py
I'm having trouble linking to an app's urls.py file in Django first_project urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('first_app', include('first_app.urls')), ] first_app urls.py from django.conf.urls import url from first_app import views urlpatterns = [ url('', views.index, name='index'), ] Error Django version 2.1.7, using settings 'first_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Not Found: / [31/Mar/2019 14:28:54] "GET / HTTP/1.1" 404 2038 -
Why the url works with parameter pk and not pk2?
When I try to send pk2 or any other arguement, it raises an AssertionError. What I mean is this that the url path('grade/<str:pk>/', IndividualGrade.as_view(), name="get-grade") doesnt gives me an error while the one below gives error: path('grade/<str:pk2>/', IndividualGrade.as_view(), name="get-grade"). My view is fairly simple as below: class IndividualGrade(generics.RetrieveUpdateDestroyAPIView): ''' PUT/GET/DELETE grade/{grade:pk}/ ''' queryset = Grade.objects.all() serializer_class = GradeSerializer def put(self, request, *args, **kwargs): try: g1 = Grade.objects.get(grade=kwargs["pk"]) serializer = GradeSerializer(g1, data=request.data) flag = 0 except Grade.DoesNotExist: # Create a new grade if a grade doesnt exist g1 = Grade.objects.get(grade=kwargs["pk"]) serializer = GradeSerializer(g1, data=request.data) flag = 1 if serializer.is_valid(): # call update/create here else: return Response(serializer.errors) return Response(serializer.data, status=status.HTTP_200_OK) I realized pk2 in the url works if I write my own get function (tried in another view), but I don't know how to fix this without writing my own get. While this have been discussed here. But I am still not sure how to fix it without writing my own get. -
Saving images uploaded through ImageField
I am trying to set up a webapp that accepts image uploads from a user, using ImageField, but I cant seem to figure out how to save the uploaded image. My media folder is empty even though there doesnt seem to be any errors. Went through a lot of tutorials to no avail. I get the basic concept, create a form, model, set media in settings.py, handle upload in views, and I am getting a working view with a image upload form, but uploading an image does not save. settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns = [ path('embed/', embed, name = 'embed'), path('success', success, name = 'success'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) forms.py class imguploadform(forms.ModelForm): class Meta: model = imgupload fields = ['title', 'image'] models.py class imgupload(models.Model): title = models.CharField(max_length = 20) image = models.ImageField(upload_to="media/images/", default = None) def __str__(self): return self.title views.py def embed(request): if request.method == 'POST': form = imguploadform(request.POST, request.FILES) if form.is_valid(): newimg = imgupload(title=request.POST['title'], image=request.FILES['image']) newimg.save() return redirect('success') else: form = imguploadform() return render(request, 'webapp/imgupload.html', {'form' : form}) def success(request): return HttpResponse("Successfully uploaded") Another thing to note, the admin panel does not show the image model -
Custom Dependent Dropdown in Django
I am trying to implement two dropdowns in my registration page with custom fields that prompt a user to select their phone brand and the specific model of their phone. I want to have the phone model dropdown to be dependent of the phone brand dropdown. In other words, if I select that I have an Apple phone, the phone model dropdown should only give me the options Iphone 6, Iphone 7, Iphone 8, etc. So far I have not been able to discover how to do a custom dependent form so I tried starting small and doing one regular dropdown. Unfortunately, I was also unable to do that. To add the regular dropdown I added the following to my models.py from django.db import models PHONES = ( ('samsung','SAMSUNG'), ('iphone', 'IPHONE'), ('oneplus','ONEPLUS'), ('lg','LG'), ) class Phones(models.Model): phone = models.CharField(max_length=6, choices=PHONES, default='iphone') And then adding the following to forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from main.models import Phones class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User, Phones fields = ("username", "email", "phone", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() #saves to db return user … -
How do I access any particular field from my serializer.py file?
I'm making an API on webhook here's my details of the project Models.py from django.db import models from django.utils import timezone from django_hstore import hstore class WebhookTransaction(models.Model): UNPROCESSED = 1 PROCESSED = 2 ERROR = 3 STATUSES = ( (UNPROCESSED, 'Unprocessed'), (PROCESSED, 'Processed'), (ERROR, 'Error'), ) date_generated = models.DateTimeField() date_received = models.DateTimeField(default=timezone.now) body = hstore.SerializedDictionaryField() request_meta = hstore.SerializedDictionaryField() status = models.CharField(max_length=250, choices=STATUSES, default=UNPROCESSED) objects = hstore.HStoreManager() def __unicode__(self): return u'{0}'.format(self.date_event_generated) class Message(models.Model): team_id = models.CharField(max_length=250) team_domain = models.CharField(max_length=250) channel_id = models.CharField(max_length=250) channel_name = models.CharField(max_length=250) user_id = models.CharField(max_length=250) user_name = models.CharField(max_length=250) text = models.TextField() trigger_word = models.CharField(max_length=250) def __unicode__(self): return u'{}'.format(self.user_name) serializer.py from rest_framework import serializers from slack.models import WebhookTransaction, Message class WebhookTransactionSerializer(serializers.ModelSerializer): class Meta: model = WebhookTransaction fields = '_all__' class MessageSerializer(serializers.ModelSerializer): class Meta: model = Message fields = ['team_id'] Now when I try to access only 'team_id' from the models It's giving me this error return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "slack_message" does not exist LINE 1: INSERT INTO "slack_message" ("team_id", "team_domain", "chan... ^ Now my question is do I have to pass all the field for this to work? IF NOT then how can I access only one field from the list? To give you more insights here are … -
How to commit using git
I am using django(python framework) and i want to Git my project. I have tracked it using cmd (I'm using window 7 ) but unable to commit. '''''''''''''''''''''''''''''''''''' git add -A ''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''' 1- shows the message command prompt displaying after I use commit cmd. -
Concurrent Process Logging in Django
I'm working on a Django-based application that needs to write to a logfile from multiple processes. I've looked at the idea from this answer which details the approach used in the multiprocessing-logging package here. However, I can't seem to find a way to implement it in Django in such a way that avoids throwing this error: PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: /logfile.log -> /logfile.log.1 In my MyApp/settings.py file I have the handler for the logfile configured as such: 'handlers': { .... 'logfile': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': BASE_DIR + "/logfile.log", 'maxBytes': 50000, 'backupCount': 2, 'formatter': 'standard', }, 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers': ['console'], 'propagate': True, 'level': 'WARN', }, 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'MyApp': { 'handlers': ['console', 'logfile'], 'level': 'DEBUG', }, In the part of the application that runs multiple processes, I have the logging configured as such: # Ref: https://github.com/jruere/multiprocessing-logging import logging from multiprocessing_logging import install_mp_handler LOG = logging.getLogger('MyApp') install_mp_handler() ... if __name__ == '__main__': ... with Pool() as pool: pool.map(func, iterable) Notes: This logs to the console fine but seems to … -
How to query to calculate the quantity times the price using Django ORM
I would like to know how to get the total price of: quantity times price in Django ORM, and which variable to use for template to view the value? The post is submitted successfully, but cannot get the total price: this is what I have in my views.py: context={ "tickets": Ticket.objects.all(), "total":Ticket.objects.filter(purchaser=User.objects.get(id=request.session['user_id'])).aggregate(total_cost=Sum(F('price')*F('quantity'), output_field=FloatField()) } return render(request, 'first_app/confirmation.html', context) This is in my models.py: from django.db import models from django.db.models import Sum, Aggregate, F class User(models.Model): first_name=models.CharField(max_length=100) last_name=models.CharField(max_length=100) email=models.CharField(max_length=100) password=models.CharField(max_length=100) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) class Ticket(models.Model): venue=models.CharField(max_length=100) quantity=models.PositiveIntegerField(default=1) price=models.DecimalField(default=25.00, max_digits=10, decimal_places=2, null=True, blank=True) loop=models.CharField(max_length=100) purchaser = models.ForeignKey(User, related_name="purchases", on_delete=models.PROTECT) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) How do you query ORM to get the total quantity * price? Should that query be included before or after you do the "ticket" key in context? Should that query be added the Ticket model field? Each each is hardcoded as $25.00 as shown in models. Thank you, I'd greatly appreciate it! -
Using SQLite3 with Django 2.2 and Python 3.6.7 on Centos7
I am moving my Django code from 2.1.7 directly to the new Django 2.2. The only problem I encountered in my Centos7 development environment was that my local development database (sqlite3) version was incompatible using my Python 3.6.7. The error I was getting from "manage.py runserver" was: django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later I am unable to use another version of Python because this is the maximum supported by AWS elasticbeanstalk. The Python 3.6.7 seems to come with sqlite module of version: >>> import sqlite3 >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.7.17' >>> I use a seperate development account on my local Centos7 workstation and issue pipenv shell to begin my code development and IDE. The only workaround I've found is to manually download SQLite3 autoconf version 3.27.2 and manually compile into that development account home folder using the following commands: wget https://www.sqlite.org/2019/sqlite-autoconf-3270200.tar.gz gzip -d sqlite-autoconf-3270200.tar.gz tar -xvf sqlite-autoconf-3270200.tar cd sqlite-autoconf-3270200/ ./configure --prefix=/home/devuser/opt/ make make install Following that, I have modified my .bashrc to reflect the following: export LD_LIBRARY_PATH="${HOME}/opt/lib" This seems to do the trick when I log back into my devuser account. My app seems to run correctly using my local development database. Python 3.6.7 (default, Dec 5 2018, 15:02:05) [GCC … -
How log in via ajax and refresh the csrf middleware token of the present page in django?
I have an application and i have a global login form, (if you are in some page after login correctly and you want save some form via ajax and this response that you session has expired, the global form appears) the problem is when the session starts, the token changes and the forms on the page no longer work. -
Slow loading Django Admin change/add
I'm making a classic single view application, mapping multiple datasources. Django-admin is paginated so there's no impact when I view my list, the problem is when I want to change/add it is . Using the debug-toolbar my queries look fine, I don't think they take a long time. I tried to use a suggestion here Django admin change form load quite slow and created a form, but this had no impact. When is use exclude = ['e_vehicle','e_product'] it's no surprise that add/change screens load instantly. Any thoughts please model.py class Product_Mapping(Trackable): product_mapping_id = models.AutoField(primary_key=True) s_product = models.OneToOneField(sProduct, on_delete=models.CASCADE) e_fund_manager = models.ForeignKey(eManager, models.DO_NOTHING, blank=True, null=True) e_product = models.ForeignKey(eProduct, models.DO_NOTHING, blank=True, null=True) e_vehicle = models.ForeignKey(eVehicle, models.DO_NOTHING, blank=True, null=True) eManager has around 3K eProduct has around 17K (has fkey to eManager) eVehicle has around 25K (has fkey to eProduct) form.py class MappingProductForm(forms.ModelForm): s_product = forms.ChoiceField(required=False, choices=sProduct.objects.values_list('final_publications_product_id', 'product_name')) e_fund_manager = forms.ChoiceField(required=False, choices=eManager.objects.values_list('e_fund_manager_id', 'manager_name')) e_product = forms.ChoiceField(required=False, choices=eProduct.objects.values_list('e_product_id', 'product_name')) e_vehicle = forms.ChoiceField(required=False, choices=eVehicle.objects.values_list('e_vehicle_id', 'formal_vehicle_name')) class Meta: model = Product_Mapping fields = '__all__' admin.py @admin.register(Product_Mapping) class ChampProductMappingAdmin(admin.ModelAdmin): form = MappingProductForm -
AttributeError: 'NoneType' object has no attribute 'get' at openEdx exchange_token api
I was working on the azure ad login for openEdx mobile app and as mentioned in the title, I got the NoneType response at token_exchange endpoint from azure ad. Azure login have no problem authentication the user from the website login but login from the mobile got 'Service unavailable response' due to the following error log on the server. I suspect the configuration issue but as far as I checked, i only need to set 'SOCIAL_AUTH_OAUTH_SECRETS' from lms.auth.json and 'THIRD_PARTY_AUTH_BACKENDS' and 'ENABLE_THIRD_PARTY_AUTH' from lms.env.json. Please let me know if I miss something out. Thanks in advance Apr 1 12:38:45 edxapp [service_variant=lms][django.request][env:sandbox] ERROR [edxapp 24509] [exception.py:135] - Internal Server Error: /oauth2/exchange_access_token/azuread-oauth2/ Traceback (most recent call last): File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/utils/decorators.py", line 185, in inner return func(*args, **kwargs) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/edx/app/edxapp/edx-platform/openedx/core/djangoapps/oauth_dispatch/views.py", line 57, in dispatch return view(request, *args, **kwargs) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, … -
Django 1.11 - Add condition to field in Admin
Problem I have a model(Challenge) with a many to many relationship to User. The user model has a one to one relationship to Profile. Profile is used to store custom stuff about the user. In the Django admin, create form must only show Users that have the field is_partner True in their Profile model. Can I achieve this without creating another table to store partners? Model class Challenge(models.Model): partners = models.ManyToManyField(User) participants = models.ManyToManyField(Team) details = models.TextField(max_length=512, default=None, blank=True) description = models.TextField(max_length=512, default=None, blank=True) documentation = models.TextField(max_length=512, default=None, blank=True) prize = models.TextField(max_length=512, default=None, blank=True) live = models.BooleanField(default=False) -
Django Rest Framework persist nested data as reference
I working on application where the user can create groups. Each group can have a list of users, as many-to-many relation. I trying to post group data as JSON to save it and keep a list of users. I using a PrimaryKeyRelatedField from DRF to use id of each register as reference, but since I posting a list of them (array actually), the serializer doesn't recognize the references. I have no idea if I posting data in wrong format, or if I have to handle it differently on views/serializer. Models class User(AbstractUser): class Meta: db_table = 'User' managed = True verbose_name = 'Users' verbose_name_plural = 'Users' ordering = ['id'] def __str__(self): return self.email class Group(models.Model): name = models.CharField(db_column='name', max_length=255, null=False) details = models.CharField(db_column='details', max_length=1000, null=True) owner = models.ForeignKey(User, db_column='owner', on_delete=None, null=True) users = models.ManyToManyField(User, related_name='group_user') class Meta: db_table = 'Group' managed = True verbose_name = 'Groups' verbose_name_plural = 'Groups' ordering = ['id'] def __str__(self): return self.name Serializer class GroupWriteSerializer(serializers.ModelSerializer): """ Serializer defined to write operations """ users = serializers.PrimaryKeyRelatedField(many=True, read_only=True) def create(self, validated_data): validated_data['owner'] = self.context['request'].user return super().create(validated_data) class Meta: model = Group fields = ( 'id', 'name', 'details', 'users', ) View class GroupViewSet(viewsets.ModelViewSet): serializer_class = GroupReadSerializer permission_classes = (IsAuthenticated,) … -
How to get the GA Tracker 'linkerParam' using python?
I'm struggling to implement Google Analytics cross-domain tracking. IT should be something like this var param = ga.getAll()[0].get('linkerParam'); var url = mydomain +"/?_ga=" + param; However, due to the architecture of our systems I need to implement this functionality at the server side using python. Any idea of how to do this ? -
How to custom checkboxes and radios in Django using Bootstrap?
I am trying to customize the checkboxes and radios in Django using bootstrap class. However, it has not worked. I already tried to insert the bootstrap class in forms.py with widgets and attrs: custom-control custom-radio custom-control-inline custom-control-input custom-control-label My code: models.py Y = 1 N = 2 YN = ( (Y, 'yes'), (N, 'no'),) class Prop(models.Model): yesorno = models.IntegerField(choices=YN, default=Y, verbose_name='Label...') forms.py class PropForm(forms.ModelForm): class Meta: model = Prop exclude = () widgets={ 'yesorno': forms.RadioSelect( attrs={ 'class':'form-inline custom-control custom-radio custom-control-inline custom-control-input custom-control-label', } ), } template.html <form action="" method="POST">{% csrf_token %} <div class="row form-inline"> {{ form.yesorno }} </div> </form> I would like to use the custom bootstrap style: https://getbootstrap.com/docs/4.3/components/forms/#radios -
The difference between SessionStore and Session object in Django
I have searched online and carefully read Django documentation, but still didn't find an answer. The documentation doesn't really explain when to use SessionStore vs. Session. I had this question when I was trying to modifying request.data in a form. I need to manually modify the session object in database to save the changes made in form. Though I am not sure whether that change is only saved to database or also in cache? I have set the SESSION_ENGINE to both cache and database backend. The cache is RedisCache. CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } SESSION_ENGINE = "django.contrib.sessions.backends.cached_db" If I modify the SessionStore object in form, is still cached? Or is it only saved to database? I would really appreciate if anyone can help me gain a solid understanding of SessionStore and Session objects. -
How to change an existing variable in a django template
Newish to Django here and need some assistance. I have a bool variable empty=True. I passed the variable through views to my template successfully. In the template I have a while loop that includes an if/else statement. I need to be able to change my variable to False if it meets a condition in the if statement. Once I'm out of the loop there is another if/else statement to check in empty is True. I can't seem to figure out how to change a variable in the template. I did try a with statement to change the variable but it didn't work correctly for me because I have to end the with statement before the loop ends. Once the with statement ends, the variable reverts back to its' original value -
Why i have this viewing error only on iOS devices?
I recently created a web site, and everything seems fine on desktop and android mobiles. But the viewing is shooting a trouble on iOS devices. It seems there is something with the padding. I already tried to fix with padding and margin, but is not a good fix and that changes everything on the others devices. I recently created a web site, and everything seems fine on desktop and android mobiles. But the viewing is shooting a trouble on iOS devices. It seems there is something with the padding. I already tried to fix with padding and margin, but is not a good fix and that changes everything on the others devices. Here is an image of the viewing problem -
Saving Pillow Images from PDF to Google Cloud Server
I am working on a Django web app that takes in pdf files and does some image processing to each page of the pdfs. I am given a pdf and I need to save each page into my google cloud storage. I am using pdf2image’s convert_from_path method to generate a list of Pillow Images for each page in the pdf. Now I want to save these images to google cloud storages but can’t figure it out. I have successfully saved these Pillow images locally but I do not know how to do this in the cloud. P.S. I did not include code because I do not think you will benefit from reading my code since I am asking more about how to do it.