Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django loop through list in two parts
I do not understand how I can loop through a list in two goes. For example, display items 0-3, then 4-7. In particular, the list "arr" is passed through the view, then I'm in the template trying to display the list. I've trying a while loop, or slice etc, but just keep on getting errors. arr contains 3 string values per iteration from the views arr.append([title, link, img_url]) <div id="newsgrid"> {% for article in arr %} <div class="card"> <img src="{{ article.0 }}" alt="news image"> <small><a href="{{ article.1 }}">Read more</a></small> </div> {% endfor %} -
Why is a POST request successfully sent from the local server, but not from the production server?
I'm doing a project in django and I've uploaded it to a server with gunicorn+nginx. Everything works fine except my POST request. I have a form on the index page with this code: <form method="post" > {% csrf_token %} <input type="hidden" name="subject" value="Consultation form"> <div class="row row-cols-lg-3 row-cols-1 gy-lg-20 gy-10"> <div class="col"> <input class="form-control form-control-xxl text-center w-100" placeholder="Your name" type="text" name="name"/> </div> <div class="col"> <input class="form-control form-control-xxl text-center" placeholder="Your phone" type="tel" required name="phone"/> </div> <div class="col"> <button class="btn btn-primary btn-xxl w-100" type="submit">Get consultation </button> </div> </div> </form> I also have a handler in the views.py file: def handle_post_request(request): if request.method == 'POST': subject = request.POST.get('subject') phone = request.POST.get('phone') name = get_POST_parameter('name', request) if phone != '' and phone != None and subject != '' and subject != None: # Send data via HTTP POST request url = 'https://svarnik.ru/bx24/' headers = {'User-Agent': 'Reforgebot/1.0'} data = { 'ikey': 'someSecretKey', 'domain': 'example.com', 'roistat': 'nocookie', 'subject': subject, 'name': name, 'phone': phone, } try: response = requests.post(url, headers=headers, data=data) except Exception as e: pass return redirect('index') def index(request): if request.method == 'POST': handle_post_request(request) ... The strange thing is that the code works fine on the local server (127.0.0.1:8000) but doesnt't on ubuntu server. I thought … -
Calculating the coupon code discount in django inside the script tag
Here im tryin to calculate the coupon code discount... If i click the apply coupon button i want to find the 20% discount from total amount My coupon code is FREE20 HTML <ul class="mb-20 shadow-sm p-3 mb-5 rounded"> <li>Items <span>₹{{cart_total_amount}}</span></li> <li>Tax <span>₹{{tax}}</span></li> {% if valid_coupon %} <li>Coupon Code Applied <span>{{coupon.discount}}%</span></li> {% endif %} {% if cart_total_amount > 3000 %} <li>Delivery Charge <span>Free</span></li> <li>Total Amount <span>₹{{cart_total_amount|add:tax}}</span></li> {% else %} <li>Delivery Charge <span>₹10</span></li> <li class="fw-bold">Total Amount <span>₹{{cart_total_amount|add:tax|add:10}}</span></li> {% endif %} </ul> <script> var item_amounts = {{cart_total_amount}}; var tax = {{tax}} var total = item_amounts + tax; var coupon_discount = {{coupon.discount}} console.log(coupon_discount) if(coupon_discount){ if(item_amounts < 3000){ cal_discount = item_amounts - (item_amounts + coupon_discount / 100) + total + 10 document.getElementById("total").innerHTML = "₹" + " " + cal_discount.toFixed() } else{ cal_discount = item_amounts - (item_amounts + coupon_discount / 100) + total document.getElementById("total").innerHTML = "₹" + " " + cal_discount.toFixed() } } </script> But got an unexpected errors in script tags such are Property assignment expected. Declaration or statement expected. And if i apply the coupon discount FREE20 i want to find the 20% discount from total amount it is not working -
Django redirect with message after XMLHttpRequest
I have a template that send a JSON to my backend with a POST XMLHttpRequest with var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance var theUrl = "newSeq"; xmlhttp.open("POST", theUrl); xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xmlhttp.setRequestHeader("X-CSRFToken", csrftoken); xmlhttp.send(JSON.stringify(my_json)); The Django backend manage the request with def newSeq(request): if request.method == "POST": print(request.body) messages.success(request, "Ricevuto") return redirect("newSeq") return render( request, 'dashboard/newSeq.html', { } ) My issue is that the redirect doesn't work and on the frontend I have the error the cookies "messages" has been rejected because it is already expired Is there a way to delete the specific cookies and make the page redirect with the correct message? -
Setting ManyToManyField intermediate field in form in Django
Suppose I have such model: class Person(models.Model): name = models.CharField(max_length=128) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through="Membership") class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) created_by = models.ForeignKey(User, on_delete=models.CASCADE) I am working on a View, in which user could assign Persons to a Group. I want to store User who created the relation (Membership). Something like that: class GroupForm(forms.ModelForm): class Meta: model = Group fields = ["members"] widgets = {"members": forms.CheckboxSelectMultiple} class GroupView(UpdateView): form_class = GroupForm model = Group def form_valid(self, form): for member in form.cleaned_data["members"]: member.user = self.request.user member.save() return super().form_valid(form) However, I'm getting error: django.db.utils.IntegrityError: NOT NULL constraint failed: myapp_membership.created_by_id Of course, I could make created_by field nullable and set created_by later, but what is the correct way to solve this? -
Django channels create a async count down
I'm trying to code a website like Gartic.io. I am using django channels as backend django websocket. But I don't know how to do a 30 second countdown async. I need this countdown to control the duration of each drawing round. I have an async function as handle_turn(self,room). And it handles turns. It calls my timer function after some checks like 2 or more player, which raund is it... What I tried async def timer(self,room): try: print('1') # check if there is an event loop loop = asyncio.get_event_loop() loop.run_until_complete(self.handle_timer(room)) except RuntimeError as e: print('2') # create a new event loop if there is no event loop if str(e).startswith('There is no current event loop in thread'): print('3') loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) asyncio.get_event_loop().run_until_complete(self.handle_timer(room)) else: raise async def handle_timer(self,room): while room.duration > 0: await asyncio.sleep(1) # wait for 1 second await self.drop_duration(room) # drop duration by -1 print('duration is ' + str(room.duration)) # print duration if room.duration == 0: # time is up for turn await self.reset_duration(room) # reset duration to 30 I got an error RuntimeError: This event loop is already running -
I can't log in to the Django application using the server and I don't know why
Currently I am trying to create an application using Django. I have made a CustomUsers class and all that. But when I try to login, it does not work. I have the following models: class CustomUserManager(BaseUserManager): def create_user(self, email, username, password, **extra_fields): if not email: raise ValueError("The Email field must be set") email = self.normalize_email(email) user = self.model(email=email, username=username, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email=None, username=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') if email is None: raise ValueError('The Email field must be set for superuser.') return self.create_user(email, password, username, **extra_fields) class CustomUser(AbstractBaseUser): username = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=100, null=True, default='') email = models.EmailField(unique=True) coins = models.ManyToManyField('Coin', through='UserCoin') is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] The following login view: def user_login(request): if request.user.is_authenticated: return redirect('dashboard') elif request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(request, username=username, password=password) if user: login(request, user) next_url = request.POST.get('next') if next_url: return redirect(next_url) else: return redirect('dashboard') else: messages.error(request, 'Invalid username or password.') else: form … -
Django Multi-tenant postgresql and mongoDB
I implemented, PostgreSQL and MongoDB in a project. MongoDB was used to saved logs. It was working fine before adding multi-tenancy in the postgresql using django-tenants=3.5.0 I created another branch and removed the MongoDB from it. So just the Postgresql with multi-tenants. It was also working fine. But the issue arises when I merge the branch and integrate the both Databases (PostgreSQL + MongoDB). I got the following error on migrate. AttributeError: 'DatabaseWrapper' object has no attribute 'set_schema' On exploring, I found this issue is related to database engine, so it should be django_tenants.postgresql_backend for PostgreSQL in-case of Django-tenant. But I'm already using it. and for MongoDB the engine is djongo . I'm also using database routes DATABASE_ROUTERS = ['logs.routers.MongoRouter', 'django_tenants.routers.TenantSyncRouter', ] here's the custom mongodb router.py class MongoRouter: """ A router to control if database should use primary database or non-relational one. """ mongo_models = {'logs'} def db_for_read(self, model, **_hints): if model._meta.model_name in self.mongo_models: return 'mongodb' return 'default' def db_for_write(self, model, **_hints): if model._meta.model_name in self.mongo_models: return 'mongodb' return 'default' def allow_migrate(self, _db, _app_label, model_name=None, **_hints): if _db == 'mongodb' or model_name in self.mongo_models: return False return True Any solution, to this situation would be really appreciated. Let me … -
Django code to check the state of prometheus target such that it checks the state when the metrics data is scraped for that target
The customer will click on process request button and the monitoringConfigurationMultipleVM API gets called, then for every successful exporter configuration, one new job for that vm and exporter combo gets added in prometheus.yml file, and then that job we are passing as a paramater to the checkprometheusTargetStatus fucntion to check the state of the target of that job that has been recently added to prometheus.yml file(in our case every job will have only one target). We are trying to check the prometheus target state after the target is being added in the prometheus.yml file which has a scrape interval of 5s, but if we try to check the state of the target right after the target is being added to the prometheus.yml file, then we get the "target does not exist or has no data" case. And if we introduce a delay i.e. by adding time.sleep(some sec time), then if the time duration of sleeping is less than the combined scrape interval time of all jobs recently added to prometheus, then it gives "target does not exist or has no data" as a result for first target and for rest of the targets it gives correct state i.e. either "up" … -
Deploy with Docker Compose usig envriroment to JSON for DRF
enter image description here { "SECRET_KEY": "", "EMAIL_HOST_USER": "", "EMAIL_HOST_PASSWORD": "", "SOCIAL_AUTH_GOOGLE_CLIENT_ID": "", "SOCIAL_AUTH_GOOGLE_SECRET": "", "SOCIAL_AUTH_KAKAO_CLIENT_ID": "", "KAKAO_REST_API_KEY": "", "SOCIAL_AUTH_NAVER_CLIENT_ID": "", "SOCIAL_AUTH_NAVER_SECRET": "", "SOCIAL_AUTH_GITHUB_CLIENT_ID": "", "SOCIAL_AUTH_GITHUB_SECRET": "", "STATE": "random_string", "DATABASES": { "default": { "ENGINE": "django.db.backends.postgresql", "HOST": "", "PORT": 5432, "NAME": "", "USER": "", "PASSWORD": "" } } } secrets.json version: '3.8' volumes: postgres: {} django_media: {} django_static: {} services: postgres: container_name: postgres image: postgres:15.3 volumes: - postgres:/var/lib/postgresql/data/ env_file: ./backend/django/secrets.json environment: - POSTGRES_USER - POSTGRES_PASSWORD - POSTGRES_NAME backend: container_name: backend build: ./backend/ entrypoint: sh -c "python manage.py collectstatic --no-input && python manage.py migrate && gunicorn Realby_project.wsgi --workers=5 -b 0.0.0.0:800 00" volumes: - ./backend/django/:/app/ - /etc/localtime:/etc/localtime:ro - django_media:/app/media/ - django_static:/app/static/ - ./backend/django/secrets.json:/app/secrets.json environment: - DEBUG=1 - POSTGRES_NAME=${POSTGRES_NAME} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_HOST=${POSTGRES_HOST} - POSTGRES_PORT=${POSTGRES_PORT} - POSTGRES_DB=${POSTGRES_DB} depends_on: - postgres restart: always nginx: container_name : nginx image: nginx:1.23.2 ports: - "80:80" - "443:443" volumes: - ./nginx/default.conf:/etc/nginx/conf.d/default.conf - django_media:/media/ - django_static:/static/ depends_on: - backend restart: always docker-compose.yml I want deploy with docker-compose using .json for enviroment but Docker Compose can not read this .json file How can i fix this files When i asked chatGPT he said make entrypoint.sh and worte this script #!/bin/bash while IFS="=" read -r key value; do if [[ … -
Should I use Session authentication when configuring the login screen through drf?
urls.py urlpatterns = [ path('', include('dj_rest_auth.urls'), name='dj_rest_auth'), path('registration/', include('dj_rest_auth.registration.urls'), name='registration'), ] managers.py class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ #일반 유저 생성 def create_user(self, email, password, gender, date_of_birth, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) if not gender: raise ValueError(_('The gender must be set')) if not date_of_birth: raise ValueError(_('The date_of_birth must be set')) #email 형태를 동일하게 만들기 위한 함수 user = self.model( email=self.normalize_email(email), gender=gender, date_of_birth=date_of_birth, **extra_fields) user.set_password(password) user.save() return user #관리자 유저 생성 def create_superuser(self, email, password,**extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('gender', 2) default_date = date(2000,1,1) extra_fields.setdefault('date_of_birth', default_date) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) settings.py 'DEFAULT_AUTHENTICATION_CLASSES': ( #'rest_framework.authentication.SessionAuthentication', 'dj_rest_auth.jwt_auth.JWTCookieAuthentication' ), when i run the server after writing the code like this TypeError: 'type' object is not iterable [21/Jun/2023 13:25:05] "GET /userapp/login/ HTTP/1.1" 500 100395 how can i fix this I want to use only JWTCookieAuthentication. Is it possible? -
How to assert FK is not null using it's id with mypy
I have a couple models: class MyUser(models.Model): district = models.ForeignKey( District, on_delete=models.CASCADE, default=None, blank=True, null=True, ) class District(models.Model): timezone = TimeZoneField(default="US/Eastern") And I'm trying to write a function that will get the timezone for a user. I tried this: def get_timezone_for_user(user: MyUser) -> datetime.timezone: if not user.district_id: return DEFAULT_TIMEZONE return user.district.timezone But mypy doesn't like this because it thinks user.district can still be None, even though I know it cannot because the existence of district_id means that user.district is also not None. I can add an assert user.district is not None in there, but then I will incur an extra query just to persuade mypy. Any ideas that don't involve adding an additional query? -
Iam trying to make a contactus functninig page but Don't kmnow why doesnt it work properly?
I just want to make a contact us but I don't know why doesn't it work I does not give any errors but it dose not work what did I do wrong sorry I couldn't write them so I took scrn_shot urls.py views.py models.py forms.py Html template -
form_valid is not working with foregin_key on Django
I'd like to insert new Quotation.But always error "Cannot assign "4030": "Quotation.contact" must be a "Contact" instance." I also want to use foreign_key so I need instance Contact. class QuotationCreateView(CreateView): model = Quotation form_class = QuotationForm template_name = "quotation_form.html" def form_valid(self, form): contact_id = form.cleaned_data['contact'] contact_instance = Contact.objects.get(pk=contact_id) self.object = form.save(commit=False) self.object.contact = contact_instance self.object.save() return super(QuotationCreateView, self).form_valid(form) def get_success_url(self): return reverse('quotation:list') def get_form_kwargs(self): kwargs = super().get_form_kwargs() username = self.request.session.get('user')['name'] kwargs['initial'] = {'our_charge_string': username} return kwargs class Quotation(models.Model): contact = models.ForeignKey(Contact, on_delete=models.CASCADE) our_charge_string = models.CharField(max_length=30) class Contact(models.Model): our_charge_string = models.CharField(max_length=30, null=True) reception_datetime = models.DateTimeField(editable=True) class QuotationForm(forms.ModelForm): contact = forms.IntegerField(label='連絡ID') our_charge_string = forms.CharField(label='当社担当者', max_length=30) class Meta: model = Quotation fields = ("contact", "our_charge_string", "car_type_string", "loading_memo_string", "loading_place_string", "delivery_memo_string", "delivery_place_string", "transit_place_string", "item_string", "memo_string", "customer_id",) I put a breakpoint on line of form_valid. -
Cannot assign : must be a instance Django foreign Key error with html form
I am working with Foregin key . In dropdown I am passing Foregin key value.White storing data in table I am getting instance error I tried to fetch data from relational table and pass that id . models.py class Contacts(models.Model): #client's point of contact user = models.ForeignKey(User, on_delete=models.CASCADE) client = models.ForeignKey(Client, on_delete=models.CASCADE) name = models.CharField(max_length=100) email = models.EmailField(max_length=100) phone = models.CharField(max_length=100) mobile = models.CharField(max_length=100) role = models.CharField(max_length=100) title = models.CharField(max_length=100) views.py def add_contacts(request): if request.method == "POST": user_dt = request.POST['user'] client_dt = request.POST['client'] client = request.POST['client'] name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] mobile = request.POST['mobile'] role = request.POST['role'] title = request.POST['title'] print(user,client,name,email,phone,mobile,role,title) data = Contacts.objects.create(user=user,client=client,name=name,email=email,phone=phone,mobile=mobile,role=role,title=title) print(data) return redirect('contacts') -
Django Error : "No module named 'bootstrap5django'"
I installed the django-bootstrap and added that to setting.py Installed apps image and when I run the loocalhost with this code : python manage.py runserver It has this eror : ModuleNotFoundError: No module named 'bootstrap5django' image I didn`t write bootstrap5django I wrote only bootstrap5 with no django word My Works : install bootstrap with "pip install django-bootstrap" add bootstrap to Installed apps in settint.py edit html file with bootstrap run localhost and then this problem: ModuleNotFoundError: No module named 'bootstrap5django' -
Static Files not being served by NGINX, instead it passes the request to Django app
I have created a django app and running it using docker and docker compose, but the static files are not getting served by nginx, instead the request get passed to django server. Please help, I was trying docker compose for first time🥲 Folder Structure docker_insta(root folder) insta_backend insta_backend manage.py requirements.txt Dockerfile entrypoint.sh nginx default.conf Dockerfile docker-compose.yml Files docker-compose.yml version: '3.9' services: db: image: postgres:13.3 environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: postgres ports: - 5432:5432 volumes: - db:/var/lib/postgresql/data redis: image: redis:6.2.4 ports: - 6379:6379 django: volumes: - static:/app/static - media:/app/media build: ./insta_backend ports: - 8000:8000 depends_on: - db - redis nginx: build: ./nginx volumes: - static:/app/static - media:/app/media ports: - 80:80 depends_on: - django volumes: static: media: db: Dockerfile(django) FROM python:3.9-alpine RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY . /app WORKDIR /app ENTRYPOINT [ "sh", "entrypoint.sh" ] -entrypoint.sh #!/bin/sh python manage.py migrate --no-input python manage.py collectstatic --no-input gunicorn insta_backend.wsgi:application --bind 0.0.0.0:8000 Dockerfile(nginx) FROM nginx:1.19.0-alpine COPY ./default.conf /etc/nginx/conf.d/default.conf default.conf upstream django_server { server django:8000; } server { listen 80; location /static/ { alias /app/static/; } location /media/ { alias /app/media/; } location / { proxy_pass http://django_server; } } settings.py ... STATIC_URL = '/static/' STATIC_ROOT = … -
Django PlanetScale CA Cert Path
I have deployed a Django webapp on Vercel which uses a PlanetScale database. I have stored the PlanetScale connection strings as environment variables in Vercel. Django seems to be able to see the env variables; however, I am getting a FileNotFoundError for the CA cert path which was provided by PlanetScale. This is causing a server error that takes the app completely offline. This CA path was working previously when stored in a .env file. I have since attempted to replace the .env file and that no longer works either. Nothing else has changed in the project so I am at a loss as how to get this connection established again. Any help would be greatly appreciated. I will provide the error stack and settings below: Error: [ERROR] 2023-06-20T20:00:18.077Z 06fecc12-d46a-4f4f-9cf7-c00e50c42fb4 Internal Server Error: / Traceback (most recent call last): File "/var/task/django/core/handlers/exception.py", line 56, in inner response = get_response(request) File "/var/task/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/task/main/views.py", line 21, in home currUser = AuthUser.objects.get(username=request.user) File "/var/task/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/var/task/django/db/models/query.py", line 646, in get num = len(clone) File "/var/task/django/db/models/query.py", line 376, in __len__ self._fetch_all() File "/var/task/django/db/models/query.py", line 1867, in _fetch_all … -
Is there a difference between permission_classes = [A, B], permission_classes = [A & B]?
What is the difference between permission_classes = [A, B] permission_classes = [A & B] ?? I understand that the first one processes permission sequentially, and the second one does it at once. Is there a difference in the result? Also, I wonder which method is preferred and why. -
i need help in jango image [closed]
I have a Django project and need help: When I add a new photo to the database from admin, the new photo will replaced to old photo and the old photo be deleted from database automatically. How can I do this? For example, when I add image 2, image 1 will automatically be removed and replaced I have not been try this problem -
spell check chrome extension
i am building a chrome extension for spelling correction and i want to make the result display on any input field as red line under the mispelled word and a drop down menu this is the background.js chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { if (request.prevWord) { fetch('http://localhost:8000/spelling_correction/' + request.prevWord ) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); } }); chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { if (request.sentence) { fetch('http://localhost:8000/spelling_correction/' + request.sentence ) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); } }); and this is content.js var prevWord = ''; var currentWord = ''; if (event.code === 'Space') { var words = event.target.value.trim().split(' '); prevWord = words[words.length - 2]; chrome.runtime.sendMessage({prevWord: prevWord}, function(response) { var obj = JSON.parse(response); obj.response.errors.forEach(function(error) { if (prevWord === error.bad) { var suggestions = error.better.join(', '); var div = document.createElement('div'); div.innerHTML = '<span style="text-decoration: underline; color: red;">' + prevWord + '</span>: Did you mean ' + suggestions + '?'; document.body.appendChild(div); } }); }); } else { currentWord += event.key; } }); document.addEventListener('keydown', function(event) { var currentSentence = ''; if (event.code === 'Period') { currentSentence = event.target.value; chrome.runtime.sendMessage({sentence: currentSentence}, function(response) { var obj = JSON.parse(response); obj.response.errors.forEach(function(error) { if (currentSentence.includes(error.bad)) { var suggestions = error.better.join(', '); var div = document.createElement('div'); … -
POST Request to Django Backend from Flutter/Dart
I am trying to make a POST Request from my Flutter Frontend to my Django Backend, I am using DIO. The Error I get is: Bad Request: /api/homeapi/Users/ [20/Jun/2023 18:16:38] "POST /api/homeapi/Users/ HTTP/1.1" 400 58 This is my Code: serializer.py: from rest_framework import serializers from .models import Brand, User class BrandSerializer(serializers.ModelSerializer): class Meta: model = Brand fields = [ 'imgURL', 'brand_name' ] class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'email', 'selected_colors' ] views.py class BrandViewSet(viewsets.ModelViewSet): queryset = Brand.objects.all() serializer_class = BrandSerializer class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def create(self, request): serializer = UserSerializer(data=request.data) try: serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) except ValidationError as e: return Response({'errors': e.detail}, status=status.HTTP_400_BAD_REQUEST) Models.py: class Brand(models.Model): imgURL = models.CharField(max_length=120) brand_name = models.CharField(max_length=200) class User(models.Model): email = models.EmailField(max_length=120) selected_colors = models.JSONField() urls.py router = routers.DefaultRouter() router.register('Brands', BrandViewSet, basename='brand') router.register('Users', UserViewSet, basename='User') urlpatterns = [ path('admin/', admin.site.urls), path('api/homeapi/', include(router.urls)), path('api/get-csrf-token/', get_csrf_token, name='get-csrf-token'), ] This is my Dart Code: api.dart import 'package:dio/dio.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; const dataUrl = 'http://127.0.0.1:8000/api/homeapi/Brands/'; Future<void> postData(String url, Map<String, dynamic> fields) async { final headers = {'Content-Type': 'application/json'}; try { final response = await http.post(Uri.parse(url), headers: headers, body: json.encode(fields)); // Convert fields to JSON string if (response.statusCode … -
How to display products from category in dajngo?
I want to filter product by category I have made two categories one main category and category. Product is filtering according to main category but not according to category please someone tell me. models.py enter image description here enter image description here views enter image description here enter image description here html enter image description here enter image description here -
can you give me advice on django?
I would like help with a problem during a class project on django hi everyone i am new to django; I would like to know how I could create a kind of form (table) that a user can enter information such as courses, course start time, course end time and d other information. he can also add courses, by dynamically displaying a django course form already created. If I can get any leads or ideas that would be great. THANK YOU -
Unable to import views from an app in Django
I am trying to import views from my app "first_app", the command from first_app import views doesn't work in Pycharm. What am I doing wrong? I also have tried: from first_project.first_app import views, but I get "ModuleNotFoundError" exception.