Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my success.html page getting a 404 error when I submit a test transaction through Stripe?
I am trying to perform a test transaction using stripe with a Django web project. The following code is my views.py file: from django.shortcuts import render, get_object_or_404 from django.urls import reverse from . models import Product, OrderDetail from django.conf import settings from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse, HttpResponseNotFound import stripe import json # Create your views here. def index(request): products = Product.objects.all() print(products) return render(request, 'myapp/index.html', {'products': products}) def detail(request, id): product = Product.objects.get(id=id) stripe_publishable_key = settings.STRIPE_PUBLISHABLE_KEY return render(request, 'myapp/detail.html', {'product': product, 'stripe_publishable_key': stripe_publishable_key}) @csrf_exempt def create_checkout_session(request, id): request_data = json.loads(request.body) product = Product.objects.get(id=id) stripe.api_key = settings.STRIPE_SECRET_KEY stripe.PaymentIntent.create( amount=int(product.price * 100), currency='usd', payment_method_types=['card'], ) checkout_session = stripe.checkout.Session.create( customer_email=request_data['email'], payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'usd', 'product_data': { 'name': product.name, }, 'unit_amount': int(product.price * 100) }, 'quantity': 1, } ], mode='payment', success_url=request.build_absolute_uri(reverse('success')) + "?session_id={CHECKOUT_SESSION_ID}", cancel_url=request.build_absolute_uri(reverse('failed')), ) print(checkout_session) order = OrderDetail( customer_email=request_data['email'], product=product, stripe_payment_intent=checkout_session['payment_intent'], amount=int(product.price) ) # checkout_session.payment_intent = intent order.save() return JsonResponse({'sessionId': checkout_session.id}) def payment_success_view(request): session_id = request.GET.get('session_id') if not session_id: return HttpResponseNotFound() stripe.api_key = settings.STRIPE_SECRET_KEY session = stripe.checkout.Session.retrieve(session_id) order = get_object_or_404( OrderDetail, stripe_payment_intent=session.payment_intent) order.has_paid = True order.save() return render(request, 'myapp/success.html', {'order': order},) def payment_failed_view(request): return render(request, 'myapp/failed.html') The stripe transaction goes through successfully before giving a 404 error … -
Implementing Salon-Specific Authorization in Django for a Salon Management Application
I am currently using Django version 4.1.5. I am beginner in django. I am developing a salon management application and I would like to utilize Django's built-in authentication and authorization features. Specifically, I have a salon master and I would like to implement authorized menus and actions based on the salon ID. Could someone kindly assist me in achieving this? I made an attempt to create custom models for the user, group, and permission functionalities, but unfortunately, it did not yield the desired outcome. It is possible that I may have not implemented them correctly. -
How can I reduce Image file Size in Python
I am working on a Django Project where in my Form I have a Python method that I want to first check whether the uploaded image is jpg, jpeg, gif or png, and then check if the uploaded image is more than 14kb and reduce it to be less than or equal to 14kb. The issue is that the first check (allowed file formats) is done correctly but the second check is not working correctly instead, the image is uploaded without the file size reduced. Below is my code: class ProfileForm(forms.ModelForm): full_name = forms.CharField(label = 'Full Name:', max_length=36, widget=forms.TextInput(attrs={'placeholder': 'Enter Your Full Name'})) email = forms.CharField(label = 'Email Address:', max_length=36, widget=forms.TextInput(attrs={'placeholder': 'Enter a Valid Email Address'})) phone_number = forms.CharField(label = 'Phone Number:', max_length=11, widget=forms.TextInput(attrs={'placeholder': 'Enter Your 11 Digits Phone Number.'})) state = forms.CharField(label = 'State:', max_length=12, widget=forms.TextInput(attrs={'placeholder': 'Enter State of Residence Name Only.'})) address = forms.CharField(label = 'Residential Address:', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Enter Street Name with Number (where applicable) and Town Name only.'})) class Meta: model = Profile fields = ['full_name', 'phone_number', 'email', 'country', 'state', 'town', 'address', 'image'] def validate_image(image): if not mimetypes.guess_type(image.name)[0] in ["image/jpeg", "image/png", "image/gif"]: return "Invalid file format. Only JPG, PNG, and GIF images are allowed." image = … -
Handle Django application if DB is taking time to respond
We recently our migrated our application from VM and in-memory Database to AKS and Azure Postgres flexible server. After the migrations, we feel DB is not stable and when monitoring the CPU utilisation it was going 90% sometimes and Django application is not responding because DB is taking longer time to respond. I know this is not straight forward issue and need more informations to debug. But i need two suggestions here, i'm not expecting the solutions, How to handle the applications down if DB is not responding, i need a workaround to handle this scenarios. Our team is optimising the queries, but i'm not feeling that's the solution and our DB size is very small (Less than 1GB) but we have Memory Optimized, E2ds_v4, 2 vCores, 16 GiB RAM, 512 GiB storage. Still it's not able to handle the requests, i'm not having problem to increase the ram but that's the solution Azure is offering but i'm not happy with that. Whenever applications going down, will clear all the sessions so all the DB connections will be closed and DB will start responding. I know this is not a solution, but we are not able to find a better … -
Two tables are associated through the middle table, how to quickly obtain the data in one table associated with the other table
Now, I have three tables, which are: class Group(models.Model): uid = models.CharField(max_length=50, primary_key=True, default=short_uuid, db_index=True) name = models.CharField(max_length=200, default='', blank=True) class Meta: app_label = 'app_1' class GroupQuestion(models.Model): id = models.BigAutoField(primary_key=True, db_index=True) order = models.PositiveIntegerField(default=0) group = models.ForeignKey('Group', related_name='group_questions', on_delete=models.CASCADE,db_constraint=False, blank=True, null=True) question = models.ForeignKey('Question', related_name='group_questions', on_delete=models.CASCADE, db_constraint=False, blank=True, null=True) class Meta: app_label = 'app_1' class Question(models.Model): id = models.BigAutoField(primary_key=True, db_index=True) name = models.CharField(max_length=200, default='', blank=True) class Meta: app_label = 'app_1' I want to use the known Group object to find the associated Question object and use the order in the GroupQuestion to sort it. How should I use the orm statement. My current approach is to first search for the associated GroupQuestoin object through Group and use values_list to obtain question_id, further obtain the Queryset of the Question object, and perform deduplication There is another drawback to this approach. group_obj = models.Group.objects.filter(uid="xxxxx").first() question_id_list = list(group_obj.group_questions.all().values_list('question_id',flat=True)) question_objs = models.Question.objects.filter(id__in=question_id_list).order_by( 'group_questions__order').distinct() There is another drawback to this approach. When I had two groups associated with the same Queston, I got question_objs with duplicate values, and I had to do some processing to remove duplicate data, which was something I didn't expect. enter image description here # When I do the following group_obj … -
DjangoRestFramework ParserError "Multipart form parse error - Invalid boundary in multipart: None"
Frontend <body> <input id="fileRef" type="file" /> <button onclick="push">Push</button> <script> function push() { const file = fileRef.files[0]; const formData = new FormData(); formData.append('image', file, file.name); fetch('http://127.0.0.1:8000/api/item/', { headers: { 'Content-Type': 'multipart/form-data', }, method: 'POST', body: formData }); } </script> </body> Backend from rest_framework.parsers import MultiPartParser class ItemViewSet(ModelViewSet): ... parser_classes = [MultiPartParser] The above is the minimal implementation of the bug, when I send the request, it will generate such an error: Multipart form parse error - Invalid boundary in multipart: None Request headers, payload I spend a long time and don't know how to solve ;) I tried change Content-Type like this 'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' But it doesn't work, My expectation is that django can correctly parse and successfully accept the file -
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.