Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
when i whant to use views.py i give 'QuerySet' object has no attribute error
i want to open course detail with next and previouse course but my try doesnt workes and i give 404 error and when i delete try and except i give 'QuerySet' object has no attribute error and says error is from counted_viewsenter image description here views.py: ``` def course_detail(request,id): try: course = Courses.objects.get(id=id) id_list = [] course = Courses.objects.filter(status = True) for cr in course : id_list.append(cr.id) if id_list[0] == id: next_course = Courses.objects.get(id=id_list[1]) previous_course =None elif id_list[-1] == id: next_course = None previous_course = Courses.objects.get(id=id_list[-2]) else: next_course = Courses.objects.get(id=id_list[id_list.index(id)+1]) previous_course = Courses.objects.get(id=id_list[id_list.index(id)-1]) course.counted_views += 1 course.save() context = { 'course': course, 'next_course': next_course, 'previous_course': previous_course, } return render(request,"courses/course-details.html",context=context) except: return render(request,'courses/404.html') ``` urls.py: ``` from django.urls import path from .views import * app_name = 'course' urlpatterns = [ path('',Maincourse,name='courses'), path('category/<str:cat>',Maincourse,name='course_cat'), path('teacher/<str:teacher>',Maincourse,name='course_teacher'), path('search/',Maincourse,name='course_search'), path('course_detail/<int:id>',course_detail,name='course_detail'), ]``` models.py: ```class Courses(models.Model): title = models.CharField(max_length=40) content = models.TextField(max_length=1000) teacher = models.ForeignKey(Trainer,on_delete=models.CASCADE) price = models.IntegerField(default=0) image = models.ImageField(upload_to='courses',default='default.jpg') category = models.ManyToManyField(Category) counted_views = models.IntegerField(default=0) counted_likes = models.IntegerField(default=0) status = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add = True) updated_date = models.DateTimeField(auto_now = True) available_seats = models.IntegerField(default = 0) schedule = models.DateTimeField(default=datetime.datetime.now()) ``` enter image description here -
How to combine multiple external REST API services in the same network using Django
I have a central Django REST API and want to serve multiple different machine learning models which I package as individual Flask REST apps. In order to provide a unified REST interface I would like to use the Django REST server as relay / proxy to the individual Flask services. All services are currently built and deployed using docker swarm/compose. What I currently can do is build for each individual Flask app the URL outlets in urls.py and then write code for each GET/POST method in Django to call the Flask outlet. However, I was wondering if in Django I could simply redirect all REST calls requesting: http://localhost/api/v1/model1 To the Flask app providing model1 and the Flask app then response for example to a request of http://localhost/api/v1/model1/submitData without needing Django to explicitly define http://localhost/api/v1/model1/submitData in urls.py. Alternatively I was thinking using Nginx to redirect all calls to http://localhost/api/v1/model1 to the Flask app instead of Django which is the default for http://localhost in my case. I hope the question is clear enough. Bottom line is that I am looking for the most convenient way to have a single REST interface but some REST services should run on individual docker images as … -
django-parler show fields only in one language on the django admin panel
[enter image description here](https://i.stack.imgur.com/aXTm0.png) I used django-parler to translate models. In some models field only show in Persian tab and don't show other language tab. Django language settings: LANGUAGES = [ ("de", "German"), ("fa", "Persian"), ("ru", "Russian"), ("tr","Turkish"), ("ar", "Arabic") ] LANGUAGE_CODE = 'de' Parler Settings: PARLER_DEFAULT_LANGUAGE_CODE = 'de' PARLER_LANGUAGES = { config('SITE_ID', cast=int): ( {'code': 'de', }, {'code': 'fa', }, {'code': 'ru'}, {'code': 'tr'}, {'code': 'ar'} ), 'default': { # defaults to PARLER_DEFAULT_LANGUAGE_CODE 'fallbacks': ['de'], # the default; let .active_translations() return fallbacks too. 'hide_untranslated': False, } } models.py: class Sliders(TranslatableModel): PRIMARY = 'PR' SECONDARY = 'SE' POSTION_IN_INDEX_CHOICES = [ (PRIMARY,_('erster Platz')), (SECONDARY,_('zweiter Platz')), ] translations = TranslatedFields( title = models.CharField(_('Titel'), max_length=50), image = FileBrowseField(_('Bild'), max_length=200, directory="first-page- sliders/images", extensions=[".jpg",".png",'jpeg']), link = models.URLField(_('Adresse'), max_length=200,default=None,null=True,blank=True), button_caption = models.CharField(_('Schaltflächentext'),max_length=10), ordering = models.SmallIntegerField('Bestellung'), postion = models.CharField(_('Position'),choices=POSTION_IN_INDEX_CHOICES,max_length=2,default=PRIMARY), created = models.DateTimeField(_('Erstellungsdatum'), auto_now=True, auto_now_add=False), updated = models.DateTimeField(_('Aktualisierungsdatum'), auto_now=False, auto_now_add=True), service = models.ForeignKey("service.Service", verbose_name=_("service"), on_delete=models.CASCADE,default=None, null=True,blank=True) ) class Meta: verbose_name = _('Schieberegler') verbose_name_plural = _('Schieberegler') def __str__(self): try: return self.title except TranslationDoesNotExist: return '' admins.py: @admin.register(Sliders) class SlidersAdmin(TranslatableAdmin): model = Sliders -
Django QuerySet Object Has No Attribute
I'm trying to add a new action to my OrderAdmin class called "order_shipped", whereby it'll send an email to the customer informing them that their order has been shipped. class OrderAdmin(admin.ModelAdmin): actions = ['order_shipped'] def order_shipped(self, request, obj): customer_email = obj.customer.email if request.method == 'POST': send_mail( 'Order Shipped', 'Your order has been shipped. Please expect it within the next 3-5 days. Thank you for your business.', EMAIL_HOST_USER, [customer_email], fail_silently=False ) return HttpResponseRedirect('/admin/store/order') order_shipped.short_description = 'Send Order Shipped Email' The problem that I'm having is that I keep getting this error: 'QuerySet' object has no attribute 'customer'. obj <QuerySet [<Order: 19>]> request <WSGIRequest: POST '/admin/store/order/'> self <OrderAdmin: model=Order site=AdminSite(name='admin')> If I add a new column called "order_shipped_btn" to the list_display using the code below, it shows the correct email for each customer. def order_shipped_btn(self, obj): return format_html('<a href="mailto:{}">SEND</a>', obj.customer.email) What I'm super confused about is why does it work for the later, but not the former? What am I doing wrong with the former? -
OTP verification failed pyotp
I am working on a django rest framework project, everything is working file but i encounter 1 problem class OTP: @staticmethod def generate_otp(): base32secret3232 = pyotp.random_base32() otp = pyotp.TOTP(base32secret3232, interval=300, digits=6, ) time_otp = otp.now() return time_otp, base32secret3232 @staticmethod def verify_otp(user, otp): return pyotp.TOTP(user.get("otp_secret"), interval=300, digits=6).verify(otp) Here OTP for user is generated successfully and i saved otp and secret in that user record and i send the user a email containing that otp for account verification. When user send the otp then for the first time it shows invalid OTP, then on subsequent changes it verify the user.I want to solve that issue First I check that whether I am entering the correct otp or not and otp,secret saved in database correctly or not. And these are working correctly. I want this issue to be resolved. -
No List matches the given query
I want to be able to add a comment on the product page, but after clicking on the comment button, it gives this error. What is the problem? I tried this code before, it worked perfectly, but now it gives an error. views.py ``` `def item_detail(request, item_bid_id): get_item = get_object_or_404(List, pk=item_bid_id) get_item_2 = get_item.first_bid filter_item = Bidmodel.objects.filter(listb_id = item_bid_id) comment = Comments.objects.filter(listc_id = item_bid_id) context = { 'item' : get_item, 'now_bid': auxiliary(get_item_2, filter_item), 'comments' : comment, } return render(request, 'auctions/item_detail.html', context ) # comment @login_required(login_url="login") def comments(request): comment = request.GET["comment"] username = request.user.username list_id = request.POST.get("listid", False) newcomment = Comments(user = username, comment = comment, listc_id = list_id) newcomment.save() return item_detail(request, list_id)` ``` item_detail.html: ``` `{% extends "auctions/layout.html" %} {% block body %} {% if messages %} {% for message in messages %} <div>{{ message }}</div> {% endfor %} {% endif %} <img src= {{ item.image.url }} alt = "{{item.title}}"><br> <a><a>Product:</a>{{ item.title }}</a><br> <a><a>Category: </a>{{ item.category }}</a><br> <a><a>Desc: </a>{{ item.description }}</a><br> <a><a>Status: </a>{{ item.status }}</a><br> <a><a>Frist Bid: </a> {{ item.first_bid }} $ </a><br> <div><a><a>Current Bid: </a> {{ now_bid }} $ </div> <div><a><a>Listed By: </a> {{ item.user }}</div> <h3 id="h3">Comments</h3> <div> <ul> {% for comment in comments %} <li><a><a>{{ comment.user }} … -
NameError: name 'django' is not defined [closed]
I am not able to run django. I have set the path too. But still I am getting error while running django. Please help! I have tried to run django. I have installed django using pip and also have set the path. I am expecting some solution to this problem so that I can run django on my system successfully. -
Django DRF with django-tenants Unit Test Issue
Description: I am working on a Django project using Django Rest Framework (DRF) and django-tenants for multi-tenancy. In my unit tests, I'm encountering an error that I need help resolving. I'm using django-tenants for multi-tenancy. The error suggests a 404 status code instead of the expected 201 Created status when creating a restaurant. I've verified my URL configuration, view names, and tenant setup, but the issue persists. Request: I'm looking for guidance on how to resolve this error and successfully create a restaurant in my unit test using django-tenants with DRF. Any insights or suggestions would be greatly appreciated. Thank you! Issue: When running a unit test to create a restaurant using the TenantTestCase, I am getting the following error: Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_create_valid_restaurant (django_apis.restaurants.tests.RestaurantCreateTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\OK\BackendProjects\apis\django_apis\restaurants\tests.py", line 55, in test_create_valid_restaurant self.assertEqual(response.status_code, status.HTTP_201_CREATED) AssertionError: 404 != 201 ---------------------------------------------------------------------- Ran 1 test in 4.596s FAILED (failures=1) Destroying test database for alias 'default'...``` **Code**: Here's the relevant code for the unit test: class RestaurantCreateTest(TenantTestCase): tenant = None # Define a class attribute to store the tenant instance @classmethod def setup_tenant(cls, tenant): # Create … -
Django : 405 Method Not Allowed
This is the Api class UnAssignEmployeeToOrderItemTaskViewSet( ResponseViewMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet, ): queryset = Order.objects.all() serializer_class = AddOrderItemSerializer def update(self, request, *args, **kwargs): try: order = Order.objects.get(id=kwargs['order_id']) order_item = OrderItem.objects.get(id=kwargs['order_item_id'], order=order) item_task = OrderItemTaskEmployee.objects.get(id=kwargs['task_id'], item=order_item) d = UnAssignEmployeeToOrderItemTaskViewSetSerializer(instance=item_task) item_task.assignee = None item_task.assigned_at = None item_task.save() serializer = OrderItemsListSerializer(order_item) return self.jp_response(s_code="HTTP_200_OK", data=serializer.data) except Exception as e: print(e) return self.jp_error_response( "HTTP_500_INTERNAL_SERVER_ERROR", "EXCEPTION", str(e) ) url router.register(r'(?P<order_id>.+)/items/(?P<order_item_id>.+)/task/(?P<task_id>.+)/unassign', UnAssignEmployeeToOrderItemTaskViewSet, 'unassign-order-items-task') But api call returns an error I spent a lot of time trying to fix this error. Please give me a solution to overcome this problem -
Why isn't it showing Id? It shows Game Object(none) instead of id
so i'm making a site that takes id for different pages for the path 'games/(id)'. when i make an object in the database table 'games', and pass it to html with context, django knows it exists and doesnt give error on the page. but when i write in the html to show {{game}} it shows Game Object(none) instead of Game Object('insert id here'). and when i do {{game.name}} it shows nothing. heres the code in 'views.py': def game(request, pk): game = Games.objects.get(id=pk) context = {'Game':Games} return render(request, 'games/games.html', context) i tried different way to do this, but nothing. still shows none. i've tried different ways with the model, but still nothing. -
I want the articles of my academic site created using django to be indexed in Google Scholar
I want the articles of my academic site created using django to be indexed in Google Scholar. Do you have a special python library for this or a way you recommend? I've tried using the fiduswriter library but I'm having trouble getting it to work and I can't find the information I need. -
psycopg2.errors.UndefinedColumn: column "source_id_id" of relation "service_approval_domains" does not exist
I have created model in django for my database. After trying to add data to table I got this error: ` lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column "source_id_id" of relation "service_approval_domains" does not exist LINE 1: ...domains" ("domain", "created_at", "retrieved_at", "source_id... ^ I am not really sure where is the problem since I have checked everything and did not find any declaration of source_id_id column. Here is my model: class ServiceApprovalDomains(models.Model): id = models.BigAutoField(primary_key=True) domain = models.TextField(unique=True ,null=False) created_at = models.DateTimeField(auto_now_add=True) retrieved_at = models.DateTimeField(auto_now=True) source_id = models.ForeignKey( ServiceApprovalDomainSources, on_delete=models.CASCADE ) class Meta: managed = False db_table = '"privacy"."service_approval_domains"' And I used manual migration so here is my SQL file: CREATE TABLE "privacy"."service_approval_domains"( "id" BIGSERIAL PRIMARY KEY, "domain" TEXT UNIQUE NOT NULL, "created_at" timestamp with time zone not null default current_timestamp, "retrieved_at" timestamp with time zone default current_timestamp, "source_id" bigserial not null references service_approval_domain_sources("id") on delete cascade ); And this is the function I am using to add data to database: def add_domains(data: list[AddServiceApprovalDomains]): for domain in data: source = ServiceApprovalDomainSources.objects.get_or_create(name=domain.source.name) try: ServiceApprovalDomains.objects.create(domain=domain.domain, source_id=source[0]) except IntegrityError: pass return True -
How to use different tables for authentication in django?
I am from Laravel background and new to django. My concern is how can I use two different tables for authentication in django. For example, admins table for admin authentication and users table for user authentication. Both tables will have column email, password. In laravel, we can use auth guard for this scenario. I want to know how can I implement this in django. I know we can use groups with auth_user table. But I would like to use different tables for user and admin. I have not tried anything yet about this. I am looking for business logic for this implementation in django. Also any code reference will be great help to me. -
Django tried using these urls... empty path didnt match any of these
Not sure why can't django find the empty path, I included the app path to the project's urls, I added path "" to the app's urls.py. so what's wrong here Here is the code for my app views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello world!") urls.py from django.urls import path from . import views urlpatterns = [ path("",views.index,name="index") ] the project's url.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('pricelist/',include("pricelist.urls")) ] -
Handling the case where the user closes the browser or stops the process in the middle of the OAuth flow Google API in Python
I am integrating Google Drive API in my Django project. My code is working perfectly but when I try to abort the authentication by either closing the browser without authenticating myself by logging into it or any sort of aborting results in freezing the whole app. Here is the code, flow = InstalledAppFlow.from_client_secrets_file(settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, self.SCOPES,redirect_uri='show_courses') creds = flow.run_local_server(port=0) with open(token_path, 'w') as token_file: token_file.write(creds.to_json()) everything get stuck on this line if user close the browser without authentication creds = flow.run_local_server(port=0) Please let me know how to handle this situation. I am struggling for this from last few months. -
How can i create a Root User in Django?
I want to create a root user RootUser under which there will be all the companies and under each company there will be different users which i have already done using CustomUser model. That root user won't have any access to the data of other companies including the users (which is defined in CustomUser model) of those companies under each company. Now my question is how do I create the root user RootUser or? Do I need a separate app for this or do I have to create the root user in the CustomUser model or is there a better way to do this? Here is my CustomUser model. I would appreciate if anyone could at least help me with the approach. Thank you. class CustomUser(AbstractUser): USER_TYPE_CHOICES = ( (1, "Super Admin"), (2, "Staff"), (3, "Users"), ) user_id = models.IntegerField(max_length=100, unique=True) user_type = models.IntegerField(choices=USER_TYPE_CHOICES, default=1) phone_number = models.CharField(max_length=500) nid_number = models.CharField(max_length=100, blank=True) city_name = models.CharField(max_length=100, blank=True) zip_code = models.CharField(max_length=10, blank=True) nid_image = models.ImageField(upload_to='nid_images', blank=True) address = models.TextField(blank=True) last_active = models.DateTimeField(default=timezone.now) profile_picture = models.ImageField( upload_to='profile_pictures', blank=False) def is_online(self): now = timezone.now() # Assuming the user is online if they have been active in the last 5 minutes return now - self.last_active … -
Connecting Django web application to python class library
I have a Django web application that runs couple of apps, I want this Django application to connect with the the other python project [which is not a web application] that has it's own data base. What I am trying to achieve is, when a user inputs a keyword and clicks search button in the django application the call has to go to the python project and execute the functionalities that it offers and display the results in the django application web page. If someone can explain me on how to achieve this that would be great. -
Celery connection to Redis throwing "timed out" error only when delay method called from Django view
I am perplexed with this error and looking for some expert help. Here are the details - I am running a Django application with celery to schedule and execute tasks I use Azure Cache for Redis as the celery backend and broker Azure Redis has SSL port enabled and non-SSL port disabled I have configured SSL using URL scheme (rediss://) as well as celery config (broker_use_ssl and redis_backend_use_ssl) My Task is defined in one django app and the view is in another (though they are deployed together) Everything works also fine in my local setup, where I don't use SSL on redis My django server is running with gunicorn inside a docker container Everything works just fine when celery-beat schedules a task and workers pick them up to execute. They both are able to communicate with Redis fine. However, when I call a task from my django view directly, with delay function, I see a timeout error on connecting Redis. Here is how I am calling the task (removed some boilerplate code for brevity): from mydjangoapp import tasks def MyViewFunction(request): tasks.MyTask.delay(param1, param2, param3) Here is the error I see : kombu.exceptions.OperationalError: Error while reading from <my-redis-server-url>:6380: ('timed out',) Can someone … -
Django No Reverse Match Failure to Supply int:pk
I am trying to create a hyperlink that takes a admin user to a sepearte web page where they can select a respective ingredient and update the quantity and price per unit. When I click on the update ingredient hyperlink to load that page Django says there is a no reverse match error. Error Message: `Traceback (most recent call last):= Exception Type: NoReverseMatch at / Exception Value: Reverse for 'ingredientupdate' with no arguments not found. 1 pattern(s) tried: ['ingredient/update/(?P<pk>[0-9]+)\\Z']` urls.py path('ingredient/update/<int:pk>', views.UpdateIngredientView.as_view(success_url = "/ingredients/"), name='ingredientupdate'), views.py `class UpdateIngredientView(UpdateView): # I am thinking this is an UpdateView model = Ingredient template_name = 'inventory/form_template.html' fields = ["quantity", "price_per_unit"]` success_url = reverse_lazy('ingredientupdate')` form_template.html form_template.html {% extends "inventory/base.html" %} {% block content %} <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"/> </form> {% url 'ingredientupdate' Ingredient.pk %} {% endblock %} After researching stack overflow articles: What is a NoReverseMatch error, and how do I fix it? it confirms to me that I need to supply the int:pk. In my template I supplied a Ingredients.pk but that was not enough. What exactly am I supposed to pass in? -
Does Django have any text file search features?
I am using Django Web Framework to store PDF files in FileFields, that will then be converted to .txt files to be used later. Does Django have any features to parse files for queries? My first thought if they diddn't was to use a simple Inverted Index, but I wanted to utilize Django tools as much as I can. I've done several searches in the Django documentation but haven't found anything. I know that the chance of Django having a feature like this was quite low. -
Django - URL pattern not found (page not found)
urls.py file from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('employees/', include('employees.urls')), path('customers/', include('customers.urls')), path('courses/', include('courses.urls')), path('planning/', include('planning.urls')), path('intranet/', include('intranet.urls')), path('', include('dashboard.urls')), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path('accounts/', include('accounts.urls')), path('api/', include('api.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) customers/urls.py file from django.urls import path from . import views app_name = 'customers' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('calendar/', views.CalenderView, name='calendar'), path('add/', views.addCustomerView, name='add_customer'), path('manage/<id>/', views.ManageCustomerView, name='manage_customer'), path('child/<mother_id>/add', views.addChildView, name='add_child'), path('child/manage/<id>', views.manageChildView, name='manage_child'), path('appointment/add', views.addAppointmentView, name='add_appointment'), path('appointment/<int:customer_id>/add', views.addAppointmentView, name='add_appointment'), path('appointment/<int:pk>/manage', views.manageAppointmentView, name='manage_appointment'), ] customers/views.py file def manageAppointmentView(request, pk): a = Appointment.objects.get(id=pk) if request.method == 'POST': form = AppointmentForm(request.POST, instance=a) if form.is_valid(): # create a new `Appointment` and save it to the db a = form.save() # redirect to the detail page of the appointment we just created # we can provide the url pattern arguments as arguments to redirect function return redirect('customers:customer', Appointment.customer_id) else: form = AppointmentForm(instance=a) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) Now, when I navigate to the following url: http://127.0.0.1:8000/customers/appointment/5/manage/ I get a page not found error even though the exact url can be found on row 10. What am I missing? The 'add_appointment' url is working perfectly fine. It's only the manage_appointment that is not … -
Django Model use a seperate model within model as if it is a past of it
I'm trying to accomplish the following; I have a model customer and model vendor (and others). I would like to have the fields of the model Location available within the customer and vendor models. What I can think of is to create the field similar available in the customer and vendor model, and have a seperate save function on each. What is the best approach? I can think of using the save function, and adding additional code to additionally create a Location entry and using that entry to update the location foreign key, meaning I need to have the field available in both Models. But is there a more efficient / proper approach? def save(self, *args, **kwargs): code to create or update the location entry super(Customer, self).save(*args, **kwargs) class Location(models.Model): type = models.CharField(max_length=30) street = models.CharField(max_length=30) number = models.CharField(max_length=30) postal = models.CharField(max_length=30) country = models.CharField(max_length=30) class Vendor(models.Model): name = models.CharField(max_length=30) location = models.ForeignKey(Location,on_delete=models.CASCADE) class Customer(models.Model): name = models.CharField(max_length=30) location = models.ForeignKey(Location,on_delete=models.CASCADE)``` -
CS50w Mail project won't print a simple console.log command to the console [closed]
Im currently working my way through the CS50w course working on project nr 3 "Mail" Designing a front-end for an email client that makes API calls to send and receive emails. The program is pre-written, the assignment is to only work with the JS and HTML. My issue is that I can't seem to send a POST request, or anything else for that matter. First I tried to solve the problem on my own, but could not get the "POST" request to get through. Looking at the Network tab in the console view I could only see the GET request loading the from prewritten code. I then followed a tutorial where they got it working. I followed it to the letter without changing anything and can't get a simple print statement to work. I tried deleting and restarting the program without changing anything but without success. Not even a simple print statement after the DOMContentLoaded would print. I don't get any error messages or logs to indicate what seems to be the problem. It just wont print anything on the console. Any help would be greatly appreciated! This is the tutorial I was following, solution starts from 05:14. https://www.youtube.com/watch?v=mj6q0gHOddY&t=438s I've … -
Django Cors-Origin resource sharing error MissingAllowOriginHeader
Hello friend i have problem, i tried many things but Nothing worked. This error appeares only for font-awesome font files and debug.js for django debug toolbar. application is deployed in GCP cloud run. static files are in Cloud Storage. application reads every other files. also connected from local to Cloud Storage and have same error Django version 4.1 django-cors-headers==4.2.0 settings.py from corsheaders.defaults import default_methods ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ ... 'corsheaders', ] CORS_ORIGIN_DOMAINS = [ 'http://localhost:8000' ] CSRF_TRUSTED_ORIGINS = CORS_ORIGIN_DOMAINS CORS_ALLOWED_ORIGINS = CORS_ORIGIN_DOMAINS CORS_ALLOW_METHODS = default_methods MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] I tried: CORS_ORIGIN_ALLOW_ALL = True MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST= [ 'http://localhost:8000' ] CORS_ALLOW_HEADERS = "*" INSTALLED_APPS = [ 'corsheaders', ... ] CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with" ] -
validated_data returns empty dictionary on update
I am building a backend system like Udemy, in this Cart API I am trying to update a cartitem object (a student want to add another course instead of this one) so I want to change the course in the cartitem and change the total_price of the cart. What happens is that when I update the course field it returns HTTP_200_OK response status but the body of the response is the JSON object of the exact same object before updating and the object is not updated models.py class Cart(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) student = models.OneToOneField( User, on_delete=models.CASCADE, related_name='cart') total_price = models.IntegerField(default=0) class CartItem(models.Model): cart = models.ForeignKey( Cart, on_delete=models.CASCADE, related_name='items') course = models.ForeignKey(Course, on_delete=models.CASCADE) views.py class CartItemViewSet(ModelViewSet): http_method_names = ['get', 'post', 'put', 'delete'] def get_queryset(self): return CartItem.objects.filter(cart_id=self.kwargs['cart_pk']) def get_serializer_class(self): if self.request.method == 'PUT': return UpdateCartItemSerializer elif self.request.method == 'POST': return CreateCartItemSerializer else: return CartItemSerializer def get_serializer_context(self): return { 'cart_id': self.kwargs['cart_pk'] } serializers.py class CartItemSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) student_id = serializers.SerializerMethodField(read_only=True) def get_student_id(self, cart_item): return Cart.objects.filter(id=self.context['cart_id'])[0].student_id class Meta: model = CartItem fields = ['id', 'student_id', 'course_id'] class CreateCartItemSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) def create(self, validated_data): instance = CartItem.objects.get(cart_id=validated_data['cart_id'], course_id=validated_data['course_id']) try: return instance except CartItem.DoesNotExist: instance = CartItem.objects.create(**validated_data) instance.save() return instance class Meta: …