Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I have object.model_set two foreign keys to the same model in Django?
Here is my code from django.db.models import Models class ChatRoom(Models.model): room_member_1 = models.ForeignKey( User, null=True, related_name="member_1", on_delete=models.SET_NULL ) room_member_2 = models.ForeignKey( User, null=True, related_name="member_2", on_delete=models.SET_NULL ) According to feature the User object could be room_member_1 and room_member_2. If one of the user object's has 5 ChatRoom then we can get user's chat rooms using following query like user_object.member_1 or user_object.member_2 Now i want to get user_object all chat room using one query without ChatRoom.objects.filter(Q(room_member_1=user_object)|Q(room_member_2=user_object)) query. Is it possible ? -
How can I configure redirectregex in compose file for traefic in a django project?
I used Cookiecutter to create a django project and now I want to configure traefik to redirect a specific url to another url with the same domain but a different path. This is my compose file: version: '3' volumes: production_postgres_data: {} production_postgres_data_backups: {} production_traefik: {} services: django: &django build: context: . dockerfile: ./compose/production/django/Dockerfile image: telegrambots_production_django depends_on: - postgres - redis env_file: - ./.envs/.production/.django - ./.envs/.production/.postgres command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: telegrambots_production_postgres volumes: - production_postgres_data:/var/lib/postgresql/data - production_postgres_data_backups:/backups env_file: - ./.envs/.production/.postgres traefik: build: context: . dockerfile: ./compose/production/traefik/Dockerfile image: telegrambots_production_traefik depends_on: - django volumes: - production_traefik:/etc/traefik/acme ports: - "0.0.0.0:80:80" - "0.0.0.0:443:443" - "0.0.0.0:5555:5555" labels: - "traefik.http.routers.redirect-router.middlewares=redirect-regex" - "traefik.http.middlewares.redirect-regex.redirectregex.regex=^mydomain\\.org\\/(.*)" - "traefik.http.middlewares.redirect-regex.redirectregex.replacement=mydomain.org/x/y/$${1}" - "traefik.http.middlewares.redirect-regex.redirectregex.permanent=false" redis: image: redis:6 celeryworker: <<: *django image: telegrambots_production_celeryworker command: /start-celeryworker celerybeat: <<: *django image: telegrambots_production_celerybeat command: /start-celerybeat flower: <<: *django image: telegrambots_production_flower command: /start-flower awscli: build: context: . dockerfile: ./compose/production/aws/Dockerfile env_file: - ./.envs/.production/.django volumes: - production_postgres_data_backups:/backups:z You can see in my compose file that I've put 4 lines under labels under traefik but this doesn't work. What should I do to fix this? -
django redirect url concatenating to the previous url, help me to stop concatenating
this is my previouse url - http://127.0.0.1:8000/viewbook/8/viewchapter/57/ this is the url I want to redirect - http://127.0.0.1:8000/viewbook/8/viewchapter/57/ but its redirect me to this url - http://127.0.0.1:8000/viewbook/8/viewchapter/57/ project - urls.py from django.contrib import admin from django.urls import path , include urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), ] home.urls.py from django.urls import path from . import views app_name = 'home' urlpatterns = [ path('',views.home,name='home'), path('viewbook/<int:id>/', views.viewbook , name='viewbook'), path('viewchapter/<int:id>/', views.viewchapter , name='viewchapter'), path('viewpost/<int:id>/', views.viewpost , name='viewpost'), ] views.py def viewbook(response , id): book = Book.objects.get(id = id) allchapters = Chapter.objects.all() chapters = [] for chapt in allchapters: if chapt.Book.id == book.id: chapters.append(chapt) inputform = ChapterForm() if response.method == 'POST': form = ChapterForm(response.POST) if form.is_valid(): chapt = Chapter(Book = book , chapterNum = response.POST['chapterNum'] , chapterText = "") print(chapt) chapt.save() print(Chapter.objects.get(id= chapt.id)) return redirect('viewchapter/%i/' %chapt.id) inputform.fields["chapterNum"].initial =len(chapters) + 1 context = { 'book' : book, 'form' : inputform, 'chapters' : chapters } return render(response , 'viewbook.html' , context) def viewchapter(response , id): chapter = Chapter.objects.get(id = id) context = {'chapter' : chapter} return render(response , 'viewchapter.html', context) I think the problem is with this line return redirect('viewchapter/%i/' %chapt.id) I change it to return HttpResponseRedirect('viewchapter/%i/' %chapt.id) but bith of them are giving me … -
CSRF verification failed. Request aborted while deploying Django app on production
I am trying to setup my project on production but I am getting this error- Origin checking failed - https://mydomain does not match any trusted origins.I tried many solutions but none of them worked.I have deployed other django projects in past but this is first time I am getting this error. my django version is 3.12.4 This is what my django settings file looks like - """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) from .globalvariable import DATABASE # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'key' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['ip', 'domain', 'domain'] CORS_ORIGIN_WHITELIST = [ "domain", # Add any other allowed origins here ] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'api', 'adminApi', 'rest_framework_api_key', 'room' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'dashboardBackend.urls' CORS_ORIGIN_ALLOW_ALL = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': … -
Celery + Django - ModuleNotFoundError: No module named 'celery.backends.amqp'
I have no clue why I am getting this error. My ´requirements.txt´ file includes: amqp==5.1.1 celery==5.2.7 I have followed the standard configurations here: Any ideas what could be wrong? -
Django Crontab keeps add "No module named 'django.utils.importlib'"
Every time I try to run python manage.py crontab add or run my testing script I get this: python manage.py crontab add Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/trademaj/virtualenv/public_html/city/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/trademaj/virtualenv/public_html/city/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/trademaj/virtualenv/public_html/city/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 257, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/trademaj/virtualenv/public_html/city/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 39, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/opt/alt/python38/lib64/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 843, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/trademaj/virtualenv/public_html/city/3.8/lib/python3.8/site-packages/django_crontab/management/commands/crontab.py", line 4, in <module> from django_crontab.crontab import Crontab File "/home/trademaj/virtualenv/public_html/city/3.8/lib/python3.8/site-packages/django_crontab/crontab.py", line 13, in <module> from django.utils.importlib import import_module ModuleNotFoundError: No module named 'django.utils.importlib' Settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'nema_app', 'user_auth', 'rest_framework', 'rest_framework.authtoken', 'django_crontab', ] . . . . . CRONJOBS = [ ('*/2 * * * *', 'nema_app.job.my_function') ] job.py: from user_auth.models import UserIntervalInfo def my_function(): # Your code here interval = UserIntervalInfo.objects.all()[0] interval.interval … -
Some files get "Static file referenced by handler not found"
I'm deploying to google app engine with Python/Django. I store css files and images in automatically created Cloud Storage. I can read css files, but not images. I think that the path is not wrong because the css file can be read. I think that it is due to the specifications of App Engine, but I do not know the detailed cause. Please support me. Of course it works fine locally. It is a situation where an error occurs only in production. ▼Version Python 3.9.12 Django 4.1.1 ▼Log(Cloud Storage) Static file referenced by handler not found: staticfiles/img/example.png/ ▼app.yaml runtime: python39 instance_class: F1 env: standard service: default entrypoint: gunicorn -b :$PORT config.wsgi:application includes: - secrets/secret.yaml handlers: - url: /static static_dir: staticfiles/ - url: /.* secure: always script: auto ▼folder -
Are channels and scrapy incompatible in Django?
This is the weirdest thing that happened to me There are scrapy and channels in my Django. After I installed channels3.0.5, my chat room can run normally, but my scrapy can't run normally, and scrapy stays at 2023-04-04 10:10:42 [scrapy.core .engine] DEBUG: Crawled (200) <POST http://pfsc.agri.cn/api/priceQuotationController/pageList?key=&order=> (referer: None), I debugged and found that I could not enter parse, I used wireshare to grab Get the data packet, there is a return value. I upgraded the channels to 4.0.0, and then my chat room can't link to the ws server, but scrapy can run normally thank you for your time scrapy log: ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware', 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware', 'scrapy.spidermiddlewares.referer.RefererMiddleware', 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware', 'scrapy.spidermiddlewares.depth.DepthMiddleware'] 2023-04-04 10:10:42 [scrapy.middleware] INFO: Enabled item pipelines: ['spider.pipelines.SpiderPipeline_PFSC'] 2023-04-04 10:10:42 [scrapy.core.engine] INFO: Spider opened 2023-04-04 10:10:42 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2023-04-04 10:10:42 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023 2023-04-04 10:10:42 [scrapy.core.engine] DEBUG: Crawled (200) <POST http://pfsc.agri.cn/api/priceQuotationController/pageList?key=&order=> (referer: None) 2023-04-04 10:11:42 [scrapy.extensions.logstats] INFO: Crawled 1 pages (at 1 pages/min), scraped 0 items (at 0 items/min) scrapy spider: def __init__(self, **kwargs): super().__init__(**kwargs) self.total_prices = 1 self.url = 'http://pfsc.agri.cn/api/priceQuotationController/pageList?key=&order=' self.date = datetime.today().strftime('%Y-%m-%d') print('today is ' + self.date) date_list = PFSC_Price.objects.filter(reportTime=self.date) self.date_list = list(date_list.values()) for data in … -
Is it safe to add user_id column to Django db session model?
Currently the Django session model doesn't have an user ID field: class AbstractBaseSession(models.Model): session_key = models.CharField(_('session key'), max_length=40, primary_key=True) session_data = models.TextField(_('session data')) expire_date = models.DateTimeField(_('expire date'), db_index=True) In [2]: Session.objects.first().get_decoded() Out[2]: {'_auth_user_id': '3', '_auth_user_backend': 'btg_auth.backends.BTGLDAPBackend', '_auth_user_hash': '2b5c55aecf5cf008803bc30f40414560582feac0'} This is impossible for us to implement "back-channel logout" because every service provider would have different session ids. To make this work, I will need to add an user identification field to the model, eg. username, so that the IdP can issue log out signal to all service providers to log the user out by using the username class AbstractBaseSession(models.Model): session_key = models.CharField(_('session key'), max_length=40, primary_key=True) session_data = models.TextField(_('session data')) expire_date = models.DateTimeField(_('expire date'), db_index=True) username = models.CharField(...) I am not 200% sure if this will have any security implications? Thought I'd post here to check with the experts. -
How to remove '*' sign on a field when dealing with crispy forms?
So in the crispy form documentation(link here: https://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_forms.html#change-required-fields), it states that: Asterisks have an asteriskField class set. So you can hide it using CSS rule. models.py class Post(models.Model, HitCountMixin): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateField(auto_now_add=True) image = models.ImageField(default='default_pics/default_post.jpg', upload_to='post_pics') # a teacher can have many blog posts author = models.ForeignKey(Teacher, on_delete=models.SET_NULL, null=True) forms.py class BlogFrom(forms.ModelForm): class Meta: model = Post fields = ['title', 'content', 'image'] widgets = { 'image': forms.FileInput(attrs={"class":"asteriskField"}) } help_texts = { 'image': 'If you do not set any image, one will be set automatically for you upon creation.' } I am not sure how to proceed from here. Help me please! -
Requesting Source Code for Photo-Truth Verification Project using Django, Vue, HTML, CSS, and SQL
I am a final year undergraduate student working on a project titled "Photo-Truth Verification Using Encrypted Metadata". My project aims to develop a web application that can verify the authenticity of photos using encrypted metadata. The project will be implemented using Django, Vue, HTML, CSS, and SQL. However, as my final year project defense is approaching fast, I am struggling to complete the project on time. I have very basic knowledge in programming and would appreciate any help I can get with the source code for my project. If anyone has experience with these technologies and would be willing to assist me with the source code for this project, I would be extremely grateful. Ideally, I need the source code within the next 5 days so that I can complete the project and prepare for my defense I have attempted to generate the source code for my project using AI like Chat GPT. Unfortunately, my limited programming knowledge made the process confusing and complicated. Therefore, I am seeking assistance from an experienced developer who has knowledge of the specific technologies I am using. I am expecting to receive the complete source code for my project, with a focus on the … -
stream multi videos flask_socketio from Multi Clients to one server
can any one plz help me, to write a simple code in python based on Flask and flask_socketio, to recieve and process videos from multi clients in the same time. i used Threads but it's so difficult to apply it on flask_socketio. this is my old code based on socket library but i want to change it to flask_socketio: # In this video server is receiving video from clients. # Lets import the libraries import socket, cv2, pickle, struct import imutils import threading import pyshine as ps # pip install pyshine import cv2 server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) host_name = socket.gethostname() host_ip = socket.gethostbyname(host_name) print('HOST IP:',host_ip) port = 9999 socket_address = (host_ip,port) server_socket.bind(socket_address) server_socket.listen() print("Listening at",socket_address) def show_client(addr,client_socket): try: print('CLIENT {} CONNECTED!'.format(addr)) if client_socket: # if a client socket exists data = b"" payload_size = struct.calcsize("Q") while True: while len(data) < payload_size: packet = client_socket.recv(4*1024) # 4K if not packet: break data+=packet packed_msg_size = data[:payload_size] data = data[payload_size:] msg_size = struct.unpack("Q",packed_msg_size)[0] while len(data) < msg_size: data += client_socket.recv(4*1024) frame_data = data[:msg_size] data = data[msg_size:] frame = pickle.loads(frame_data) text = f"CLIENT: {addr}" frame = ps.putBText(frame,text,10,10,vspace=10,hspace=1,font_scale=0.7, background_RGB=(255,0,0),text_RGB=(255,250,250)) cv2.imshow(f"FROM {addr}",frame) key = cv2.waitKey(1) & 0xFF if key == ord('q'): break client_socket.close() except Exception as e: … -
New users on Django app at heroku doesn't persist on database
We started a project on Heroku, using Django, but users aren't persisted on Django User table on our database, but as Admin users at Django? We use User.objects.create_user() from django.contrib.auth.models.User Database is MySQL Any tips? -
Using the URLconf defined in iblogs.urls, Django tried these URL patterns, in this order:
I know this question has been asked before, but I haven't found an answer that solves my situation. I'm looking at the Django tutorial, and I've set up the first URLs exactly as the tutorial has it, word for word, but when I go to http://127.0.0.1:8000/, it gives me this error: but when i go to http://127.0.0.1:8000/admin/ its working fine,where and what i am doing wrong? i am using python version 3.11.1 please let me know for any other info Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog Using the URLconf defined in iblogs.urls, Django tried these URL patterns, in this order: admin/ ^media/(?P<path>.*)$ The current path, blog, didn’t match any of these. urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from .views import home urlpatterns = [ path('admin/', admin.site.urls), path(' ', home) ] views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. def home(request): return HttpResponse("hello") urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('blog/',include('blog.urls')) ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Django migration: django.db.utils.IntegrityError: (1062, "Duplicate entry '' for key 'slug'")
I am having a very similar problem as in the below question: django.db.utils.IntegrityError: (1062, "Duplicate entry '' for key 'slug'") I also think that the reply marked as accepted will work for me. The problem is that I can't figure how to implement this solution (I was trying to ask in comments to the answer, but I don't have enough reputation). After reading https://docs.djangoproject.com/en/4.1/ref/migration-operations/, nothing became clearer. I tried to search the Internet for guides on how to edit or copy migrations, but I haven't found anything useful to me, apart from discovering that migrations are/can be also files? Until now, I thought that migration is an action, not a file. I am very new to Django, and the only thing I have ever done with migrations is to just run a basic python manage.py migrate and python manage.py makemigrations commands. Would anyone be able to advise what 'copy migrations.AlterField operation twice,' means? How can I copy a migration? And why does it have .AlterField attached to it? This whole paragraph seems like it might be a solution to my problem, but my knowledge is insufficient to figure out what to do with it... Could someone please explain how to … -
Google Cloud Scheduler - Decode OIDC Http Authorization Decode in Django
I have deployed a django app in GCP Cloud Run and trying to setup a cron job in GCP Scheduler. The job uses OIDC authentication. How to verify the OIDC in the backend. I tried the below code, but I could not get any data from the decode. from google.auth import jwt def send_mail(request): auth_header = request.headers.get('Authorization') if auth_header: auth_type, creds = auth_header.split(' ', 1) if auth_type.lower() == 'bearer': certs = requests.get('https://www.googleapis.com/oauth2/v1/certs') claims = jwt.decode(creds, certs=certs.json(), verify=True) logger.info(f"Claims: {claims}") return HttpResponse(status=204) -
Send files to another server with Django
I have a project in which I made the frontend in Angular and the backend in Django. The frontend is uploaded on my hosting service and the backend is uploaded to pythonanywhere. What I am looking for is the media files to be uploaded to my hosting. I found that it can be done using django-storages but the documentation is very unclear and I can't understand it. I already followed the steps, adding DEFAULT_FILE_STORAGE and FTP_STORAGE_LOCATION to my settings.py but I don't know how to proceed. I searched the internet for information about it but got nothing. I would appreciate more information about it or any alternative to achieve my goal -
How to load an image from ImageField of all instances of a model
So I have an app called todo, a Good model with ImageField. In my template I want to iterate over all instances of Good model and display all instances' images which were uploaded by admin in admin panel but when I try to run the code below I get: Not Found: /todo/static/goods_images/image_2023-04-03_224219080.png [04/Apr/2023 00:22:26] "GET /todo/static/goods_images/image_2023-04-03_224219080.png HTTP/1.1" 404 2355 model.py: from django.db import models class Good(models.Model): name = models.CharField(max_length=100) price = models.FloatField() pic = models.ImageField(upload_to='todo/goods_images', null=True, blank=True) class Meta: ordering = ['-price'] def __str__ (self): return str(self.name) views.py: from django.shortcuts import render from django.views.generic.list import ListView from .models import Good class GoodsList(ListView): model = Good context_object_name = 'goods' template_name = 'goods_list.html' goods_list.html: {% load static %} <html> {% for good in goods %} <div> {{ good.pic }} <img src="{{ good.pic.url }}" /> {{ good.name }} {{ good.price }} </div> {% endfor %} </html> settings.py: from django.urls import path from .views import GoodsList from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('goods_list/', GoodsList.as_view()), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Already went through a couple of videos but all of them load as static only one image and so in template write the exact path to it but … -
Django how get all invoices containing item
I spent over two days looking in docs and internet and cannont find solution. I have models: class Invoice(models.Model): (...) class Product(models.Model): (...) class InvoicedItems(models.Model): invoice = models.ForeignKey(Invoice, on_delete=CASCADE) article = models.ForeignKey(Product, on_delete=CASCADE) How to get list of all invoices containing one product? I want to make search engine. I tried to define in InvoicedItems: def get_invoices_by_article(article): inv_obj = InvoicedItems.objects.filter(article=article) inv = inv_obj.invoice return inv But all the time I get error: 'QuerySet' object has no attribute 'invoice' I know that I am close but I need your help. Thanks in advance! -
Add autocomplete to CKEditorUploadingWidget
I have a Django form that uses CKEditorUploadingWidget from the ckeditor_uploader package. The form class is called TemplateMesForm and contains a CharField named temp_html. from ckeditor_uploader.widgets import CKEditorUploadingWidget class TemplateMesForm(forms.RequestForm): temp_html = forms.CharField(label='Html:'), widget=CKEditorUploadingWidget()) I would like to add autocomplete to the temp_html field, but I'm unsure how to do so. Can you please help me with this? -
Django movie and director relation. Movie is not attached to the director
I'm making a model, consisting of a movie and a director. When I create a movie, I want the movie to be automatically owned by the director I selected but it's not working. class Movie(models.Model): name = models.CharField(max_length=100) category = models.CharField(max_length=100) imdb = models.DecimalField(max_digits=2, decimal_places=1) director = models.ForeignKey('Director', on_delete=models.DO_NOTHING) class Meta: verbose_name_plural = 'Movies' def __str__(self): return self.name class Director(models.Model): name = models.CharField(max_length=150) movies = models.ManyToManyField(Movie, related_name='movies', blank=True) class Meta: verbose_name_plural = 'Directors' def __str__(self): return self.name I am creating a new movie using django-admin page. for instance;django-admin creating movie However the movie is not automatically added to the director. Director I also want a movie to belong to only one director. How can I do these. I will be very glad if you can help me. Thanks in advance -
Broken pipe error when using @shared_task in Django
I am utilizing the celery library to execute tasks in the background even when the user closes or refreshes the page. Since the task takes some time, I opted to use celery. The algorithm works fine as long as I don't refresh or close the page. However, I encounter the "Broken pipe from ('127.0.0.1', 56578)" error when it occurs. I also attempted to update the account after executing nonFollowers_users(), but I received an error stating that the MySQL server had gone away. for id in accounts: account = Account.objects.get(id=id) #below method is @shared_task from celery nonFollowers_users(account, count, sleep) try: return JsonResponse({'success': True}) except (ConnectionResetError, BrokenPipeError): # the connection was closed, return a response with an appropriate status code return HttpResponse(status=499) -
I am unable how this line of code is working
class ReviewCreate(generics.CreateAPIView): # queryset=Review.objects.all() serializer_class=ReviewSerializer def perform_create(self, serializer): pk=self.kwargs.get('pk') # print(pk) watchlist=WatchList.objects.get(pk=pk) serializer.save(watchlist=watchlist) print("1") In the line serializer.save(watchlist=watchlist) why watchlist=watchlist is being passed.when i goes in CreateAPIView class of rest framework generic class there post method is implemented and from there on it is going into mixins class where create method is implemented like this. class CreateModelMixin: """ Create a model instance. """ def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): serializer.save() def get_success_headers(self, data): try: return {'Location': str(data[api_settings.URL_FIELD_NAME])} except (TypeError, KeyError): return {} As control goes to perform_create function it is saving the data in DB but in our views.py we are again doing serializer.save(watchlist=watchlist). Then why we are doing this again and how data is created in DB with only watchlist field value whereas Review model has other field also .Pls Help -
How to hierarchically output data?
Can you show exactly how to hierarchically output all the children and parents of a model instance. For example, I have a model and a code. How do I get all the parents and children of the object? Model: class Menu(models.Model): name = models.CharField(max_length=150) parent = models.ForeignKey( 'self', on_delete=models.CASCADE, blank=True, null=True, related_name='parent_name') def __str__(self): return self.name And the following code: def index(request, name='Magomed'): menu_item = Menu.objects.raw(''' WITH RECURSIVE menu AS ( SELECT id, parent_id, name FROM app_menu WHERE name = %s UNION SELECT app_menu.id, app_menu.parent_id, app_menu.name FROM app_menu JOIN menu ON app_menu.parent_id = menu.id OR app_menu.id = menu.parent_id) SELECT * FROM menu;''', [name]) -
Show the data in the Template according to the value of the select
Hi friends i need help as i am new to django! I need to show the information that I have saved in a table according to the option chosen from a select. When selecting the select option in the template I save the value in a variable using JavaScript (I do that without problems). I can't get the value of that variable to the get_context_data method, to later show it in my template. JavaScript code: $(function () { $('select[name="reporteFecha"]').on('change', function () { var fecha = $(this).val(); $.ajax({ url: window.location.pathname, type: 'POST', data: { 'action': 'search_fecha', 'fecha': fecha }, dataType: 'json', }) }); }); Views code: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ### I need to obtain within this function the value of the select in a variable ### context = { 'title': 'Reporte de Control de Electricidad', 'entity': 'Reporte Electricidad', 'list_url': reverse_lazy('cont_elect:Reporte_list'), 'form': ReportForm(), } return context I need to obtain in a variable inside the get_context_data the value that I capture with the JavaScript to later be able to show it in the template