Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to let user pick date AND time in the form?
I am trying to create a sort of To Do List. Majority of it is done. I can get user to enter the task, along with its detail and pick the starting and ending date. However, since I am rendering the fields in a form, I want the user to easily and conveniently enter the date and time. For that I have added a datepicker type widget. The datetime stored in database is still in ISO format. Now, the issue is that user can pick or enter the date perfectly fine. But it does not allow the user to enter the time. Once the date has been picked, the user can't enter the time. The code goes as under: class TaskForm(ModelForm): class Meta: model = TaskModel exclude = ["completed"] widgets = { 'title': TextInput(attrs={"class": "form-control"} ), 'detail': Textarea(attrs={"class": "form-control"}), 'start_time': DateInput(format = ['%d/%m/%Y %H:%M'], attrs={"type":"date", 'class': 'form-control datetimepicker-input', 'data-target': '#datetimepicker1'}), 'end_time': DateInput(format = ['%d/%m/%Y %H:%M'], attrs={"type": "date", 'class': 'form-control datetimepicker-input'}) } And the Model.py file is: class TaskModel(models.Model): title = models.CharField(max_length=30) detail = models.TextField(blank=True) start_time = models.DateTimeField() end_time = models.DateTimeField() completed = models.BooleanField(blank = True, null=True) The rest of the code is just simple and conventional Django based views and … -
Changing localhost to a custom domain name in Django
I have modified my ALLOWED_HOSTS variable to include "localhost", "127.0.0.1", and "mysite.com". Additionally, I have created a hosts file in the same directory as my manage.py file which contains the following line: 127.0.0.1 mysite.com Despite these changes, the localhost name does not appear to be updating. -
How can I pass a big html code block to a with variable in Django template?
I'm looking to pass a big html code block value to a with variable. How can I achieve that elegantly? Example: {% include "includes/template.html" with info="big html code block" %} I'm wondering how I can accomplish this elegantly. One option would be to escape all quotes and new lines. Is there any other better way to do that? -
I was testing my API the"GET" Request went fine, but when i tried the "POST" request it showed:405 "Method POST is not allowed" Django REST framework
405 Method Not Allowed "detail": "Method "POST" not allowed." #views.py from django.shortcuts import render from rest_framework.decorators import api_view from rest_framework.response import Response from . models import Product from . serializers import ProductSerializer @api_view(['GET']) def product_list(request): if request.method == 'GET': products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) if request.method == 'POST': serializer = ProductSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) -
How to fix Typeerror : unsupported operand type(s) for +: 'DeferredAttribute' and 'int'
I'm trying to count the number of reviews I've got for a movie. Here I'm increasing number_rating by 1 value every time you add a new review by new user. here is my views.py code. class ReviewCreate(generics.CreateAPIView): serializer_class = ReviewSerializer def get_queryset(self): return Review.objects.all() # ************ def perform_create(self, serializer): # provides overring | Save and deletion hooks | concrete class views pk = self.kwargs.get('pk') # also have perform_update perform_destroy watchlist_movie = watchlist.objects.get(pk=pk) review_user = self.request.user # we are getting current user / ERROR review_queryset = Review.objects.filter(watchlist=watchlist_movie, review_user=review_user) if review_queryset.exists(): # ERROR raise ValidationError('You have already reviewed this movie.') if watchlist.number_ratings == 0: # here providing validated data from serializers watchlist.avg_rating = serializer.validated_data['rating'] else: # (old rating + new rating) / 2 watchlist.avg_rating = (watchlist.avg_rating + serializer.validated_data['rating']) / 2 # for number of ratings == current ratings + one. watchlist.number_ratings = watchlist.number_ratings + 1 watchlist.save() serializer.save(watchlist = watchlist_movie, review_user = review_user) error is coming to the else part, adding + 1 to existing count to show the actual number count. What's this error about, How to solve this kind-of errors in future? -
I tried to run my django project and it shows the following error
(venv) PS C:\Users\User\OneDrive\Desktop\student-management-using-django-main> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 1348, in do_open h.request(req.get_method(), req.selector, req.data, headers, File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1282, in request self._send_request(method, url, body, headers, encode_chunked) File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1328, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1277, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1037, in _send_output self.send(msg) File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 975, in send self.connect() File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 941, in connect self.sock = self._create_connection( File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\socket.py", line 845, in create_connection raise err File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\socket.py", line 833, in create_connection sock.connect(sa) TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection f ailed because connected host has failed to respond During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "D:\student-management-using-django-main\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "D:\student-management-using-django-main\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "D:\student-management-using-django-main\venv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "D:\student-management-using-django-main\venv\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "D:\student-management-using-django-main\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config … -
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'accounts.User'
Im getting the following error AttributeError: Manager isn't available; 'auth.User' has been swapped for 'accounts.User' in my django project when I try to click on register button i have made where the email and password is sent to the backend. I have acoounts app where I have the following code in the files: backend.py: from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model class EmailBackend(ModelBackend): def authenticate(self, request, email=None, password=None, **kwargs): User = get_user_model() try: user = User.objects.get(email=email) except User.DoesNotExist: return None else: if user.check_password(password): return user return None models.py: from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.contrib.auth import get_user_model from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' objects = CustomUserManager() def __str__(self): return self.email views.py: from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login as auth_login from django.contrib.auth import authenticate from .models import User from django.contrib import messages def register(request): if request.method == 'POST': … -
template tag is not working djaongo framework
I am currently working with Django framework and I am facing an issue with the template tag {{msg}}. It seems to not work when used within block comments. ` # views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def projects(request): msg ='hello,you are on the projects page' return render(request,'my_project_1_app/my_project.html',{'msg':msg}) def project(request,pk): return render(request,'my_project_1_app/single_project.html') ` ` {% comment %} my_project.html {% endcomment %} {% extends 'main.html'%} {% block content%} {{msg}} <h1> my_project templates</h1> <p>hello iam from paragrap in my_project.html</p> {% endblock content%} `` Here is an example of how I am using it: {# Some comment #} {{msg}} But the {{msg}} tag is not rendering anything. Is there a way to make it work within block comments? -
have some issue in my script but not able to debug oit
i am implementing the auto complete search bar in my django project and below is my script for showing the suggestion the renderList function is not working. render result is working. i want showing data on front end for that my renderList function need to work but somehow it is not working.becz there is the format in which the data will be displayed. <div class="header-right"> <form action="{% url 'Search' %}"> <div id="mobile-autocomplete" class="autocomplete"> <input class="autocomplete-input" name="query" placeholder="Search" /> <ul class="autocomplete-result-list autocomplete-result- list-mobile" style="padding: 10px; max-height:842px;"></ul><hr> </div> </form> <script> new Autocomplete('#mobile-autocomplete', { search: input => { const url = `{% url 'search_address'%}?query=${input}`; return new Promise(resolve => { fetch(url) .then(response => response.json()) .then(data => { resolve(data.data || []); }) .catch(error => { console.error('Error fetching autocomplete results:', error); resolve([]); }); }); }, onSubmit: result => { const words = result.split(' '); const query = words.join(' '); window.location.assign(`/Search?query=${query}`); }, renderResult: (result, props) => { console.log('Rendering result:', result); const { name, image, url } = result; const item = document.createElement('div'); item.classList.add('autocomplete-item'); const imageContainer = document.createElement('div'); imageContainer.classList.add('autocomplete-image'); const img = document.createElement('img'); img.src = image; img.alt = name; imageContainer.appendChild(img); const nameContainer = document.createElement('div'); nameContainer.classList.add('autocomplete-name'); const link = document.createElement('a'); link.href = url; link.textContent = name; nameContainer.appendChild(link); item.appendChild(imageContainer); item.appendChild(nameContainer); … -
How can I conditionally pass a value to a with variable in Django template?
I'm looking to pass a value to a variable based on a condition in my code. Here's the pseudo code of what I'm trying to achieve: {% include "includes/template.html" with info=if condition: a else: b %} I'm wondering how I can accomplish this. Any suggestions or guidance would be greatly appreciated! -
While creating reviews getting error "Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x1032d5660>."
Here is my views.py code to create reviews for a movie: class ReviewCreate(generics.CreateAPIView): serializer_class = ReviewSerializer def get_queryset(self): return Review.objects.all() def perform_create(self, serializer): pk = self.kwargs.get('pk') watchlist_movie = watchlist.objects.get(pk=pk) review_user = self.request.user review_queryset = Review.objects.filter(watchlist=watchlist_movie, review_user=review_user) if review_queryset.exists(): raise ValidationError('You have already reviewed this movie.') if watchlist.number_ratings == 0: watchlist.avg_rating = serializer.validated_data['rating'] else: watchlist.avg_rating = (watchlist.avg_rating + serializer.validated_data['rating']) / 2 watchlist.number_ratings += 1 watchlist.save() serializer.save(watchlist=watchlist_movie, review_user=review_user) Here is my urls.py patterns: urlpatterns = [ path('list/', WatchList.as_view(), name='watchlist'), path('<int:pk>/', WatchListDetail.as_view(), name='watchlist-detail'), path('stream/', StreamPlatform.as_view(), name='streamplatform'), path('stream/<int:pk>/', StreamPlatformDetail.as_view(), name='streamplatform-detail'), path('<int:pk>/review-create/', ReviewCreate.as_view(), name='review-create'), path('<int:pk>/reviews/', ReviewList.as_view(), name='review-list'), path('review/<int:pk>/', ReviewDetail.as_view(), name='review-detail'), ] And my serializer file code for review serializer: class ReviewSerializer(serializers.ModelSerializer): review_user = serializers.StringRelatedField(read_only=True) class Meta: model = Review exclude = ('watchlist',) The code is intended to allow users to submit reviews for movies. However, the original code contained some errors, which I have corrected. I've also added indentation, formatted the code blocks, and included the appropriate markdown. -
in my new Django project my html file isn't rendering
When I have my index.html file inside the template folder alone, it renders fine. However, when I put my app name as a folder inside of the template folder, the page doesn't render. I am sure the file path is correct, and the html file is correct except for one line of h1. urls.py (entire project level) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('students.urls')), ] urls.py (students app level) from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] views.py (students app level) from django.shortcuts import render def index(request): return render(request, 'students/index.html') -
Best practices for architecting a multi-tenancy web application on Azure
I am working on designing a multi-tenancy web application on Azure and I would like some guidance on the best architectural practices. I want to ensure scalability, security, cost-effective, and efficient resource utilization while accommodating multiple tenants on the same infrastructure. Here are some specific areas I'm looking for advice on: Tenant isolation: What are the recommended approaches for achieving isolation between tenants within the application? Are there any Azure services or features that can help with this? Database design: How should I structure the database to support multiple tenants? Should I use a separate database for each tenant or a shared database with tenant-specific schemas? Authentication and authorization: What strategies should I consider for managing user authentication and authorization across tenants? Are there any Azure services that can simplify this process? Scaling and resource allocation: How can I effectively scale the application to handle the increasing number of tenants and their demands? Are there any Azure services or patterns that can assist with auto-scaling and resource allocation? Monitoring and diagnostics: What tools and practices should I implement to monitor the performance and health of the multi-tenancy application? Are there any Azure services or third-party tools that can help with … -
Django 4.2.2 not respecting STORAGES['default']['BACKEND']
Using settings.py: STORAGES = { "staticfiles": { "BACKEND": "storages.backends.s3boto3.S3Boto3Storage", }, "mediafiles": { "BACKEND": "storages.backends.s3boto3.S3Boto3Storage", }, "default": { "BACKEND": "storages.backends.s3boto3.S3Boto3Storage", }, } and running: from django.conf import settings print('settings.DEFAULT_FILE_STORAGE', settings.DEFAULT_FILE_STORAGE) prints: settings.DEFAULT_FILE_STORAGE django.core.files.storage.FileSystemStorage Media is writing to local and not S3 and this must be why. Static, for some reason, writes to S3 no problem. Any help or ideas would be appreciated. The full codebase can be seen here: https://github.com/rkuykendall/Simplici7y -
Is Using Psycopg2 with Django Ok?
I prefer using Psycopg2 over Django's built-in database handling system. Are there any major disadvantages to this? Would this not work well with larger-scale projects? Are there any important features that I would be missing out on this way? -
Validate a model instance for unique drf
I am working on a "Recipes" model and I want to prevent the creation of duplicate models with the same fields. Specifically, I want to throw a validation error if a model instance already exists with the same field values. This is my current code: def validate_recipe(self, value): recipes = Recipe.objects.all().filter(author=self.context['request'].user) for rec in recipes: if rec._meta.fields == value._meta.fields: raise serializers.ValidationError( {'errors': 'Do you have this recipe!'} ) return value Here are the images of the output I am currently getting: enter image description here enter image description here -
Dynamically scheduled tasks
I successfully configured Celery on my Django app and tested it. The test run was successful, as shown by the following output: celery -A concentrApp call mytask 0016f381-ed04-4a44-8c7a-c091a66dce0a [2023-06-17 13:46:28,465: INFO/MainProcess] Task mytask[0016f381-ed04-4a44-8c7a-c091a66dce0a] received [2023-06-17 13:46:28,477: INFO/ForkPoolWorker-8] Task mytask[0016f381-ed04-4a44-8c7a-c091a66dce0a] succeeded in 0.009182458000005056s: None ` Now, I would like to take this a step further and make the task dynamic. My goal is to create an endpoint that accepts parameters such as time, and param, and then run the task every sunday-thursday in the given hour using the provided parameter. This will allow me to customize the task execution based on user input, and make it several times that the user want. Thank you -
مشکل ارور :Page not found (404) در جنگو
I wrote a program in Zang, but whatever I do, it gives this error: 404 Using the URLconf defined in storefront.urls, Django tried these URL patterns, in this order: admin/ The current path, contact/, did not match any of these. URLs.py code: from django.urls import path from .views import save_user urlpatterns = [ path('save-user/', save_user, name='save_user'), ] There is no error during execution, but when I enter the code: http://localhost:8000/myapp/save-user/ in the browser, it gives an error on that page. -
can't open the page "127.0.0.1:8000" because the server dropped the connection unexpectedly
I want to run a Django project via Docker. I wrote a Dockerfile and docker-compose, but when I run the Django project it says : "Safari can't open the page Safari can't open the page "127.0.0.1:8000" because the server dropped the connection unexpectedly. This problem sometimes occurs if the server is busy. Wait a few minutes and try again." Dockerfile FROM python:3.9-slim WORKDIR /app RUN pip3 install --upgrade pip wheel COPY . . ADD requirements.txt . RUN pip3 --no-cache-dir install -r requirements.txt CMD ["python3", "manage.py", "runserver", "127.0.0.1:8000"] docker-compose.yml version: '3.6' services: invite_service: container_name: invite_service build: dockerfile: Dockerfile context: . ports: - "8000:8000" ALLOWED_HOSTS in Django settings ALLOWED_HOSTS = ['localhost', '127.0.0.1', '0.0.0.0'] -
psycopg2.OperationalError triyng to connect postgres to django
i am getting this error when i try to runserver: `Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\db\backends\base\base.py", line 289, in ensure_connection self.connect() File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\db\backends\base\base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\db\backends\postgresql\base.py", line 275, in get_new_connection connection = self.Database.connect(**conn_params) File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\psycopg2_init_.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Zhadi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Zhadi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\core\management\commands\runserver.py", line 136, in inner_run self.check_migrations() File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\core\management\base.py", line 574, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\db\migrations\loader.py", line 58, in init self.build_graph() File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\db\migrations\recorder.py", line 81, in applied_migrations if self.has_table(): File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\db\migrations\recorder.py", line 57, in has_table with self.connection.cursor() as cursor: File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\db\backends\base\base.py", line … -
DJANGO: I have genres in my database, and django doesnt display them in my page('shop.html') even though i used loop
I am trying to modify a Django website. One of the webpages lists video games. Each game has a genre property, and I want to allow the user to filter the games based on their genres. However, each game can have multiple genres. Therefore, I created a Genre model that has a "title" property, and each Game has a many-to-many relationship with genres. I have already created the Genre model and created a page that lists all the existing genres. Now I want to create a page that lists all the games that have a certain genre. Here is my code below: in models.py class Genre(models.Model): title = models.CharField(max_length=255, verbose_name='Название жанра') def __str__(self): return self.title in views.py def shop_page(request): return render(request, 'store/shop.html') def genre_page(request, pk): genre = Genre.objects.get(pk=pk) genres = Genre.objects.all() games = Game.objects.filter(genres=genre) context = { # 'genre': genre, 'genres': genres, 'games': games } return render(request, 'store/shop.html', context) in urls.py path('shop/', shop_page, name='shop_page'), path('genre/', genre_page, name='genre'), in shop.html <ul class="trending-filter"> <li> {% for genre in genres %} <a class="is_active" href="{% url 'genre' genre.pk %}" data-filter="*">{{ genre.title }}</a> {% endfor %} </li> </ul> -
How can I use skfuzzy in Django?
I have created a Django project and I want to implement a simple fuzzy logic with three inputs and one output. However, when I import "skfuzzy" in Django views and reload the page, I get a Gateway Timeout error after 2 minutes (even without any implementation, just importing "skfuzzy"). I have run "pip3 install scikit-fuzzy" in the project virtual environment, and everything seems to be working fine. The code runs without a problem in the terminal, but it doesn't work in the Django project. Why is this happening? -
Django filter a model in the template
I want to be able to filter a model in the template (or find a different solution to fix my problem). The relevant models look like this: class CommissionElection(models.Model): title = models.CharField(max_length=64) commission = models.ManyToManyField(Commissie, related_name="elections") class ElectablePerson(models.Model): commission = models.CharField(max_length=128) election = models.ManyToManyField(CommissionElection, related_name="electables") class Commissie(models.Model): commissie = models.CharField(max_length=64) Here Commissie is a model from a different app. I have created a page for a specific election, now I want on that page a list per commission which states all the ElectablePersons that stated themselves electable for that commission (and for that election). I tried the following in my template: {% for commission in election.commission.all %} {{ commission }} {% for electable in election.electables.filter(commission=commission) %} {{ electable}} {% endfor %} {% endfor %} This gives the error Could not parse the remainder: '(commission=commission)' from 'election.electables.filter(commission=commission)' Is there anyway I could filter the model in the template or is there a different way I could do this? -
How to add to card without login, without user authentication. Help in session method of Django
How to add to card without login, without user authentication. Help in session method of Django. I am stuck in this. How to modify this code, so I can easily implement add to card, add to wishlist without login and also connected with users. Models.py class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) product_qty = models.IntegerField(null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) class Wishlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) wishlist.py from django.http import JsonResponse from django.shortcuts import render, redirect from django.contrib import messages from buyjoi.models import Product, Cart, Wishlist from django.contrib.auth.decorators import login_required @login_required(login_url='loginpage') def wishlistpage(request): wishlistitem = Wishlist.objects.filter(user=request.user) context = {'wishlistitem':wishlistitem} return render(request, 'wishlist.html', context) def addtowishlist(request): if request.method == 'POST': if request.user.is_authenticated: prod_id = int(request.POST.get('product_id')) product_check = Product.objects.get(id=prod_id) if(product_check): if(Wishlist.objects.filter(user=request.user, product_id=prod_id)): return JsonResponse({'status':"Product already in wishlist"}) else: Wishlist.objects.create(user=request.user, product_id=prod_id) return JsonResponse({'status':"Product added to wishlist"}) else: return JsonResponse({'status':"No such product found"}) else: return JsonResponse({'status':"Login to continue"}) return redirect('/') def deletewishlistitem(request): if request.method == 'POST': if request.user.is_authenticated: prod_id = int(request.POST.get('product_id')) if(Wishlist.objects.filter(user=request.user, product_id=prod_id)): wishlistitem = Wishlist.objects.get(product_id=prod_id) wishlistitem.delete() return JsonResponse({'status':"Product removed from wishlist"}) else: Wishlist.objects.create(user=request.user, product_id=prod_id) return JsonResponse({'status':"Product not found in wishlist"}) else: return JsonResponse({'status':"Login to continue"}) return redirect('/') checkout.py from http.client import HTTPResponse from django.shortcuts … -
Is it possible to use update_state and progress_observer within a function executed by a Celery task instead of directly inside the task itself?
I am developing a Django app that browses a website, selects a comic, and downloads it in the background with Celery. In the task.py file, I have a download_comic() function decorated with @shared_task(). The function checks the URL's hostname and uses different child classes of the base class FileHost to download the file. The actual download is done inside the class method, not on the task function. I came across this article (https://buildwithdjango.com/blog/post/celery-progress-bars/) that suggested using task.update_state and progress_observer.set_progress for progress monitoring. However, I am not sure if I can use these functions inside a class method or not. Here's a snippet of the FileHost class and download() method for reference: class FileHost: def __init__(self, url): self.url = url r = requests.get(self.url) self.soup = BeautifulSoup(r.content, "html.parser") def download_file(self): # Implement the file download logic here raise NotImplementedError() def download(self, filename, direct_link): response = requests.get(direct_link, stream=True) temp_path = Path('/tmp') / filename if 'Content-Disposition' in response.headers: content_disposition = response.headers['Content-Disposition'] temp_path = Path('/tmp') / content_disposition.split("=", -1)[-1] if response.status_code == 200: total_size = int(response.headers.get('content-length', 0)) downloaded_size = 0 with open(temp_path, "wb") as file: for chunk in response.iter_content(chunk_size=4096): if chunk: file.write(chunk) downloaded_size += len(chunk) # Calculate the progress percentage progress = int((downloaded_size / total_size) * …