Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stored JWT Access Key in Cookie but still can't access API
In my nextjs react app I have this for my login page to store my cookie: axios.post(apiUrl, data) .then((response) => { console.log(response.data) const token = response.data.access Cookies.set('jwtCookie', token, {expires: 1}) Router.push('/') setShowLoading(false); props.history.push('/show/' + response.data._id) }) .catch((error) => setShowLoading(false)); }; I am successfully receiving the access key from my backend and my cookie can be seen in the Application section of Dev tools on Chrome. However, from this point I'm a bit confused as to what to do to allow me to access the page which needs authentication. I have a page where I am making a get request using axios: const user = await axios .get(`http://localhost:8000/api/users/${username}/complete/`, {withCredentials: true}) .then(function(response) { return response.data; }); How do I tell my backend that my access key is stored in a cookie called jwtCookie so that it will let me do the get request? I am using Django Rest Framework and set the permission class on this page to IsAuthenticated. I know there is a gap in my knowledge somewhere, I was hoping someone could help me bridge that gap. Thank you! -
Add template context variable to redirect() call
I am building a job board. This project has a post_job view. After successfully posting a job, the user is redirected to the dashboard view (a page that shows a list of all their posts). def post_job(request): # ... return redirect('dashboard') Is there a way to pass an additional context variable to the dashboard.html template. I.e: return redirect('dashboard', {'success': True}) so that I can then say in the dashboard.html file: {% if success %} Your job has been posted successfully. {% endif %} Thanks for any help. -
Make HTML element be under form textarea
I am trying to customize my admin form by modifying change_form.html. Here's what I have so far: In my forms.py, I have: class ProblemForm(forms.ModelForm): slug = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'link'})) topic = forms.ModelChoiceField(label = "Topic", queryset = Topic.objects.all()) questionToProblem = forms.CharField(label = "Question", widget = CustomAdminPageDown(attrs={'id' : 'mathInputForQuestion', 'onchange':'Preview.Update()'})) solutionToProblem = forms.CharField(label = "Solution", widget = CustomAdminPageDown(attrs={'id' : 'mathInputForSolution'})) class Meta: model = Problem fields = ('questionToProblem', 'solutionToProblem') In my change_form.html, I have: {% extends "admin/change_form.html" %} {% block after_field_sets %}{{ block.super }} <body> <p>Preview is shown here:</p> <div id="MathPreview" style="border:1px solid; padding: 3px; width:50%; height: 20%; margin-top:20px" class="format-paragraph"></div> <div id="MathBuffer" style="border:1px solid; padding: 3px; width:50%; height: 20%; margin-top:20px; visibility:hidden; position:absolute; top:0; left: 0"></div> </body> However, I want the to be under the questionToProblem form, so that when I look at the page, the div is right below the textarea. How would I do that? -
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3
I'm beginner in Django and I want to use MySQL with but when I try to run server with python manage.py runserver I get "django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.". Mac OS; Python version : 3.7.6; Django version : (3, 0, 2, 'final', 0). thank you in advance. -
Which is the Android way of creating data input forms on an App
I am starting with Android and I want to create an application to deal with some data model like for example product and client. I want to allow the user to create and edit products and clients along with some input validation. Which is the Android way of doing that? Do I have to create a layout for each form and data validation by hand? Is there any framework to automatize that hard work? Indeed, I am looking for something like Django which allows you to define data models and then it provides you with a easy way of rendering a form which already includes data validation. -
Django Rest Framework Delete forbidden
I'm currently struggeling with some django rest framework issues. I want to define a delete request for my APIView. This is my view.py: class Employee(APIView): permission_classes = (AllowAny, ) serializer_class = EmployeeSerializer def get(self, request, pk, format=None): employee = EmployeeModel.objects.get(pk=pk) serializer = EmployeeSerializer(employee, many=False) return Response(serializer.data) def delete(self, request, pk, format=None): employee = EmployeeModel.objects.get(pk=pk) employee.delete() return Response(status=status.HTTP_204_NO_CONTENT) And this is my urls.py: urlpatterns = [ path('', views.index, name='index'), path('admin/', admin.site.urls), path('api/auth/', include('rest_framework.urls')), path('api-token-auth/', obtain_auth_token, name='api_token_auth'), path('api/', include(router.urls)), path('api/v1/employeelist/', views.EmployeeList.as_view()), path('api/v1/employee/<pk>', views.Employee.as_view()) ] The get method works fine when I call /api/v1/employee/4 for instance. The UI of the API shows me the allowed methods: GET, DELETE, HEAD, OPTIONS but when I send a delete request I always get the error 403 forbidden. Does anybody know why? -
django how to create model with many possible hours
I work on online ticket booking system. I have the main model representing movie and second model with foreign key to the main model and free standing models.datafield & models.timefield. I was wondering if it is possible to create data model with reference to the main model, including many hour choices within one date ? For example there is an instance 10th November and has five different hour possibilites instead of creating 5 outstandin instances 10th november 15:00, 10th november 16:00 etc. I believe ManyToMany field is not the solution is this case. Correct me if Im wrong. Appreciate for help. -
How do I Send Request to EndPoint on application Startup
I am working on a Django project which has an API endpoint that receives a post request and sends a welcome email to the registered user, currently, I have to use a form to send this request to the endpoint, is there a way to manually read the email and name from my environmental variable and send a request once I run the app the first time? something like EMAIL = 'try@test.com' NAME = 'Bob' I have this stored as an env variable already and here is my current code @require_http_methods(["POST"]) @login_required def add_user(request): if request.is_ajax(): name = request.POST.get('name') email = request.POST.get('email') if not BlueUsers.objects.filter(user_email=email).exists(): newuser_obj = BlueUsers.objects.create(user_name=name, user_email=email) conf_obj = Config.objects.first() if conf_obj: post_url = "{}/priv/create-user/".format(conf_obj.hostname) data = { 'name': newuser_obj.user_name, 'email': newuser_obj.user_email, 'redtree_user_id': newuser_obj.id } headers = {'data-auth-key': conf_obj.authentication_token} try: response = requests.post(post_url, data=data, headers=headers) except: response = None I have been struggling with this -
I want to display the name of the values in django anotate
I am trying to build a mini bank like app where I can do deposits and withdrawals. In one of the templates, I want to sum all the deposits and withdrawals in the model which has the same currency name in common, so I use annotate which works fine. But I couldn't display the name of the currency in the template. Instead, it is displaying 1,2,3 instead of Pound, Dollar, Euro. Here is the relevant part of my model: class Banks(models.Model): currency = models.ForeignKey(Currency, blank=True, null=True) total_deposits = models.IntegerField(blank=True, null=True) total_withdrawals = models.IntegerField(blank=True, null=True) Here is the view: result = Banks.objects.values('currency' ).order_by('currency' ).annotate(total_withdrawals=Sum('total_withdrawals') ).annotate(total_deposits=Sum('total_deposits') ) context = { "result": result, } Here is the template: <table class='table'> <thead> <tr> <th class='aligncenter'>#</th> <th class='aligncenter'>CURRENCY</th> <th class='aligncenter'>TOTAL DEPOSITS</th> <th class='aligncenter'>TOTAL WITHDRAWALS</th> <th class='aligncenter'>BALANCE</th> </tr> </thead> {% for instance in result %} <tr> <td class='aligncenter'>{{forloop.counter}}</td> <td class='aligncenter'>{{instance.currency}}</td> <td class='aligncenter'>{{instance.total_deposits}}</td> <td class='aligncenter'>{{instance.total_withdrawals}}</td> <td class='aligncenter'>{{instance.total_deposits|sub:instance.total_withdrawals}}</td> </tr> {% endfor %} </table> here is the template output: I want to see the currency name under the currency column. Not 1, 2 and 3 -
Django Restframework serializaer is_valid is emptying an extra field
I'm running through a problem where calling serializer.is_valid is wipping out one extra field called images. Actually I've a nested serializer named PostSerializerCommunity which calls another serializer named ImagePostSerializer. All fields in the main serializer are in its default model except by this one images which belongs to another serializer/model. I couldn't find or understand why is it refusing to let em access the images field into the validated_data. It's empty after calls is_valid. Any ideas? file: api/community/views.py @action(methods=['get', 'post'], detail=True) def posts(self, request, pk=None): community = self.get_object() if request.method == 'GET': queryset = Post.objects.filter(community=community) page = self.paginate_queryset(queryset) if page is not None: serializer = PostSerializer(page, many=True, context={'current_user': request.user}) return self.get_paginated_response(serializer.data) serializer = PostSerializer(queryset, many=True, context={'current_user': request.user}) return Response(serializer.data) elif request.method == 'POST': data = request.data.copy() data['author'] = request.user.pk data['community'] = comunidade.pk data['type'] = '' images = data['images'] serializer = PostSerializerComunnity(data=data) serializer.is_valid(raise_exception=True) register = self.perform_create(serializer) if register.text is None: register.text = '' register.save() headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): return serializer.save() class PostSerializerCommunity(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'text', 'author', 'community', 'images') text = serializers.CharField(required=False, source='text') images = ImagePostSerializer(required=False, many=True) author = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), required=True, source='author') def create(self, validated_data): author = validated_data.get('author') text = … -
should fields be statically or dynamically in school system?
i'm trying to make an online management system using django for an institute (school) to store grades , and provide grades online , should fields for entering students data (subjects grade) be statically for each class levels and students or dynamically increase or decrease rows depend on the class levels (using java script) -
Django search page
I'm trying to make a website that lets visitors search for books using another search engine. I have a script that takes a query, and returns some HTML with the results of the search, but I'm struggling to make a front end for this. I am using django because it seemed like the best option when I started, but now I am going in circles and I can't figure out how to make this thing - I'm just getting overwhelmed because the different tutorials and documentation that I'm reading all go into the advanced stuff before I can get the basic thing working. Do I need separate search and results templates? Right now I'm getting the error The view book_search.views.search didn't return an HttpResponse object. It returned None instead. How can I fix this error and/or design this whole thing better? Here's what I have so far (the script that returns the results in html is pull.py): The views and urls are from inside the book_search app. views.py: from django.shortcuts import render from django.http import HttpResponse from . import pull from .forms import SearchForm def index(request): return HttpResponse("Welcome to the index page") def test_search(request): context = {'query': 'test query'} return … -
Django 3 TypeError: context must be a dict rather than set
Please am new to programming and am building a website with django 3.0.2 with a tutorial of django 1.10 but i ran into error , i have searched for possible solutions but couldn't get one here is the output from the terminal Internal Server Error: / Traceback (most recent call last): File "C:\Users\LENOVO\Desktop\TGPB\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\LENOVO\Desktop\TGPB\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\LENOVO\Desktop\TGPB\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\LENOVO\Desktop\TGPB\blog\views.py", line 12, in post_list return render(request, 'blog/post_list.html', {'posts: posts'}) File "C:\Users\LENOVO\Desktop\TGPB\env\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\LENOVO\Desktop\TGPB\env\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\LENOVO\Desktop\TGPB\env\lib\site-packages\django\template\backends\django.py", line 59, in render context = make_context(context, request, autoescape=self.backend.engine.autoescape) File "C:\Users\LENOVO\Desktop\TGPB\env\lib\site-packages\django\template\context.py", line 270, in make_context raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__) TypeError: context must be a dict rather than set. Here is my view from django.shortcuts import render from .models import Author, Tag, Category, Post def index(request): return HttpResponse("Hello Django") #View function to display list of posts def post_list(request): posts = Post.objects.all() return render(request, 'blog/post_list.html', {'posts: posts'}) and my post_list template {% extends "blog/base.html" %} {% block title %} Blogg … -
Control text positioning inside a select box (Select2, django-autocomplete-light)
I have a modelform in which i've added a taggitselect2 widget as part of django-autocomplete-light. This looks up tags from taggablemanager to allow an autocompletion. The autocomplete is working fine - but the alignment of the text inside the select box is off. The text aligns with the bottom of the select box, leaving a big gap between the top of the tag and the top of the select box. Easier with a picture: https://imgur.com/a/WxFMLfF forms.py widgets = { 'tags': autocomplete.TaggitSelect2( url='recordings:recording-autocomplete', attrs={ 'data-placeholder': 'Start typing to autocomplete...', } ....inside def __init__ self.helper.layout = Layout( Row(Column(Field('tags')),css_class='form-row'), I've tried looking at styling options - this is a bootstrap project so ideally i would like the same styling you get with data_role="tagsinput" but if i assign that to the widget i guess it overrides the custom part and i get some broken output. -
Django issue with admin and static folder into runserver response
I have this project with these folders and I want to fix the output of runsever command versus static folder and admin area: (env) [mythcat@desk mysite]$ tree -d . ├── mysite │ ├── __pycache__ │ └── static │ ├── admin │ │ ├── css │ │ │ └── vendor │ │ │ └── select2 │ │ ├── fonts │ │ ├── img │ │ │ └── gis │ │ └── js │ │ ├── admin │ │ └── vendor │ │ ├── jquery │ │ ├── select2 │ │ │ └── i18n │ │ └── xregexp │ └── rest_framework │ ├── css │ ├── docs │ │ ├── css │ │ ├── img │ │ └── js │ ├── fonts │ ├── img │ └── js └── test001 ├── migrations ├── static └── templates └── test001 I add into urls.py : from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns ... urlpatterns = [ ... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += staticfiles_urlpatterns() The settings.py is set with applications and this source code: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates'),] PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ '/home/mythcat/projects/django/mysite/mysite/static/', '/home/mythcat/projects/django/mysite/mysite/static/admin/', '/home/mythcat/projects/django_chart/mysite/mysite/static/admin/css', '/home/mythcat/projects/django/mysite/mysite/static/rest_framework/',] I used this: (env) … -
How do you configure Django 3 to work with MySql 5?
I'm using Mac 10.13.6 and MySql 5.5 (can't upgrade at this time). I have just created a skeleton Django (v 3.0.2)/Python 3.7 app and configured my database setting like so DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'sql_mode': 'traditional', }, 'NAME': 'maps_data', 'USER': 'myuser', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '3306', } } I have used pip to install the mysqlclient ... (env) localhost:maps davea$ pip install mysqlclient Requirement already satisfied: mysqlclient in /Users/davea/Documents/workspace/chicommons/maps/env/lib/python3.7/site-packages (1.4.6) However, when I attempt to run the initial migrations created for me, I get these errors I don't understand ... (env) localhost:maps davea$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Traceback (most recent call last): File "/Users/davea/Documents/workspace/chicommons/maps/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql) File "/Users/davea/Documents/workspace/chicommons/maps/env/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 74, in execute return self.cursor.execute(query, args) File "/Users/davea/Documents/workspace/chicommons/maps/env/lib/python3.7/site-packages/MySQLdb/cursors.py", line 209, in execute res = self._query(query) File "/Users/davea/Documents/workspace/chicommons/maps/env/lib/python3.7/site-packages/MySQLdb/cursors.py", line 315, in _query db.query(q) File "/Users/davea/Documents/workspace/chicommons/maps/env/lib/python3.7/site-packages/MySQLdb/connections.py", line 239, in query _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(6) NOT NULL)' at line 1") The above exception was the direct cause … -
Social Authencation NuxtJS using a backend server
nuxt-auth logs me in with a social network but it doesn’t allow me to exchange the social token with my own token. Can anyone help me in writing a custom flow so that the tokens are exchanged and the strategy gets converted to a local one? -
Username turns into link to user profile Django
Hey guys I tried asking this a few times but don't think I was thorough enough now I have tried so many different ways in the last few days was wondering if someone could point me in the right direction. I want usernames used in the post.post to turn into links for that users profile. right now this is the output I am getting. link to what my post.post looks like as you can see I get the username in the post but its does not show as a link to that users profile it just shows as plain text I would like for @devil to be a link to the users profile ... in the back end though the system does find that @devil is a user in the database it just doesn't show it as a link in my front end template This is my views.py I am using so that the back end finds any user in the post.post def get(self, request): form = HomeForm() posts = Status1.objects.filter(user=request.user).order_by('-id') users = User.objects.all() args = {'form':form, 'posts':posts, 'users':users} return render(request, self.template_name, args) def post(self, request): form = HomeForm(request.POST) users = User.objects.all() if form.is_valid(): post = form.save(commit=False) post.user = request.user … -
How to create multiple images upload in Djnago CreateView?
I have a django project and I created a post operation in this project, so the user will be able to share multiple picture posts. But I have a problem. I can't write multiple image upload function. I looked at a lot of content, but it doesn't work. Either it reports a problem or contex is not sent to the html page I wanted. Please help me. The multi picture function I want should be under CreateView and should be placed in the same templet as it. Also, there should be 4 Image upload buttons, and the last one should be assigned multiple features (to html tag) models.py: class Photo(models.Model): post= models.ForeignKey(Person, on_delete=models.CASCADE) image = models.ImageField(upload_to=get_image_filename) uploaded_at = models.DateTimeField(auto_now_add=True) views.py: class PersonCreateView(CreateView): model = Person form_class = PersonForm success_url = reverse_lazy('person_changelist') forms.py: class PhotoForm(forms.ModelForm): image = forms.ImageField(label='Image') class Meta: model = Photo fields = ('image', ) -
Django - How to combine seperate apps into one webpage
im a new programmer and this is my first post here on stackoverflow. Iv'e gotten stuck. Iv'e really tried to figure it out on my own but I cant. So to my understanding Django is all about DRY and plug and play architecture with reusable apps. I'm trying to create my own Portfolio website using as proper and neat coding as I can. Given that, im trying to keep my apps independent so if I wanted, or anyone else, they could use it themselves. The problem is that I have my apps completely created but I'm trying to map them to one home page instead of blahblah.com/Messaging and blahblah.com/Projects I have two seperate apps, one a messaging form so someone can contact me, and another so I can list projects that I would display on the site. Here is my current code. My directory structure /PortfolioWebsite /Messaging /migrations /templates /Messaging (namespaced as Django recommends) Messagingtem.html __init__.py admin.py apps.py tests.py forms.py models.py tests.py urls.py views.py /PortfolioWebsite __init.py asgi.py settings.py urls.py wsgi.py /Projects /migrations /static /Projects (namespaced as Django recommends) /images projectimage1.jpg projectimage2.jpg /templates /Projects (namespaced as Django recommends) projectbase_list.html __init__.py admin.py apps.py models.py tests.py urls.py views.py /templates base.html (used for bootstrap) … -
How to display multiple related Models data in a Django Template table
I am new in Django and have problems during display datas from two models in one table. My two models are related with a OneToOneField. Here is the code of my models.py class Seed(models.Model): """Modell repräsentiert ein Saatgut und dessen allgemeine Angaben.""" id_seed = models.AutoField(primary_key=True) #Hier wird die Standrad Id id in id_seed überschrieben author=models.ForeignKey(User, on_delete=models.CASCADE) title=models.CharField('Bezeichnung', max_length=200, help_text="Bsp.: 'Berner Rose'") description = models.TextField('Beschreibung', help_text='Allgemeine Beschreibung.', blank=True) class SeedProperties(models.Model): id_seedproperties =models.AutoField(primary_key=True) seed=models.OneToOneField(Seed, on_delete=models.CASCADE) location_needs=models.CharField('Standortbedürfnisse', max_length=200, help_text="Bsp.: 'Freiland, Schutz empfohlen'", blank=True) here is my view: @login_required def seedlist(request): """View function for seedlist site""" context = { 'saatgutliste': Seed.objects.filter(author=request.user), 'saatguteigenschaften': SeedProperties.objects.all(), } return render(request, 'seedlist.html', context=context) And now I tried this, but without success.: {% for saatgut in saatgutliste %} <tr> <td><a href="{{ saatgut.get_absolute_url }}">{{ saatgut.title }}</a></td> <td>{{ saatgut.description }}</td> <td>{{ saatguteigenschaften(saatgut).location_needs}}</td> <td>test</td> </tr> {% endfor %} The error appears at the following line: saatguteigenschaften(saatgut).location_needs Does someone have a solution for my issue? Thanks a lot in advance! -
Not Found: /products/images/DSroadmap.png Not Found: /products/images/codewall.jpg [26/Jan/2020 22:13:36]
I am unable to load images from my MEDIAL_URL on a html page. Below is my code for uploading images, media url and the html. Any any help will be highly appreciated. html: <div class="row"> {% for item in items %} <div class='col-sm-3'> {% for item in item.itemimage_set.all %} {% if item.featured %} <img src="{{ MEDIA_URL }}{{ item.image }}"> {% endif %} {% endfor %} {{ item.title }} {{ item.price }} </div> {% cycle "" "" "" "</div><br/><hr/><div class='row'>" %} {% endfor %} </div> model: class ItemImage(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) image = models.ImageField(upload_to='products/images/') featured = models.BooleanField(default=False) thumbnail = models.BooleanField(default=False) active = models.BooleanField(default=True) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __unicode__(self): return self.item.title media url & root: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media') -
Django F() - avoid automatic parentheses
When using F() for making calculations between database table columns, parentheses are automatically added but not in correct mathematical order. If you do something like this: Model.objects.all().values(id).anotate(calc=F(column_a)+F(column_b)*F(column_c)) You will get a query like: SELECT id, ((column_a+column_b)*column_c) as calc FROM table; The correct mathematical order would be: (column_a+(column_b*column_c)) How can I achieve the correct order without adding parentheses in correct order by my self. Adding it by my self is not an option as a formula is programmatically created. -
Using query to match object and then get all objects associated via foreignkey
I am trying to create a job board where a user can search for jobs by zip code. I separated information about the Business into one model and the Job into another. The Business has the address, state, phone number fields etc, while Job has information about the job itself. I designed it this way so the user would not have to renter information about the physical business every time a job is posted. However now when I try and query the Jobs matching the zip code entered, I really have to grab the Business objects matching that zip code and then grab the Job objects associated with them? Here is my code: models.py from django.db import models from django.contrib.auth.models import User class Business(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) zip_code = models.CharField(max_length = 10) class Job(models.Model): business = models.ForeignKey(Business, on_delete= models.CASCADE) # ... views.py: def search_results(request): query =request.GET.get('query') jobs = Job.objects.filter(zipcode = query) # tried this before realizing the `zipcode` field was part of the `Business` model and not the `Job` model. return render(request, 'job/search_results.html', { 'jobs': jobs}) Thanks for any help. Also, this seems like a question that is probably very common but I was not sure what term to … -
Could not find backend 'django_redis.cache.RedisCache': No module named 'django_redis'
I have a django 3.0 project and I'm using django-redis for caching. I've created this class for get and set in redis: import json from django.core.cache import cache from django.conf import settings from django.core.cache.backends.base import DEFAULT_TIMEOUT CACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT) class RedisConnection: def __init__(self): self.images = "images" def set_image(self, key, value): if self.get_image(key): return image_dict = self.get_image_list() image_dict[key] = value cache.set(self.images, json.dumps(image_dict), timeout=CACHE_TTL) def get_image(self, key): image_dict = self.get_image_list() if key in image_dict: return image_dict[key] return None def get_image_list(self): if self.images in cache: image = cache.get(self.images) return json.loads(image) else: return {} And this is the CACHES setting in settings.py: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } But when I'm trying to run the line if self.images in cache: from get_image_list method, I encounter this error: Could not find backend 'django_redis.cache.RedisCache': No module named 'django_redis' I have installed django-redis package and I'm not sure where this error comes from. Should I import django_redis in some module?