Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx ERR_SSL_PROTOCOL_ERROR
Need help setting up Ngin. I need to set up https for my service This is the service configuration events {} http { server { listen 80; listen \[::\]:443 ssl; server_name example.com localhost; # SSL-сертификаты ssl_certificate /etc/nginx/certs/example.crt; ssl_certificate_key /etc/nginx/certs/example.key; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; keepalive_timeout 70; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_stapling on; ssl_trusted_certificate /etc/nginx/certs/ca.crt; resolver 8.8.8.8; location / { proxy_pass http://example_app:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } } This is the docker-compose.yml configuration version: '3' networks: imggen_network: driver: bridge services: nginx: container_name: nginx image: nginx:latest ports: - "80:80" - "443:443" volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro - ./nginx/certs:/etc/nginx/certs:ro depends_on: - example_app networks: - imggen_network The service works on port http://127.0.0.1:8000/, but when accessing https://127.0.0.1:8000/ it gives an error This site cannot provide a secure connection. Site 127.0.0.1 sent an invalid response. Run network diagnostics in Windows. ERR_SSL_PROTOCOL_ERROR The service works on port http://127.0.0.1:8000/, but when accessing https://127.0.0.1:8000/ it gives an error This site cannot provide a secure connection. Site 127.0.0.1 sent an invalid response. Run network diagnostics in Windows. ERR_SSL_PROTOCOL_ERROR -
Getting Docker-Compose file working on ubuntu
I have a django project running correctly with docker compose on my mac, but I want to get the docker-compose working on my linux ubuntu machine. When I run the docker-compose file on my mac everything works fine; however, I run into an issue on ubuntu where it says that port 5432 is in use. This is because: "On your Mac, you can run PostgreSQL on the host machine and use the same port (5432) without conflict because Docker for Mac uses a feature called "host networking" by default. With host networking, containers share the network stack with the host machine, allowing them to access services running on the host directly. In the case of your Docker Compose file, when you run it on your Mac with PostgreSQL running on the host on port 5432, the container can still access the PostgreSQL service on the host because it shares the network stack. The container's PostgreSQL service listens on the same port inside the container (5432) as the host's PostgreSQL service. So, when your Django application inside the container tries to connect to the database at localhost:5432, it effectively connects to the PostgreSQL service running on the host." So I modify … -
how to shrink my celery-worker docker image?
I am running Django application on ECS and I am trying to optimize the size of Docker containers. Below are my Dockerfiles that I am using to build django-app, celery-worker and celery-beat services on ECS. CMD are inserted in ECS task definition. The problem I have is that the size of celery worker container exceeds 1 GB and with enabled autoscalig it takes around 5 minutes to create new task in ECS service, to build and deploy the container. It is not a problen when deploying whole application but it is probmematic when I want to autoscale my app and I need to wait 5 minutes for new task so celery can run another tasks. Concurrency is set up to 3 and I cannot put higher number because my tasks are heavy and last around an hour (each). How can I optimize the size of celery Dockerfile and the way in is being built and deployed on ECS? Dockerfile for Django: FROM python:3.9-slim ENV DockerHOME=/home/app/web ENV GitHubToken=ghp_*** RUN mkdir -p $DockerHOME WORKDIR $DockerHOME ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip COPY . $DockerHOME RUN apt-get update && apt-get install -y git RUN pip install git+https://github.com/ByteInternet/pip-install-privates.git@master#egg=pip-install-privates # … -
My Home page doesn't work in Django and react app
I am working on a project with Django and React and I have already deployed it in Render but my Home page doesn't work. The screen is all white. The others pages work correctly. This is my urls.py in core: urlpatterns = [ path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), path('auth/', include('djoser.social.urls')), path('api/blog/', include('apps.blog.urls')), path('api/category/', include('apps.category.urls')), path('api/contacts/', include('apps.contacts.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] And this is my Home route in React: <Route path="/" element={<Home />} /> I have tried everything including Chat GPT but I can't find the error. When I was working on debug mode the Home page worked correctly. -
Permission denied for urls paths Django + Apache + mod_wsgi
I have configured a Dajgno application to be hosted in an Apache server using mod_wsgi. I have successfuly opened the home page, but haven't been able to open others urls paths. For instance, if I try to access /pop/, it returns 403 forbidden error. Here are my code: urls.py from django.contrib import admin from django.urls import path, include from dashboard import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', views.NewView.as_view()), path('pop', views.PopView.as_view()), ] urlpatterns += staticfiles_urlpatterns() wsgi.py import os import sys from django.core.wsgi import get_wsgi_application path = '/home/andremou/DashboardUnicamp/unicamp/unicamp' if path not in sys.path: sys.path.append(path) #os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'unicamp.settings') os.environ["DJANGO_SETTINGS_MODULE"] = "unicamp.settings" application = get_wsgi_application() .conf file <VirtualHost *:443> ServerAdmin [CENSORED] DocumentRoot [CENSORED] #ServerName [CENSORED] ServerName [CENSORED] #ServerAlias [CENSORED] ServerAlias [CENSORED] RewriteEngine On RewriteCond [CENSORED] RewriteCond [CENSORED] RewriteRule [CENSORED] Alias /dashboardteste/ /home/andremou/DashboardUnicamp/unicamp/unicamp/ # Executar o Django como usuario apache SuexecUserGroup apache apache #Header set X-Frame-Options SAMEORIGIN <Directory /home/andremou/DashboardUnicamp/unicamp/unicamp> <Files wsgi.py> Order deny,allow Allow from all Require all granted </Files> </Directory> # Certificados TLS/SSL SSLEngine on SSLCertificateFile /etc/httpd/conf.d/ssl/moodle.pem SSLCertificateKeyFile /etc/httpd/conf.d/ssl/moodle.key SSLCertificateChainFile /etc/httpd/conf.d/ssl/moodle_chain.crt WSGIScriptAlias /dashboardteste /home/andremou/DashboardUnicamp/unicamp/unicamp/wsgi.py WSGIDaemonProcess unicamp python-home=/home/andremou/DashboardUnicamp/my_env python-path=/home/andremou/DashboardUnicamp/unicamp WSGIProcessGroup unicamp WSGIApplicationGroup %{GLOBAL} </VirtualHost> The structure of my files: home |-andremou |-DashboardUnicamp |-my_env |-unicamp ||-dashboard | |-migrations | |-static | |-templates … -
django dynamic URL routing
so i have been trying to use single template to display multiple content for different pages in django. i have an main app called websiteappand main template as index.html if i click a link in main page it goes to another app called moviedetailthat contains a template called movie-detail. html from that template i want to display various content according to the link clicked in main page i have been trying so long i didn't find any answer what do i need to change and how i have tried int:pk and objects.get(id=pk) it doesn't work -
how can i bookmark songs in my django project with rest framework and js
I've been trying to put the favorites feature for days with django rest framework and javascript api fetch in my lyrics project but without success all the methods I'm trying don't work please help me I'm a beginner in javascript, even in api with django too. here is what I tried, where did I mow apiviews.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status,permissions from rest_framework.viewsets import ModelViewSet from rest_framework.viewsets import ReadOnlyModelViewSet from rest_framework.permissions import IsAuthenticated from rest_framework import generics from rest_framework.response import Response from rest_framework import viewsets, status from rest_framework.decorators import action from .serializers import SongSerializer from .models import Song, User from .models import Song, Favorite class FavoritesongView(APIView): serializer_class = SongSerializer queryset = Song.objects.all() @action(detail=True, methods=['post'], permission_classes=[IsAuthenticated]) def favorite(self, request, id): song = self.get_object() user = request.user if user not in song.favorited_by.all(): song.favorited_by.add(user) song.save() return Response({'status': 'favorited'}) @favorite.mapping.delete def unfavorite(self, request, id=None): song = self.get_object() user = request.user if user in song.favorited_by.all(): song.favorited_by.remove(user) song.save() return Response({'status': 'unfavorited'}) api_urls from django.contrib import admin from django.urls import path from favorites.apiViews import FavoritesongView urlpatterns = [ path('songs/<int:id>/favorite/', FavoritesongView.as_view()) ] Js file function addToFavorites(songId) { fetch(`/api/songs/${songId}/favorite/`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('token')}` } }) .then(response … -
HTMX tags not activating when using locally-stored copy of source code in Django project
I have a Django project where I'm using HTMX to set up "cascading" SELECT widgets (i.e. the options listed in SELECT #2 are modified based on the user option from SELECT #1). I've confirmed that the HTMX tags in SELECT #1 are triggering as expected when I put this line in the HTML template header to pull in the HTMX code from their web site: <script src="https://unpkg.com/htmx.org@1.9.2" integrity="sha384-L6OqL9pRWyyFU3+/bjdSri+iIphTN/bvYyM37tICVyOJkWZLpP2vGn6VUEXgzg6h" crossorigin="anonymous"></script> Specifically, I can confirm the event is triggering because at this point the corresponding view for the target (create_itemid_2) is just a stub, and I see the printed message in my Powershell console. def create_itemid_2(request): print('HTMX event fired') context = {} return render(request,'create_itemid_2.html',context) So now I want to pull down the code, and use it locally in my Django project, so I'm not dependent on the external resource. The problem is, after I've done that, the event never triggers. I can even see the js file being successfully retrieved in my console (HTTP status 200, then 304 after that), but still the event never triggers. [14/Jun/2023 08:05:05] "GET /newitemid/ HTTP/1.1" 200 1652 [14/Jun/2023 08:05:05] "GET /static/htmx/htmx.min.js HTTP/1.1" 200 361101 [14/Jun/2023 08:09:50] "GET / HTTP/1.1" 200 515 [14/Jun/2023 08:09:52] "GET /newitemid/ HTTP/1.1" … -
How to optimize the filtering of queryset in ModelViewSet
I'd like to know if it's possible to optimize the following code (especially the part when event_wmode is passed as a parameter) class MessageViewSet(viewsets.ReadOnlyModelViewSet): permission_classes = (permissions.DjangoModelPermissions,) serializer_class = MessageSerializer filter_backends = [ DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter, ] filter_fields = ["device", "date", "variable", "sensor"] search_fields = [ "variable", "device__name", ] ordering_fields = "__all__" ordering = ["device", "-date"] def get_queryset(self): if self.request.user.is_superuser: return Message.objects.all() else: return Message.objects.filter(device__users=self.request.user) def list(self, request, *args, **kwargs): if not self.request.GET.get("event_wmode"): return super().list(request, *args, **kwargs) else: # remove duplicate wMode in result queryset = self.filter_queryset(self.get_queryset()) currentwMode = None excluded_pks = [] for item in reversed(queryset): if item.variable == "wMode": if item.message not in ["1", "4", "8", "9", "10"]: excluded_pks.append(item.pk) continue if currentwMode == None: currentwMode = item.message continue elif currentwMode == item.message: excluded_pks.append(item.pk) else: currentwMode = item.message queryset = queryset.exclude(pk__in=excluded_pks)[:100] # paginate the result page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) The purpose of this mode is to remove unnecessary wMode. What I want is to keep only the wMode when it changes, and only the values 1 4 8 9 and 10 (for variable=wMode only). Let's imagine I have this message sequence: [{ message: … -
django only show the highest value of m2m in template
Hej! I have a table view with multiple columns one of them contains a m2m field from the model. I dont want all values (if multiple values/entries are given for that m2m) only the highest. Example: 1890 bonbons 30 bonbons 300000 bonbons i only want to show the 300000 bonbons in that cell and not all 3 values. {% for candymarket in mall %} <td> {% for bon in candymarket.bonbon_color.all %} {{bon.value}} | {{bon.color}} {% endfor %} </td> {% endfor %} How can I filter inside the template? I still want to be able to get all values in a detail view. Is there something like {% if bon.value|length > 200 %} only with is max? Any help or link to a documentation is appreciated! :) class CandyMarket(models.Model): name = models.CharField( max_length = 500, unique = True ) bonbon= models.ManyToManyField( Bon, verbose_name = "BON", through = "BonForCandyMarket", blank = True, related_name = "bonbon_in_market" class BonForCandyMarket(models.Model): market= models.ForeignKey( Candymarket, on_delete = models.PROTECT, related_name = "bonbon_color" ) bon= models.ForeignKey( Bon, on_delete = models.PROTECT, related_name = "market_with_bonbon" ) value= models.PositiveSmallIntegerField( blank=True, null=True ) class Bon(models.Model): description_english = models.CharField( max_length = 500, unique = True ) -
Django admin url shows "table or view does not exist" while using oracledb
I am very beginner to django & oracle. Trying to connect oracledb from django using hr schema. Data is availabe to django model from database but it shows "table or view does not exist" when browsing admin url. I have the following tables on the database. DJANGO_MIGRATIONS DJANGO_CONTENT_TYPE AUTH_PERMISSION AUTH_GROUP AUTH_GROUP_PERMISSIONS AUTH_USER AUTH_USER_GROUPS AUTH_USER_USER_PERMISSIONS DJANGO_ADMIN_LOG Does django automatically migrate admin to the oracle database or I need to create them manually? -
Issues running Django Channels in Docker container
I am running Django application in Docker container. The command I use to start Django application is daphne -b 0.0.0.0 -p 8000 main.asgi:application. However, I get an error that ModuleNotFoundError: No module named 'main'. Here is my asgi.py file: import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings') django.setup() from channels.auth import AuthMiddlewareStack from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from modules.chat.urls import ws_urlpatterns as chat_ws_urlpatterns application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack(URLRouter(chat_ws_urlpatterns)) }) What is wrong in my asgi.py configuration? -
i keep getting the error "Parameter "form" should contain a valid Django Form." when i try to create form from class in models
i need to add comment to class Course and when i try to make form from the class it show this error models.py class Course(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=7, decimal_places=2) period = models.DecimalField(max_digits=5, decimal_places=2) instructor = models.CharField(max_length=50) description = models.TextField(max_length=250) image = models.ImageField(upload_to='courses/') category = models.ForeignKey( Category, on_delete=models.CASCADE, blank=True, null=True) slug = models.SlugField(max_length=100, blank=True, null=True) user = models.ForeignKey( User, on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateField(auto_now_add=True) comment = models.ManyToManyField(Comment, related_name=("user_comment")) def __str__(self): return self.name forms.py class CommentForm(forms.ModelForm): class Meta: model = Course fields = ['comment'] views.py def comment_add(request): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): myform = form.save(commit=False) myform.user = request.user myform.save() return redirect('home:home') else: form = CommentForm cont = {'form': form} return render(request, 'desc.html', cont) desc.html <form method="post" class="pt-4"> {% csrf_token %} {% bootstrap_form form %} <button class="btn btn-info text-white w-100" type="submit">comment</button> </form> i tried to solve the error but i can't -
Save Django attachments from a form
Good morning, I would greatly appreciate your help, I am starting to use Django and I am making a web application that allows workers in a job to attach their documentation (files) through a form. The problem is that at the moment of pressing the submit of the form with the attached files, these are not saved, however, the name and other fields of the Charfield type are saved correctly. The only way to save the files is to attach them from the admin portal, but the idea is that each user enters from a url generated with their id that will be sent by email. Also, the files should be saved with the naming (DSR_”rut”-”name”-”filename (form label)”-0-”extension), but I still can't configure the naming of the file name instance. file, according to the label of the form. models.py: class Candidato(models.Model): nombre = models.CharField(max_length = 70, null=True, blank=True) rut = models.CharField(max_length = 10, primary_key=True) correo = models.EmailField(null=True, blank=True) centro_de_costo =models.CharField(null=True, blank=True, max_length =30, choices = cc) estado = models.IntegerField(null=True, blank=True) imagen = models.ImageField(upload_to=upload_directory_name, null=True, blank=True) certificado_antecedentes = models.FileField(upload_to=upload_directory_name, null=True, blank=True) hoja_de_vida_conductor = models.FileField(upload_to=upload_directory_name, null=True, blank=True) certificado_residencia = models.FileField(upload_to=upload_directory_name, null=True, blank=True) certificado_afiliacion_afp = models.FileField(upload_to=upload_directory_name, null=True, blank=True) certificado_afiliacion_salud = models.FileField(upload_to=upload_directory_name, null=True, blank=True) … -
Create new column in the existing table that has value as other column in sql using django ORM
I want to add new column in existing table that cannot be null and should have value as other column in the table. My attempt: In my django app models, I have added the new field and migrated using migrations: order_id = models.IntegerField(null=True) Ran the below sql query in database Update order_data_table SET order_id=id Again removed null=True from models so as to set it as non-nullable field and migrated Is there a better way to do? -
Search based application using Elasticsearch
I want to make search based application using python and elasticsearch. I want to create web application for this i will python but which framework i should use Django or Flask i don't know. -
Reliable django-river alternatives?
I like the workflow functionality that django-river provides, but its performance is inappropriate and occasionally it fails to find the next available choices. Do you know any fast and reliable django-river alternatives that would use Python code instead of database relations for workflow states? -
Converted PDF is downloadable on both mobile (375px) and lg devices (1024px) but it is not visible on mobile devices. It is not clickable on mobile
This is my views.py to convert html template to pdf from datetime import datetime from io import BytesIO import os from django.conf import settings from django.http import HttpResponse from frontend.views.task_shifts import valid_task_date from frontend.views.utils import * from django.contrib.auth import logout from django.shortcuts import redirect, render from django.contrib.auth import logout from xhtml2pdf import pisa from django.template.loader import get_template from django.contrib.auth.decorators import login_required def render_to_pdf(template_src, context_dict): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf_path = os.path.join( settings.BASE_DIR, 'pdf_files', 'Rating_report.pdf') pisa_status = pisa.CreatePDF(html, dest=result) if pisa_status.err: return HttpResponse('We had some error') with open(pdf_path, 'wb') as f: f.write(result.getvalue()) return pdf_path @login_required(login_url='login_user') def get_pdf(request): if request.user.is_authenticated == False or request.session.get('station_code') is None or request.session['station_code'] is None: logout(request) return redirect("login_user") if (request.method == 'POST'): date1 = request.POST.get('date') date = datetime.strptime(date1, '%Y-%m-%d').date() context = {'date': date } pdf_path = render_to_pdf('front/pdf/pdf.html', context) pdf_file = os.path.basename(pdf_path) with open(pdf_path, 'rb') as f: response = HttpResponse(f.read(), content_type='application/pdf') response['Content-Disposition'] = f'inline; filename="{pdf_file}"' return response else: messages = [] messages.append('Enter date to see pdf') return render(request, 'home.html', {'messages': messages}) and my html template is {% load custom %} {% load static %} {% block body %} <h1> pdf demo</h1> <p>for : {{date}}</p> {% endblock %} and the form to submit the … -
django.db.utils.DataBaseError: database disk image is malformed
I am getting the above error in my terminal. My db.sqlite3 file is explicitly re-assigned to plain text. I want to fix that thing. Please guide me regarding this issue. This error is with the database file. This is displaying me a warning in the db.sqlite3 file as "This file is explicitly re-assigned to plain text". -
Image not shown in debug for false in django
I want to run always in debug=false in django. However, it works only when i turned to debug to true. Otherwise not. In setting.py DEBUG = False also, in setting.py STATIC_URL = '/static/' STATIC_ROOT = '/static/' MEDIA_URL = '/media/' if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] else: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') In main urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include('mysite.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have directory of media, static, staticfiles in the directory where manage py is located. If i put code exactly in apache will my code works. P.S In development also i want to fix debug as false always. -
passing websocket messages from django consumers.py to html, then respond back to backend
The problem i'm having is The only way i can find to pass messages from consumers.py which recieves the message to index.html where its needed is with this line. async_to_sync(self.channel_layer.group_send)( self.room_group_name, {"type": "chat_message", "message": message} ) this sends the message to index.html AND back to my backend... i dont want it to bounce the message back to my backend. how can i send a response back to my backend from index.html because i need to send info on what the user has entered into an in? here is an example of how the system currently works how websockets currently work and heres how i want them to work how i want websockets to work how can i stop bouncing the message back to my backend and still pass the message onto my html, then respond from my html back to my backend? ################ below is the code js in my index html const colorSocket = new WebSocket( "ws://" + window.location.host + "/ws/endpoint/chat/" ); colorSocket.onopen = function() { console.log("Connected! (" + this.readyState + ")"); }; colorSocket.onmessage = function(event) { let data = JSON.parse(event.data); console.log(data.message); // etc........... } consumers.py import json import random from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class … -
Django template: Set same data in tables cell matching to header
I have below view.py c0 = date.today().replace(day=16) c1 = c0 - relativedelta(months=1) c2 = c0 - relativedelta(months=2) c3 = c0 - relativedelta(months=3) c4 = c0 - relativedelta(months=4) c5 = c0 - relativedelta(months=5) datadump = data.objects.filter(user=request.user,ret_prd__gte=datetime.now() - relativedelta(months=5)).order_by('type','user','-ret_prd') return render(request,'rethome.html',{'datadump':datadump,'c0':c0,'c1':c1,'c2':c2,'c3':c3,'c4':c4,'c5':c5}) And below template code: {% regroup datadump by type as ret_type %} {% for type in ret_type %} <h1>{{ type.grouper }}</h1> <table> <tr> <th>user</th><th>{{c0|date:'M Y'}}</th><th>{{c1|date:'M Y'}}</th><th>{{c2|date:'M Y'}}</th><th>{{c3|date:'M Y'}}</th><th>{{c4|date:'M Y'}}</th><th>{{c5|date:'M Y'}}</th> </tr> {% regroup type.list by user as userlist %} {% for user in userlist %} <tr><td>{{user.grouper}}</td> {% for data in user.list %} <td>{{user.ret_prd}}</td> {% endfor %} </tr> {% endfor %} </table> {% endfor %} I am getting below result: Is there any way I can show for each user row cells under same column heading? -
I created a new Django project but I did not get a new one. Although I create new ones, it gives me one of my previous projects
enter image description hereenter image description here These two images were not the same project but they were giving me the same project. They were totally new projects. But when I run the project they did not return me a new Django project as usual Working on project. Once remembered create virtual environment and try to create. But I think I, I could not create virtual env properly. After that I am able create new project on django. All new projects will be created the same project as above. -
How to initialize a custom model field for testing?
I've got a custom model field class VaultField(CharField): which is used to store values in Vault. Used like so: class MyClass: secret = VaultField(max_length=200, blank=True) The custom field is using self.model.__name__. My plan was to unit test this field by initializing it and calling the methods (from_db_value, to_python, etc.): field = VaultField(blank=True) field.to_python() But because the field is using self.model it's erroring on: AttributeError: 'VaultField' object has no attribute 'model' How do I get a model into the VaultField? This does not work: VaultField(max_length=200, blank=True, model=MyModel) -
How to get Redis cache info from requests_cache
I'm using requests_cache library with Redis and i want to know how to get info from redis cache. My task is to send info from 3rd party API json in Redis with celery every 5 minutes and get info from redis in my view. How can i do that? celery.py @app.task def get_project_budget(): backend = requests_cache.RedisCache(host=config('REDIS_HOST'), port=config('REDIS_PORT'), password=config('REDIS_PASSWORD'), ttl_offset=259200) session = requests_cache.CachedSession('project_cache', backend=backend, stale_if_error=True, expire_after=360) url = 'http://3rd_party_api.com' response = session.get(url) views.py import requests_cache class ProjectList(ListView): def get_queryset(self): # How can i call Redis cache there by name queryset = [] return queryset