Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix 'Raw query must include the primary key' in Django?
I have written a Raw SQL Query which I want to return through the objects.raw() function in my views.py: (For reference, pk is my input in my API Query) UserDetails.objects.raw("""SET datestyle = dmy; SELECT CASE WHEN ud.gender = 'M' THEN 1 ELSE 0 END Gender, DATE_PART('year',AGE(CURRENT_DATE,DATE(ud.dob))) AS AGE, CASE WHEN ud.mobile_count IS NOT NULL THEN ud.mobile_count ELSE 2 END Mobile_Number_Count, CASE WHEN ud.mobile_registered_at_bureau = TRUE THEN 1 ELSE 0 END Mobile_Registered_With_Bureau, ud.state_id AS State_Id, ud.city_id AS City_Id, CAST(REPLACE(rlv_lp.lookup_value, ' Days','') AS INTEGER) AS Loan_Period, CAST(REPLACE(rlv_rf.lookup_value, ' Days','') AS INTEGER) AS Repayment_Period, CASE WHEN cli.create_full_installment = TRUE THEN 1 ELSE 0 END Moratorium_Availed, CASE WHEN pinfo.is_married = TRUE THEN 1 ELSE 0 END Is_Married, CASE WHEN pinfo.is_spouse_working = TRUE THEN 1 ELSE 0 END Is_Spouse_Working, pinfo.no_of_children as No_Of_Children, CASE WHEN pinfo.is_joint_family = TRUE THEN 1 ELSE 0 END Is_Joint_Family, CASE WHEN pinfo.is_migrant = TRUE THEN 1 ELSE 0 END Is_Migrant, pinfo.other_assets AS Other_Asset, CASE WHEN pinfo.is_political = TRUE THEN 1 ELSE 0 END Is_Political, CASE WHEN pinfo.is_police = TRUE THEN 1 ELSE 0 END Is_Police, CASE WHEN pinfo.is_lawyer = TRUE THEN 1 ELSE 0 END Is_Lawyer, CASE WHEN bd.gst_no IS NOT NULL THEN 1 ELSE 0 END Has_GST, bd.business_nature AS Industry_Type, … -
Why login function in Django takes HttpRequest object?
Login function in django.contrib.auth takes HttpRequest object. I wanted to know why does it require HttpRequest object or in general how it works. -
Calling value of django tag in javascript
I am currently working on a beginner level project in django. I want to be able to pass the value of my django tag {{total_value}} in javascript in the similitude of this total: document.getElementById("total").value , I tried using var total = {{total_value}}; and passed total but it didn't work. Can someone help me out. Thank you in advance. -
Django-webpush: Service worker is not supported in your browser (Firefox)
I am using Django-Webpush to push notification. I followed the instructions and its working perfectly on Chrome, but in Firefox (version 84.0 - which supports service workers) I get the message that the service worker is not supported in your browser!. I checked other websites that have service workers and they seem to be working fine. I ran the browser with all add-ons deactivated, but the problem still persists. I also ran the browser with all add-ons disabled to see if anything was preventing it, without any success. In order to get the message that service workers are not supported in my browser, the following condition should fail in webpush.js : if('serviceWorker' in navigator) { var serviceWorker = document.querySelector('meta[name="service-worker-js"]').content; navigator.serviceWorker.register(serviceWorker).then(function(reg){subBtn.textContent = 'Loading...'; registration = reg; initialiseState(reg); }); } else { messageBox.textContent = 'Service Worker is not supported in your Browser!'; messageBox.style.display = 'block'; } Any idea on what else to check? -
How to dynamically add/remove the fields in django restframework serializer.?
I want to dynamically add/remove field items from a django rest serializer. when an api gets request that contains information to populate certain fields of the model only, i wanted to create/retrieve that particular fields only apart from populating all the fields of the model. is there any way to do this? -
Registring models on django admin site
I have made a django admin superuser previously for a project and now for another project i created another admin site super user but when i register models on admin site it gets registered on both admin sites( i.e prev one and in new one) -
Why I can't enable PyLint for this Django project using Visual Studio Code?
I am starting working with Django Python framework (working on an Ubuntu 20.04 VM) following the famous Mozzilla example project, this one: https://developer.mozilla.org/it/docs/Learn/Server-side/Django/Home_page I am using Python 3.8.5 version. I am finding the following problem (here on Stackoverflow I see that many persons had this problem and this should be related to Pylint. Basically the problem is the same exposed here: Django/Visual Studio Tutorial - objects method error I have this Django views.py file: from django.shortcuts import render # Create your views here. from .models import Book, Author, BookInstance, Genre def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() # Available books (status = 'a') num_instances_available = BookInstance.objects.filter(status__exact='a').count() # The 'all()' is implied by default. num_authors = Author.objects.count() context = { 'num_books': num_books, 'num_instances': num_instances, 'num_instances_available': num_instances_available, 'num_authors': num_authors, } # Render the HTML template index.html with the data in the context variable return render(request, 'index.html', context=context) The problem is that Visual Studio Code give me the following error on line like this: num_books = Book.objects.all().count() the error is: Class 'Book' has no 'objects' memberpylint(no-member) And this is my Book class code: class Book(models.Model): """Model … -
Remote access to django module
BACKGROUND I want to create an app that will be hosted on external server. It sounds easy and simple but I want to keep control over my code. So my idea is to develop an app that will load only necessary components over the HTTP. WHAT IS IN NOTES MODULE It's a simple django module. apps.py from __future__ import unicode_literals from django.apps import AppConfig class NotesConfig(AppConfig): name = 'notes' path = r'/PATH/TO/PROJECT/SAMPLE_httpimport/notes/' models.py from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models from django.urls import reverse from django_extensions.db.models import TimeStampedModel, TitleSlugDescriptionModel from mptt.models import MPTTModel class Note(TimeStampedModel): title = models.CharField(max_length=256) body = models.TextField() created_by = models.ForeignKey(User, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('note-detail', kwargs={'pk': self.pk}) def __str__(self): return self.title urls.py from django.conf.urls import url from notes.views import NoteListView, NoteDetailView, NoteCreate, NoteUpdate, NoteDelete urlpatterns = [ url(r'^$', NoteListView.as_view(), name='note-list'), url(r'^(?P<pk>\d+)/$', NoteDetailView.as_view(), name='note-detail'), url(r'note/add/$', NoteCreate.as_view(), name='note-add'), url(r'note/(?P<pk>[0-9]+)/$', NoteUpdate.as_view(), name='note-update'), url(r'note/(?P<pk>[0-9]+)/delete/$', NoteDelete.as_view(), name='note-delete'), ] views.py from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.urls import reverse_lazy from django.views.generic import CreateView from django.views.generic import DeleteView from django.views.generic import DetailView from django.views.generic import ListView from django.views.generic import UpdateView from notes.models import Note class NoteListView(ListView): model = Note class NoteDetailView(DetailView): model = Note class NoteCreate(CreateView): model = … -
How do I show all child objects in a template?
These are my models.py class Supplier(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Product(models.Model): sku = models.IntegerField(null=True) description = models.CharField(max_length=30) costprice = models.FloatField(null=True, max_length=99, blank=True) retailprice = models.FloatField(null=True, max_length=99, blank=True) barcode = models.CharField(null=True, max_length=99, unique=True, blank=True) image = DefaultStaticImageField(null=True, blank=True, default='images/item_gC0XXrx.png') supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.description I have a supplierpage/str:pk_supplier/ and inside it I want to display all products that belong to that specific supplier in a table like: <tr> <th>ID</th> <th>Description</th> <th>Cost</th> <th>Retail Price</th> <th>Barcode</th> </tr> </thead> <tbody> <tr> **{% for ??? in ???? %} <-----what should i put here??** <td> <a href="{% url 'productpage' product.id %}">{{product.id}}</a></td> <td><h6><strong>{{product.description}}</strong></h6></td> <td>£{{product.costprice |floatformat:2}}</td> <td>£{{product.retailprice |floatformat:2}}</td> <td>{{product.barcode}}</td> </tr> {% endfor %} -
Django choice field
I want to create a form that user can select her/his company from a choicefield. But this choicefield should contains another model's field. What I mean: models.py class CompanyProfile(models.Model): comp_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) comp_name = models.OneToOneField(User, on_delete=models.CASCADE) class UserProfile(models.Model): comp_name = models.ForeignKey(on_delete=models.CASCADE) #select from CompanyProfile comp_id = models.ForeignKey(on_delete=models.CASCADE) user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500) password = models.CharField(max_length=50) email = models.EmailField(max_length=254) forms.py companies = [] #problem is here class SignUpForm(UserCreationForm): comp_name = forms.CharField(label='What is your company name?', widget=forms.Select(choices=companies)) comp_username = forms.CharField(max_length=30, required=False) email = forms.EmailField(max_length=254) class Meta: model = User fields = ('comp_name', 'comp_username', 'email', 'password1', 'password2') How can I select company name from CompanyProfile? -
Python3 & Django3.1.4 - No module named django.core.management
I had issues with django because installing it using pip would only install django1.x for python2.7, so I made a clean install, but now it won't works when calling it. I very recently reinstalled Python and Django: python3 --version Python 3.9.1 python3 -m django --version 3.1.4 But when I try to create a new project using Django, I get the error: django-admin startapp test Traceback (most recent call last): File "/usr/local/bin/django-admin", line 5, in <module> from django.core.management import execute_from_command_line ImportError: No module named django.core.management If I do python3 -m django startapp test the command will do what's asked, but not if I do python3 -m django-admin startapp test I'll get /usr/local/bin/python3: No module named django-admin I looked for answers to people who had a similar error message but it didn't solve my problem. Could you tell me what I'm missing/what should I do ? -
Django reverse nested filtering
I want to make a filter on a nested Model with the Django reverse relation. Below is the sample models I have : class ProcessVersion(TimeStampedModel): tag = models.CharField(_('Tag Name'), max_length=48) status = FSMField( _('Status'), max_length=12, choices=VERSION_STATUS_CHOICES, default=VERSION_STATUS_IN_EDITION) class Step(models.Model): version = models.ForeignKey( ProcessVersion, verbose_name=_('Process Version'), on_delete=models.CASCADE, related_name='steps', blank=True, null=True) is_active = models.BooleanField( _('Is active'), default=False) title = models.CharField(_('Title'), max_length=32) class Block(models.Model): step = models.ForeignKey( Step, verbose_name=_('Loan Process Step'), on_delete=models.CASCADE, related_name='blocks', blank=True, null=True) is_active = models.BooleanField( _('Is active'), default=False) title = models.CharField(_('Title'), max_length=128, blank=True) The first scenario was accessing the Step through it's related name and it worked : process_version = ProcessVersion.objects.get(id=process_version_id) steps = process_version.steps.get(id=param_id) meaning that I passed through ProcessVersion to get the Step. Now, my question is what if I want to get the Block but passing through ProcessVersion with it's id , how can I query that ? -
How to avoid Django Rest Framework logging extra info?
I am using Django Rest Framework. In settings.py I am using the following entry: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': str(BASE_DIR) + '/debugme.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } IN my code I just added logger.info('Checking Balance!') but when I checked debugme.log it dumped loads of unwanted info but the one I needed? Watching for file changes with StatReloader Waiting for apps ready_event. Apps ready_event triggered. Sending autoreload_started signal. Watching dir /muwallet_web/muwallet/locale with glob **/*.mo. Watching dir /usr/local/lib/python3.9/site-packages/rest_framework/locale with glob **/*.mo. Watching dir /usr/local/lib/python3.9/site-packages/django_extensions/locale with glob **/*.mo. Watching dir /muwallet_web/muwallet/api/locale with glob **/*.mo. (0.004) SELECT c.relname, CASE WHEN c.relispartition THEN 'p' WHEN c.relkind IN ('m', 'v') THEN 'v' ELSE 't' END FROM pg_catalog.pg_class c All I need to show info I need. -
Django - No CSRF error for posts without token
I'm using Django to host a React application. I added the CSRF protection middleware in Django. I tried testing it by sending a http post with Postman, without the x-csrftoken in the header. To my surprise, I did not get a 403, but I was able to get data without the x-csrftoken. How is this possible? Below you find my CSRF settings. My additional Django settings are very straightforward and include CORS. ... # Cross Origin Resource Sharing Protection CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:3000', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True # Cross Site Request Forgery Protection CSRF_TRUSTED_ORIGINS = [] MIDDLEWARE = [ ... 'django.middleware.csrf.CsrfViewMiddleware', ] -
Django: problem declarig 2 fields with the same related object
I'm trying to create a model that has 2 fields with the same related object (Call): class Call(LogsMixin, models.Model): """Definición del modelo de Proveedor.""" id = models.CharField("ID de la convocatoria", primary_key=True, null=False, default="", max_length=50) name = models.CharField("Nombre de convocatoria", null=False, default="", max_length=200) active = models.BooleanField("Activada", default=True) class Consumption(LogsMixin, models.Model): """Definición del modelo de Consumos""" client = models.ForeignKey('authentication.Client', verbose_name=("Cliente"), null=True, default=None, on_delete=models.SET_DEFAULT) sap_price = models.DecimalField(("Precio de SAP"), max_digits=6, decimal_places=2, null=False, default=0) access_date = models.DateField("Fecha de acceso", auto_now=False, auto_now_add=False) call = models.ForeignKey(Call, verbose_name=("Convocatoria"), null=True, default=None, on_delete=models.SET_DEFAULT) accessible_calls = models.ManyToManyField(Call, verbose_name=("Convocatorias accesibles")) When I try to make the migrations I receive the next error: ERRORS: consumptions.Consumption.accessible_calls: (fields.E304) Reverse accessor for 'Consumption.accessible_calls' clashes with reverse accessor for 'Consumption.call'. HINT: Add or change a related_name argument to the definition for 'Consumption.accessible_calls' or 'Consumption.call'. consumptions.Consumption.call: (fields.E304) Reverse accessor for 'Consumption.call' clashes with reverse accessor for 'Consumption.accessible_calls'. HINT: Add or change a related_name argument to the definition for 'Consumption.call' or 'Consumption.accessible_calls'. Does anyone have any clue? -
How to add load more button in django application
I have developed a template for viewing the images in my Django application.I want to view only 2 images at the starting and then after clicking the load more button, the next 2 images have to be shown. I am unable to do this. <div class="items"> {% for portfolio in portfolios %} <!-- ======= Portfolio Section ======= --> <section id="portfolio{{portfolio.id}}" class="portfolio"> <div class="container" data-aos="fade-up"> <div class="row portfolio-container" data-aos="fade-up" data-aos-delay="200"> <div class="col-lg-4 col-md-6 portfolio-item"> <img src="{{ portfolio.file.url }}" class="img-fluid" alt="{{ portfolio.title }}"> <div class="portfolio-info"> <h4>{{ portfolio.title }}</h4> <p style="font-size: 11px">Uploaded by <a href="{% url 'profile' username=portfolio.user.username %}">{{portfolio.user}}</a></p> <a href="{{ portfolio.file.url }}" onclick="views({{portfolio.id}})" data-gall="portfolioGallery" class="venobox preview-link" title="{{ portfolio.title }}"> <i class="bx bx-show-alt"></i> </a> <a href="{{ portfolio.file.url }}" onclick="dow({{portfolio.id}})" class="details-link" title="Download" download> <i class='bx bxs-download pl-2'></i> </a> <p id="views{{portfolio.id}}" >{{portfolio.views}}</p> <span id="dow{{portfolio.id}}">{{portfolio.total_downloads}}</span> {% if user.is_authenticated %} {% if user.username in portfolio.likes %} <button type="submit" onclick="like({{portfolio.id}});" name="post_id" id="ul{{portfolio.id}}" value="{{portfolio.id}}" class="btn btn-primary btn-sm"> Unlike </button> {% else %} <button type="submit" onclick="like({{portfolio.id}});" name="post_id" id="l{{portfolio.id}}" value="{{portfolio.id}}" class="btn btn-primary btn-sm"> Like </button> {% endif %} {% else %} <a class="btn btn-outline-info" href="{% url 'login' %}">Log in to like this article</a><br> {% endif %} </div> <strong class="text-secondary" >Total likes:<span id="total_likes{{portfolio.id}}">{{portfolio.number_of_liked}}</span></strong> </div> </div> </div> </div> </section> <!-- End Portfolio Section … -
How to serialize field dynamically if I don't know in advance which serializer will be chosen?
I have a simple serializer: class BoxSerializer(Serializer): modelName = serializers.CharField(required=True) body = ??? And I want to serialize a field 'body' depending on 'modelName ' field. For example, if modelName is 'Phone' then i want to use PhoneSerializer for 'body' field. If modelName 'book' i want to user BookSerializer and so on. How can i implement this? Please note that I am not going to save anything to the database -
Django maintain password history and compare passwords
I have a Profile model by extending the User model where I added the fields for the last 5 passwords and the last password change date. class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE) birth_date = models.DateField(null=True, blank=True) phone = models.CharField(max_length=10) status = models.CharField(max_length=10) role = models.CharField(max_length=10) pwd1 = models.CharField(max_length=256, blank=True) pwd2 = models.CharField(max_length=256, blank=True) pwd3 = models.CharField(max_length=256, blank=True) pwd4 = models.CharField(max_length=256, blank=True) pwd5 = models.CharField(max_length=256, blank=True) last_pwd_change_date = models.DateField(null=True, blank=True) I am able to force the password expiry date in the views.py like so lastpwddate= userProfile.last_pwd_change_date today=date.today() datediff=today-lastpwddate if datediff.days > 90: errorlogger.error("Password Expired") auth.logout(request) My next step would involve the following: Whenever a new user registers, the password they used will be stored in the pwd1 to pwd5 fields Whenever a user updates their password, I would like to compare the new password with the last 5 passwords. If there is any similar password among them, throw an error I am new to Django and since I am using the default code for password change etc. I am not sure how to proceed. Do I create a new view function or change any existing code in (possibly) the auth folder? How should I proceed? Any help is much appreciated. -
Django keras load_model raise OSError how to fix?
# image_predict.py import os file_path = os.path.join(settings.STATIC_URL, 'util/keras_model.h5') print(file_path) model = tensorflow.keras.models.load_model(file_path) i want to use keras model but it doesn't work. -
Multi-Stage Docker build failed - Error: invalid from flag value
I am trying to implement multi-stage docker build to deploy Django web app. An error occurred while trying to copy from one docker stage to another. I am sharing Dockerfile and error traceback for your reference. The same Docker build worked before one day ago. Somehow, It is not working today. I have searched for some workaround. But, no luck. My Dockerfile as: FROM node:10 AS frontend ARG server=local RUN mkdir -p /front_code WORKDIR /front_code ADD . /front_code/ RUN cd /front_code/webapp/app \ && npm install js-beautify@1.6.12 \ && npm install --save moment@2.22.2 \ && npm install --save fullcalendar@3.10.1 \ && npm install --save pdfjs-dist@2.3.200 \ && npm install \ && npm install --save @babel/runtime \ && yarn list && ls -l /front_code/webapp/app/static \ && npm run build \ && rm -rf node_modules \ && cd /front_code/webapp/market-app \ && yarn install \ && yarn list && ls -l /front_code/webapp/market-app/static \ && yarn build \ && rm -rf node_modules \ FROM python:3.8-alpine AS base ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ARG server=local ARG ENV_BUCKET_NAME="" ARG REMOTE_ENV_FILE_NAME="" ARG FRONT_END_MANIFEST="" ARG s3_bucket="" ARG AWS_ACCESS_KEY_ID="" ARG AWS_SECRET_ACCESS_KEY="" ARG RDS_DB_NAME="" ARG RDS_USERNAME="" ARG RDS_PASSWORD="" ENV server="$server" ENV_BUCKET_NAME="$ENV_BUCKET_NAME" REMOTE_ENV_FILE_NAME="$REMOTE_ENV_FILE_NAME" FRONT_END_MANIFEST="$FRONT_END_MANIFEST" s3_bucket="$s3_bucket" AWS_SECRET_ACCESS_KEY="$AWS_SECRET_ACCESS_KEY" AWS_ACCESS_KEY_ID="$AWS_ACCESS_KEY_ID" RDS_DB_NAME="$RDS_DB_NAME" RDS_USERNAME="$RDS_USERNAME" RDS_PASSWORD="$RDS_PASSWORD" RUN … -
Gitlab runner deletes Django media files on the server
I'm deploying a Django project on Centos 7 server using gitlab runner. Each time I commit and push the project, gitlab runner tries to remove folders (such as the media folder) that are not in the gitlab repository(are on .gitignore). I don't want gitlab runner to delete media files. How can I ignore deleting some files and folders when gitlab runner starts its job? -
How to allow Iframe to other website from Django Website?
I am new to Django. I have launched a new site with Django. I wish people can iframe my site. But when doing I frame, It shows Site Refused to connect. . As a newbie, I don’t have any idea what to do now. Would you please suggest me. Thanks in Advance -
Django - Issue with parsing multiselect values received as request.GET context parameter to a template
I had passed request.GET as context parameter to my template. I am planning to use populate multiselect dropbox with the values coming from request.GET in the colony tag. I have passed the context correctly from views.py file but I am not able to fetch the all the colony values in template. If I use values.colony, I just get the last value in this list. I am using following code views.py 'values': request.GET I am using value in values.getlist('colony') in the template file to retrieve all colony values but this line is giving error anytime I use values.getlist('colony'). Can you please suggest what I am doing wrong? -
Unable to create task in Redis
I am using Celery to create tasks, but after a while Redis returns an error Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/celery/worker/worker.py", line 203, in start self.blueprint.start(self) File "/usr/local/lib/python3.7/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/usr/local/lib/python3.7/site-packages/celery/bootsteps.py", line 365, in start return self.obj.start() File "/usr/local/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 311, in start blueprint.start(self) File "/usr/local/lib/python3.7/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/usr/local/lib/python3.7/site-packages/celery/worker/consumer/connection.py", line 21, in start c.connection = c.connect() File "/usr/local/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 400, in connect conn.transport.register_with_event_loop(conn.connection, self.hub) File "/usr/local/lib/python3.7/site-packages/kombu/transport/redis.py", line 1061, in register_with_event_loop cycle.on_poll_init(loop.poller) File "/usr/local/lib/python3.7/site-packages/kombu/transport/redis.py", line 336, in on_poll_init num=channel.unacked_restore_limit, File "/usr/local/lib/python3.7/site-packages/kombu/transport/redis.py", line 201, in restore_visible self.unacked_mutex_expire): File "/usr/local/lib/python3.7/contextlib.py", line 112, in __enter__ return next(self.gen) File "/usr/local/lib/python3.7/site-packages/kombu/transport/redis.py", line 121, in Mutex lock_acquired = lock.acquire(blocking=False) File "/usr/local/lib/python3.7/site-packages/redis/lock.py", line 187, in acquire if self.do_acquire(token): File "/usr/local/lib/python3.7/site-packages/redis/lock.py", line 203, in do_acquire if self.redis.set(self.name, token, nx=True, px=timeout): File "/usr/local/lib/python3.7/site-packages/redis/client.py", line 1801, in set return self.execute_command('SET', *pieces) File "/usr/local/lib/python3.7/site-packages/redis/client.py", line 901, in execute_command return self.parse_response(conn, command_name, **options) File "/usr/local/lib/python3.7/site-packages/redis/client.py", line 915, in parse_response response = connection.read_response() File "/usr/local/lib/python3.7/site-packages/redis/connection.py", line 756, in read_response raise response redis.exceptions.ReadOnlyError: You can't write against a read only replica. As I understand it, such problems arise when the task fails. It is important to note that I am using docker-compose. I am attaching an … -
How to refrence to an item in WishList for a Product in Django?
I want to implement a wishlist for the products in my Django site so that I can represent them in a wishlist page to the user. the products are in the products app. products.models.py class ControlValves(models.Model): title = models.CharField(max_length=50, unique=True) product_name = models.CharField(max_length=50, blank=True) .... class Accessories(models.Model): title = models.CharField(max_length=50, unique=True) description = models.CharField(max_length=50, blank=True) .... There is a services app that contains various services(models). Then I want to create a wishlist in users app. users.models.py class Wishlist(models.Model): owner = models.ForeignKey( User, on_delete=models.CASCADE) title = models.CharField(max_length=50, null=True, blank=True) item = models.ForeignKey( which_model_should_be_here??? , on_delete=models.CASCADE) since I am fetching the list of products and services from two different apps and within each, there are various models: question: 1- I don't know how to point to the selected product or service? should I declare a foreign key to each possible product model o services model, or there is another efficient way? 2- an example of how to load them to show to the user( i.e. how to write a query to load them from DB) would be great. I also checked the answer to this and this, but they are fetching products from just one model, so it's easy because there should …