Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hello, I wrote the program so that the user enters the form, then it is authenticated, then it is logged in, but it says failure. Can you guide me?
class Register(View): def get(self, request: HttpRequest): register_form = RegisterForm() context = {'register_forms': register_form} return render(request, "register.html", context) def post(self, request: HttpRequest): register_form = RegisterForm(request.POST) if register_form.is_valid(): email = register_form.cleaned_data['email'] username = register_form.cleaned_data['username'] if RegisterModel.objects.filter(email__iexact=email).first(): messages.error(request, "The email has already been found") elif RegisterModel.objects.filter(username__iexact=username).first(): messages.error(request, "The username has already been found") else: # new_user = register_form.save(commit=False) # new_user.is_active = get_random_string(72) register_form.save() print("", tag="success", tag_color="green", color="yellow") # Authentication the user username = register_form.cleaned_data['username'] password = register_form.cleaned_data['password'] user = authenticate(username=username, password=password) if user: login(request, user) time.sleep(2) messages.success(request, "Successfully registered and logged in!") print(register_form.cleaned_data, tag="success",tag_color="green", color="yellow") else: messages.error(request, "Invalid username or password. Please try again.") context = {'register_forms': register_form} return render(request, "register.html", context) Authenticate successfully -
Django not writing to database but print statements are working and updated
I am using Django as my Web framework. The relevant function is def addWeight(request): if request.method == "GET": form = weightForm() return render(request, "base/weight.html", {"form": form}) if request.method == "POST": try: form = weightForm(request.POST) if not form.is_valid(): return HttpResponseBadRequest("Error with your form") data = form.cleaned_data day = macro_day.objects.get_or_create(owner=request.user, date=data["date"]) print(data["weight"]) day[0].weight = data["weight"] print(day[0]) print(day[0].weight) return HttpResponse(status=204)` <form action="weight" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="SUBMIT"> </form> The form object is: class weightForm(forms.Form): date = forms.DateField(label="Date") weight = forms.IntegerField(label="Weight", min_value=0, max_value=500) day[0].weight reflects the value sent into the function by the webform but when I actually go into my database or call the object it appears that the change hasn't been made. I have another function implemented like this and I don't seem to have the same issue with it. What am I doing wrong? -
Django: While Button Pressed
I am currently working on a control for a camera (visca-over-ip) having 4 buttons that control in which direction the camera should turn. Currently I am in the testing phase and now need these 4 Buttons to set a variable in django to TRUE if the Button is held. If it was let go something else should happen. It should be something Like: index.html: <button>Left</button> camera.py button_pressed = (Code that checks if button is held down) def button_hold(): while button_pressed == True: (do something) -
Deploying django project on a 2019 windows server virtual machine (offline)
I've been working on a Django project for a while, and after completing it, I want to deploy it so my colleagues can work with it. I have a virtual machine (Windows Server 2019) that doesn't have internet connection. I copied my Django project there, but the first problem I faced was with the Python packages. Since my project has its own virtual environment, I assumed that by copying the project, everything would work. However, I had to reinstall all the packages offline using the wheel files. This has made me question the purpose of the virtual environment. I also intend to deploy it using an Apache server. When deploying a Django project with Apache, I need the mod_wsgi package. However, when I tried installing it, I encountered this error, even though I have already installed Visual Studio C++ Build Tools 14 : building 'mod_wsgi.server.mod_wsgi' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for mod_wsgi Running setup.py clean for mod_wsgi Failed to build mod_wsgi ERROR: Could not build … -
Django - Downloading a file to local downloads folder
In Django, I am trying to download an entire album into local "downloads" default folder on the client's PC. but how do I specify the target folder? currently, my code doesn't nothing. from views.py: def download_file(lfile): uploaded_file = lfile response = HttpResponse(uploaded_file.image, content_type='application/force-download') response['Content-Disposition'] = f'attachment; filename="{lfile.fname}"' return response def download_album(request, albumpk, albumowner): album = Category.objects.filter(id=albumpk) lfiles = Photo.objects.filter(category=albumpk) for lfile in lfiles: dfile = download_file(lfile) return redirect('albumlist', albumowner) -
Subtract two date fields using computed twig in Drupal 10
Would be grateful for some assistance on this. I am building a webform using the webforms module in Drupal 10 and I want to subtract two date fields and as a result display the difference between the dates. For example, {{ 2024-01-11 - 2024-01-10 }} = {TheDifferenceInDays}. Thanks I have tried using the following expression in my computed twig field however this is returning a value of 0 - is that because the date fields need to be in a specific format? {{ date1 - date2 }} -
Pagination does not work when i use generil.ListView class in Django
I want to create pagination in Django for order list. It seems everything is coded correctly but for some reason when i get to webpage, instead of links to other pages it shows 'Page of . ' Apologies for formatting of this post as it's my first time posting a question and note that there are 7 objects of order, therefore there should be a page. My code looks like this: models.py class Order(models.Model): date = models.DateField('Date', null=True, blank=True) car = models.ForeignKey(Car, on_delete=models.SET_NULL, null=True) ORDER_STATUS = ( ('p', 'Processing'), ('o', 'Ordered'), ('s', 'In service'), ('c', 'Completed'), ('t', 'Taken back by customer') ) status = models.CharField(max_length=1, choices=ORDER_STATUS, blank=True, default='p') @property def order_total_price(self): order_rows = self.order_row.all() total_price = sum(row.total_price for row in order_rows) return round(total_price) @property def order_rows(self): return ', '.join(str(el) for el in self.order_row.all()) def __str__(self): return f'{self.car}' views.py class OrderListView(generic.ListView): model = Order context_object_name = "orders" template_name = "orders.html" paginate_by = 5 urls.py from django.urls import path, include from . import views urlpatterns = [ path('index/', views.index, name="index"), path('cars/', views.cars, name='cars'), path('car/<int:pk>/', views.car_detail, name='car_detail'), path('orders/', views.OrderListView.as_view(), name='orders'), path('order/<int:order_id>/', views.order_detail, name='order_detail'), path('search/', views.search_results, name='search_results'), path('', views.index, name='index'), ] and orders.html {% extends 'base.html' %} {% block header %}Orders{% endblock %} {% … -
Random Not Found</h1><p>The requested resource was not found on this server.</p>
I'm experiencing an issue which seems to be related somehow to Gunicorn + Django and I can't find the cause of the problem. I start Gunicorn using this command: gunicorn config.wsgi --bind=0.0.0.0:5000 --timeout=300 --workers=2 --threads=4 --worker-class=gthread --name=api --log-level debug --error-logfile gunicorn_error.log --access-logfile - --capture-output and then while trying to curl for example CSS file : curl http://0.0.0.0:5000/STATIC_DIR/CSS/FILE.css?v23423424 sometimes I get the correct response and CSS file but sometimes: <h1>Not Found</h1><p>The requested resource was not found on this server.</p> interestingly, if, for example, I kill 2 of the 3 gunicorn processes, they will start again in a moment and then everything will work properly. I can't find anything in the logs which can indicate the reason. Has anyone encountered a similar problem? enable DEBUG log try different types of worker-class -
Rendering data on the same template from different models
I want to render data on the same template(shared template) from different models I have the following models in models.py from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): """ Custom user model to support role-based authentication. """ USER_TYPE_CHOICES = [ ('client', 'Client'), ('staff', 'Staff'), ('admin', 'Admin'), ] user_type = models.CharField(max_length=10, choices=USER_TYPE_CHOICES, default='client') phone = models.CharField(max_length=15, blank=True, null=True) email = models.EmailField(unique=True) address = models.CharField(max_length=255, blank=True, null=True) # Specify unique related_name for groups and user_permissions user_groups = models.ManyToManyField( 'auth.Group', related_name='custom_user_groups', blank=True, verbose_name='groups', help_text='The groups this user belongs to.', ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='custom_user_permissions', blank=True, verbose_name='user permissions', help_text='Specific permissions for this user.', ) def get_user_type_display(self): """ Display the user type in a more readable format. """ return dict(CustomUser.USER_TYPE_CHOICES)[self.user_type] class Meta: swappable = 'AUTH_USER_MODEL' class GarbageCollectionRequest(models.Model): """ Represents a request for garbage collection made by a client. """ client = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='garbage_requests') request_date = models.DateTimeField(auto_now_add=True) request_details = models.TextField(max_length=255) address = models.CharField(max_length=255) phone = models.CharField(max_length=15, blank=True, null=True) email = models.EmailField() is_assigned = models.BooleanField(default=False) collection_date = models.DateTimeField(blank=True, null=True) def __str__(self): return f"Request #{self.pk} - {self.client.username} - {self.address}" And my class-based views.py from django.shortcuts import render, redirect from django.shortcuts import render, get_object_or_404, redirect from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.urls … -
CSRF verification failed. Request aborted. (CSRF token not set while clearly being present)
Yes I added the csrf token to my form, yes I added post method in the form, yes I checked if the server send cookie matches the client side cookie. Als other good context maybe is that I have loginrequiredMixin on my homepage view so it redirects you to the login page when trying to access it but don't think that is the problem. Django is saying the reason is that it can't find the csrf token but I checked what its called in the source code of Django and it matches the key and has a matching value from the one send from the server which is request_csrf_token = request.POST.get("csrfmiddlewaretoken", "") here are the forms I'm using which have inherited Django default sign up and login forms: class LoginForm(AuthenticationForm): def __init__(self, request=None, *args, **kwargs): super(LoginForm, self).__init__(request, *args, **kwargs) self.fields['username'].widget = forms.TextInput(attrs={'class': 'form-control', 'id': 'username'}) self.fields['password'].widget = forms.PasswordInput(attrs={'class': 'form-control'}) self.fields['remember_me'] = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={'class': 'custom-control-input', 'id': 'remember-me'}) ) class SignUpForm(UserCreationForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'})) username = forms.CharField(max_length=100, required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': 'form-control'})) password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput(attrs={'class': 'form-control'})) im losing my shit here, what am I doing wrong? <form method="POST" id="formAuthentication" class="mb-3"> <div class="input-group mb-3"> {{ form.username|attr:"placeholder:Username"|add_class:'form-control' … -
how to rach model from the other model in django?
if i have model called Reaction and it has ForeignKey refers to the other model called User. now i know that i can reach the User model from the Reaction model but i have a list of more that 1000 users came from User model , and i want to reach the ractions of them from the Reaction model. how can i do that without taking each user from User model and get it through Reaction model. these are my models : class User(models.Model): name = models.TextField() class Reaction(models.Model): from_user = models.ForeignKey(User, on_delete=models.PROTECT, default=None, related_name="reaction_from_user") to_user = models.ForeignKey(User, on_delete=models.PROTECT, default=None, related_name="reaction_to_user") date = models.DateField(null=True) time = models.TimeField(null=True) type_of_reaction = models.TextField() have_been_seen = models.BooleanField(default=False , null=True) -
Django telling me an existing template does not exist. | {% include %}
I'm currently trying to point to a template in Django which is not in the directory with which is the calling template is sitting in. This is the relative path which has been copied and pasted here: static\libraries\templates\our-tech-stack.html Root | |---static | | | |--libaries | | | |--templates | | | |--<our-tech-stack.html> |---templates | |--<calling-template.html> This is the include in the <calling-template.html> {% include "../static/libraries/templates/our-tech-stack.html" %} This is the setup in my settings.py `'DIRS': [ . ... ... os.path.join(BASE_DIR, 'static/libraries/templates'), ... ... ... ],` As you can see this has been correctly set up, so why is Django telling me that the template does not exist when it very clearly does? Read office documentation - however, the official documentation is wrong. -
Django manage.py makemigrations: Show differences between model and database
I occasionally run into a problem where manage.py makemigrations will generate migrations that, as far as I can tell, concern models or model fields I didn't touch. Is there any way to find out what differences between the model and the database manage.py makemigrations found, that make it think a migration is needed? I searched the web and checked the django-admin and manage.py documentation but couldn't find a way to make makemigrations "explain itself" or to find differences between my models and database any other way. Any hints would be greatly appreciated :) -
Django posts page not displaying
System check identified no issues (0 silenced). January 11, 2024 - 16:23:58 Django version 5.0, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [11/Jan/2024 16:24:00] "GET /posts/?Category=All HTTP/1.1" 200 9404 [11/Jan/2024 16:24:00] "GET /static/images/MyPic.jpg HTTP/1.1" 304 0 [11/Jan/2024 16:24:00] "GET /static/images/IntroPicture2.png HTTP/1.1" 304 0 [11/Jan/2024 16:24:02] "GET /posts/?Category=All HTTP/1.1" 200 9404 -
"operator does not exist: bigint = bigint[]" Error when I want to use __in lookup agains ArrayAgg field Django
#views.py queryset = User.objects.all() queryset = queryset.annotate( request_ids=ArrayAgg("requests__id") ) unread_messages = Request.objects.filter( pk__in=OuterRef("request_ids") ) queryset = queryset.annotate( unread_messages=Coalesce(Subquery(unread_messages), 0) ) I want to achieve something like this in SQL: WITH user_requests AS ( SELECT uchat_user.username, Array_Agg(uchat_request.id) AS request_ids FROM uchat_user LEFT JOIN uchat_request ON uchat_request.refugee_id = uchat_user.id GROUP BY uchat_user.username ) SELECT *, ( SELECT COUNT(*) FROM uchat_request WHERE uchat_request.id IN (SELECT unnest(user_requests.request_ids)) ) AS total_requests FROM user_requests However I get this error (table might be different but the overall the exception is like this): operator does not exist: bigint = bigint[] LINE 1: ...efugee_id" FROM "uchat_request" U0 HAVING U0."id" IN (ARRAY_... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Could you please help with that? -
My Django App not displaying the right page
System check identified no issues (0 silenced). January 11, 2024 - 16:01:17 Django version 5.0, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [11/Jan/2024 16:01:27] "GET /index/ HTTP/1.1" 200 9404 [11/Jan/2024 16:01:42] "GET /search/ HTTP/1.1" 200 9404 [11/Jan/2024 16:01:50] "GET /posts/?Category=All HTTP/1.1" 200 9404 [11/Jan/2024 16:02:56] "GET /admin HTTP/1.1" 200 9404 [11/Jan/2024 16:03:02] "GET /admin/ HTTP/1.1" 200 9404 [11/Jan/2024 16:03:53] "GET /posts/?Category=All HTTP/1.1" 200 9404 [11/Jan/2024 16:03:59] "GET /posts/?Category=Mythology HTTP/1.1" 200 9404 I am not able to see the Posts Page -
which library to use with django for generating word, excel and PDF documents?
I would like to generate a document from django. I wonder which library I can use to do that. I would like to generate word, excel and PDF documents. I tried to find a library in Django, but I did not find any good plugin or library. -
@login_required() next paramater has a backslash that's causing the url to not be found
When a non-logged in user attempts to create a listing, when he clicks the create listing link, he will be redirected to the login page before being able to create the listing. The redirection to login page works, but after logging in successfully, it receive a NoReverseMatch error. when i print the next parameter, I get '/create'. but my create url is 'create' only, so this is the reason why i'm having this error. why does it have a backslash at the url? i can create a code to remove the backslash, but is there a better way to do it? urls.py urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("listing/<int:listing_id>", views.listing, name="listing"), path("create",views.create, name="create"), ] views.py def login_view(request): if request.method == "POST": # Attempt to sign user in username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) # Check if authentication successful if user is not None: login(request, user) next_url = request.POST.get('next') print(next_url) if next_url and next_url !='/login': return HttpResponseRedirect(reverse(next_url)) else: return HttpResponseRedirect(reverse('index')) else: return render(request, "auctions/login.html", { "message": "Invalid username and/or password." }) else: print(request.GET.get('next')) return render(request, "auctions/login.html") login.html {% extends "auctions/layout.html" %} {% block body %} <h2>Login</h2> {% … -
Keycloak with multiple django servers
I would like to ask for advice about this problem. My current setup with single django server and keycloak is this: for login handling, I am using django-allauth library (django-allauth All bellow steps are assuming, user is working in browser. Keycloak serves as user provider and login service for django: user goes to django.server/login user is redirected to keycloak login page user logs in backend checks if user exists in django DB, if not, creates it (this is done by django-allauth) user is redirected to django home page all after-login user activities with django does not require keycloak anymore.. all permission hadnling is done by pure django (django.contrib.auth). user is identified through session. I am not using any keycloak functionalities (resources, scopes,...) EXCEPT roles (roles are synced to django as groups) My current problem is this: What if I have multiple django servers and I want them to communicate with each other with permissions of logged in user? Example: User visits djangoServer_A view which requests djangoServer_B view (which requires some authentication) and response of djangoServer_B view is returned to django_server_A view... Some pseudo-code: # djangoServer_A from django.shortcuts import render from django.contrib.auth.decorators import login_required @login_required def serverA_view(request): serverB_response = call_serverB_view(**some_parameters) return … -
Celery daemon service is not triggering target function on schedule basis in Django
celery.py under main project MAP/map import os from celery import Celery from celery.schedules import crontab from django.apps import apps os.environ.setdefault('DJANGO_SETTINGS_MODULE', map.settings') app = Celery("Celery App") app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: [app.name for app in apps.get_app_configs()]) app.conf.beat_schedule = { 'load_trafic_attendance': { 'task': traffic.tasks.load_traffic_data', 'schedule': crontab(minute="*/10") }, } task function under traffic app in task.py file @app.task(name=traffic.tasks.load_traffic_data') def load_traffic_data(): …………………… …………………… celery.conf file under script app # Celery configuration options CELERY_BIN="/home/sam/MAP/env/bin/celery" CELERY_APP="map" CELERYD_NODES="worker beat" CELERYD_CHDIR="/home/sam/MAP/" CELERYD_OPTS="--time-limit=300 --concurrency=8" CELERYD_LOG_LEVEL="INFO" CELERYD_LOG_FILE="/home/sam/logs/%n%I.log" CELERYD_PID_FILE="/home/sam/run/%n.pid" celery.service file in /etc/systemd/system/ dir [Unit] Description=Celery Service After=network.target [Service] Type=forking User=sam Group=sam WorkingDirectory=/home/sam/MAP/ EnvironmentFile=/home/sam/MAP/scripts/celery.conf ExecStartPre=/bin/bash -c 'mkdir -p /home/sam/logs; chown sam:sam /home/sam/logs; mkdir -p /home/sam/run; chown sam:sam /home/sam/run' ExecStart=/bin/sh -c '${CELERY_BIN} multi start ${CELERYD_NODES} -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait ${CELERYD_NODES} --pidfile=${CELERYD_PID_FILE}' ExecReload=/bin/sh -c '${CELERY_BIN} multi restart ${CELERYD_NODES} -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} {CELERYD_OPTS}' [Install] WantedBy=multi-user.target The above setup does not call the load_traffic_data function at all though it should be called in every 10 minutes. However when we run two debug commands on shell after entering into virtual env it calls the function at every 10 minutes. what I am missing here to daemonize the service? two debug command are: celery -A map beat --loglevel=debug And celery … -
Problem to use Vuejs in Django template with django-vite
Hi i have a simple django app and i want to use Vue3 for render component on the page Lets show my code then describe my problem. < -- index.html - loaded with django --> {% load django_vite %} {% vite_hmr_client %} {% vite_asset 'js/main.js' %} <div id="app"> <counter /> </div> this is main.js scripts that use a counter.vue component import { createApp } from 'vue'; import Counter from './Counter.vue'; const app = createApp({}) app.component('counter',Counter) app.mount("#app") Counter.vue file <template> <button>{{count}}</button> </template> <script> export default { data() { return { count: 12, }; }, }; </script> When i run Django server and npm run dev, nothing show in page and also no error, but if i use below code for main.js and in index.html vue component rendered. const app = createApp(Counter) app.mount("#app") index.html {% load django_vite %} {% vite_hmr_client %} {% vite_asset 'js/main.js' %} <div id="app"></div> But i cant use this method(single component) for render i need multi components for single vue app. -
How to deploy django asgi application in vercel...?
I created a chatting application on django with songs synchronisation feature For that purpose I used channels and Daphne I tried many times but got all errors Actually I didn't know How to deploy asgi, real-time apps on vercel I really need to deploy my app on vercel -
POST http://localhost:8000/date 500 (Internal Server Error)
I don't know whats wrong with me. everytime its gives POST http://localhost:8000/date 500 (Internal Server Error). my views.py: @csrf_exempt def date(request): if request.method == 'POST': data = json.loads(request.body) selected_date = data.get('selectedDate') # Now you can do something with the selected_date, for example, save it to a model # YourModel.objects.create(your_date_field=selected_date) data = order_transactions.objects.create(settlement_date=selected_date) return JsonResponse({'message': 'Date saved successfully'}) else: return JsonResponse({'message': 'Invalid request method'}, status=400) my urls.py: path('date', date), my react: async function toBeCalledByEventListener() { await fetch('/date', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ selectedDate }), }) .then(response => response.json()) .then(data => { // Handle the response if needed }) .catch(error => { console.error('Error:', error); });}; -
WinError 2 The system cannot find the file specified:
I have Django code which uploads pdf files to the SQLite database. In the first program, I uploaded successfully into the database but now I added some code and it shows me the error. The code i added is getting the size of the file and saving it to the database my code: from django.db import models from django import forms from django.core.validators import MinValueValidator import os class BookUploadModel(models.Model): book_title = models.CharField(max_length=200) category = models.CharField(max_length=100) cover_page= models.ImageField() Book_file = models.FileField() author_name = models.CharField(max_length=100) price= models.IntegerField(validators=[MinValueValidator(5)]) published_date = models.DateField() file_size = models.BigIntegerField(null=True,blank=True) def save(self, *args, **kwargs): if self.Book_file: self.file_size = os.path.getsize(self.Book_file.path) super().save(*args, **kwargs) class Meta: verbose_name_plural = 'Books' def __str__(self): return f"Book ({self.id})" def clean_photo(self): image_file = self.cleaned_data.get('cover_page') if not image_file.cover_page.endswith(".jpg"): raise forms.ValidationError("Only .jpg image accepted") return image_file views.py file: def upload(request): form = UploadForm() if request.method=='POST': # POST, return form with data from the request form = UploadForm(request.POST,request.FILES) if form.is_valid(): form.save() form = UploadForm() return render(request,"upload.html",{'form':form}) Error: Traceback (most recent call last): File "C:\Users\Tade\.virtualenvs\djangosetup-z2E8Qdx0\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Tade\.virtualenvs\djangosetup-z2E8Qdx0\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Tade\Desktop\djangosetup\bookstore_app\views.py", line 44, in upload form.save() File "C:\Users\Tade\.virtualenvs\djangosetup-z2E8Qdx0\lib\site-packages\django\forms\models.py", line 542, in save self.instance.save() File "C:\Users\Tade\Desktop\djangosetup\bookstore_app\models.py", line 17, … -
How to remove instances inside serializer
Here inside the serializer using to_representation, validate to remove the instance that doesn't satisfy the condition "completed == total_videos" but gets all the instances, so please suggest a solution to fix this class LearnerVideoMarkUsCompleteMyCourseSerializer(serializers.ModelSerializer): course = CourseSerializerForEnrolledCourseService() total_videos = serializers.SerializerMethodField() completed = serializers.SerializerMethodField() id = serializers.UUIDField(source="course.id") def get_total_videos(self, data): total_video_count = VideoDetails.objects.filter( video__coursemodulevideos__module_id__coursesectionmodule__section_id__coursesectiondetails__course=data.course ).count() return total_video_count def get_completed(self, data): progress = data.learner.learner_video_markascomplete.filter( course=data.course, mark_us_complete=True ).count() return progress class Meta: model = LearnerVideoMarkUsComplete fields = ("course", "id", "completed", "total_videos") def validate(self, data): completed = self.get_completed(data) total_videos = self.get_total_videos(data) print("complete", completed) print("total_videos", total_videos) if completed == total_videos: return data else: return "not equal" def to_representation(self, instance): completed = self.get_completed(instance) total_videos = self.get_total_videos(instance) if completed == total_videos: return super().to_representation(instance) else: return None