Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF issue in react native and Django
I recently updated by react native from 0.67.0 to 0.72.6 , django i'm still using 3.1.2. For session i'm using the default what ever django provides. Now i have a csrf token stored Asynchronous storage in mobile apk previously, call this apk_1, this uses the old react native version i.e 0.67.0 , Now i provided a update on google play store with new react native 0.72.6, now after updating the app from playstore one of the post method is not working, this post method uses csrf token , it shows 403 forbidden, how can the change in react native framework will affect this csrf token issue ?. im using axios for sending requests, but i have not updated the axios package it is same as apk_1 -
Is there a way to use modulo to check value in django Q object?
I have a script which does some filtering operations on a database in a very dynamic manner. What I need is to create a very specific condition in certain cases which requires me to check if a field is divisble by 500. A relevant snippet is below: title_filter_weekly = Q( option__title__startswith=str(index), option__title__endswith=str(expiry_date.strftime("%d")) + str(expiry_date.strftime("%b").upper()) + str(expiry_date.strftime("%y")) + option_entry_type, ) title_filter_monthly = Q( option__title__startswith=str(index), option__title__endswith=str(expiry_date.strftime("%b").upper()) + str(expiry_date.strftime("%y")) + option_entry_type, option__is_monthly=True, ) # Check if "leg_round_value" is in position_info and True round_value_condition = ( "leg_round_value" in position_info and position_info["leg_round_value"] ) # Apply the additional condition for divisibility by 500 if round_value_condition: title_filter_weekly &= Q(option__strike_price) title_filter_monthly &= Q(option__strike_price) The last two lines are incomplete, what I basically want is to add in the condition that option__strike_price is divisible by 500. I can try to possibly do the intial filtering, and then further filter via loop, but I want minimise queries as much as possible and it seems like there may be a better way. -
How Can I Get Data from Script to Populate ChoiceField in Django
I'm working on an app for golfing. i'm stuck right now trying to do have a user enter in a course name, and return the result. When the user clicks a button, I use a beautifulSoup script to scrape a scorecard database website based on the input name. Right now i'm just trying to test out a user entering a course, and seeing the results returned in the AJAX response so I can further my javascript, but i'm not seeing anything. If I print the results from the views.py though, I can see it returned successfully. I just don't know how to attached that view response to return to the ajax call. Here is my code: views.py def lookupCourses(request, courseName): course_result = course_query(courseName) return JsonResponse(course_result) urls.py app_name='golf_courses' urlpatterns = [ path('add/', Golf_CourseCreateView.as_view(), name='add'), path(r'lookup/<str:courseName>/', lookupCourses, name='lookup'), ] courses.js 'use strict'; const courseNameBtn = document.getElementById('button-addon2'); const getCountryData = function () { const courseName = document.getElementById('id_courseLookup').value fetch(`http://127.0.0.1:8000/golf_courses/lookup/${courseName}/`) .then(function (response) { console.log(response); return response; }); }; courseNameBtn.addEventListener('click', getCountryData) course_parse.py def course_query(course): # COURSE_QUERY = sys.argv[1] COURSE_QUERY = course URL = "https://www.mscorecard.com/mscorecard/courses.php?CourseName={}&Country=USA&SubmitButton=Search".format(COURSE_QUERY) page = requests.get(URL) soup = BeautifulSoup(page.content, "html.parser") page_body = soup.find("div", class_="page-content") matching_courses = page_body.find_all("a", class_="no-hover") course_dict = {} for i, course in … -
Make user activation ApiView open DRF
I have this APIView to activate a user: class UserActivationView(APIView): authentication_classes = ([]) permission_classes = [AllowAny] """ Intermediate view to activate a user's email. """ def get (self, request, uid, token): protocol = 'https://' if request.is_secure() else 'http://' web_url = protocol + request.get_host() post_url = web_url + "/auth/users/activate/" post_data = {'uid': uid, 'token': token} result = requests.post(post_url, data = post_data) content = result.text return Response(content) I need to access it from a link in an email sent using Djoser But I get this error when accessing the APIView: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept "{\"detail\":\"Authentication credentials were not provided.\"}" View path in users: path('activate-user/<str:uid>/<str:token>/', views.UserActivationView.as_view()), The urlConf: # Register API apipatterns = [ path('', include('activities.urls')), path('', include('social_auth.urls')), path('', include('users.urls')), ] urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include(apipatterns)), path('auth/', include('djoser.urls')), path('auth-token/', include('djoser.urls.authtoken')), re_path(r'^$', views.index, name='index'), ] -
DRF inserting relative urls to models.URLField
I am posting a relative url to a model DRF which includes a models.URLField. The problem is that it returns for the field insert a valid internet address. I know that the problem is with is_valid method. Also, I know that I can edit the relative url at both sides to be an absolute url. But I do not know how to handle the problem to just allow relative urls too. Any idea? -
Bootstrap Modal visible but the texts not visible
I have created django application. I am trying to add modal to my table button. Modal is working but inside text don't show. How can i fix that? I'm using Bootstrap v5.3 <div class="bd-example" > <table class="table table-striped w-auto"> <thead class="table-dark w-auto"> <tr> <th scope="col">Sub Type</th> <th scope="col">Sub Type Description</th> <th scope="col">Actions</th> </tr> </thead> <tbody> {% for sy in sub_type %} <tr> <td>{{ sy.Sub_Type }}</td> <td>{{ sy.Sub_Type_Desc }}</td> <td> <a href="" class="btn btn-outline-dark" data-bs-toggle="modal" data-bs-target="#exampleModal"> <i class="bi bi-eye-fill"></i> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content" > <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> attooo </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> </a> <a href="" class="btn btn-outline-dark"><i class="bi bi-clipboard-plus"></i></a> <a href="" class="btn btn-outline-dark"><i class="bi bi-trash3"></i></a> </td> </tr> {% endfor %} </tbody> </table> </div> </div> I have tried a lot of way but didnt work it. Screenshots -
How can I assign another m2m based on the m2m field in Django?
I want to save multiple bandcolors for each color I'm saving multiple colors for a watchseries. Models: class Color(models.Model): color_name = models.CharField(max_length=100, blank=True, null=True) class WatchSeries(models.Model): series = models.CharField(max_length=50) colors = models.ManyToManyField(to='Color', related_name='+') class BandColor(models.Model): color = models.CharField(max_length=50) Not sure, Do I need to create a new model like below: class BandColorByWatchColor(models.Model): series = models.ForeignKey('WatchSeries', related_name="+", blank=True, null=True, on_delete=models.SET_NULL) color = models.ForeignKey('Color', related_name="+", blank=True, null=True, on_delete=models.SET_NULL) band_color = models.ManyToManyField(to='BandColor', related_name="+") After saving colors for individual Watch series, this is how I can see the colors and populate the BandColor for each on the right side in Django admin panel: Admin site code: class BandColorByWatchColorFormSet(BaseInlineFormSet): def get_form_kwargs(self, index): kwargs = super().get_form_kwargs(index) kwargs['parent_object'] = self.instance return kwargs class BandColorByWatchColorForm(forms.ModelForm): band_color = forms.ChoiceField(choices = []) class Meta: model: BandColorByWatchColor def __init__(self, *args, parent_object, **kwargs): self.parent_object = parent_object super(BandColorByWatchColorForm, self).__init__(*args, **kwargs) values_list = [(x.pk, x.color) for x in BandColor.objects.all()] self.fields['band_color'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), choices=values_list, required=False) class WatchSerieColorInline(admin.TabularInline): model = WatchSeries.colors.through formset = BandColorByWatchColorFormSet form = BandColorByWatchColorForm extra = 0 class WatchSeriesAdmin(admin.ModelAdmin): model = WatchSeries form = WatchSeriesAdminForm filter_horizontal = ('colors', 'repaint_colors') inlines = [WatchSerieColorInline] save_on_top = True list_display_links = ('series', ) search_fields = ('series', ) list_display = ['series', 'sku_mapping', 'created_at', 'updated_at', 'created_by', 'updated_by', 'is_deleted'] def … -
redirect_uri_mismatch while fetching accestoken and refreshtoken from react and django
i am trying to get accestoken and refreshtoken from google auth using django server , I am calling the api from frontend in reactjs , but i am getting the following error every time Error 400: redirect_uri_mismatch my backend code looks like this , current_directory = os.path.dirname(os.path.abspath(__file__)) CLIENT_SECRET_FILE = os.path.join(current_directory, 'client_secret.json') SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'] REDIRECT_URI = 'http://localhost:3000/parent/our_information' class GetAuthUrlView(APIView): def get(self, request): flow = Flow.from_client_secrets_file( CLIENT_SECRET_FILE, scopes=SCOPES, redirect_uri=REDIRECT_URI ) print(flow) auth_url, _ = flow.authorization_url(prompt='consent') return JsonResponse({'auth_url': auth_url}) class ExchangeCodeView(APIView): def get(self, request): code = request.GET.get('code') flow = Flow.from_client_secrets_file( CLIENT_SECRET_FILE, scopes=SCOPES, redirect_uri=REDIRECT_URI ) flow.fetch_token(code=code) credentials = flow.credentials access_token = credentials.token refresh_token = credentials.refresh_token return JsonResponse({'access_token': access_token, 'refresh_token': refresh_token}) redirect url in google console frontend code of reactjs const [authUrl, setAuthUrl] = useState(''); useEffect(() => { axios.get('http://localhost:8000/email/get_auth_url') .then((response) => { setAuthUrl(response.data.auth_url); }) .catch((error) => { console.error(error); }); }, []); const handleSignIn = () => { window.location.href = authUrl; }; const handleCallback = () => { const urlParams = new URLSearchParams(window.location.search); const code = urlParams.get('code'); axios.get(`http://localhost:8000/email/exchangeToken/?code=${code}`) .then((response) => { const { access_token, refresh_token } = response.data; // Use access_token and refresh_token as needed console.log('Access Token:', access_token); console.log('Refresh Token:', refresh_token); }) .catch((error) => { console.error(error); }); }; useEffect(() => { if (window.location.search.includes('code=')) { handleCallback(); … -
Display Domain Instead of IP in Address Bar When Accessing Django Web App
I'm running a Django web app (version 5.0) on a Hostinger VPS, utilizing Nginx (version 1.18.0, Ubuntu) as a reverse proxy server. My Nginx configuration in /etc/nginx/sites-available is as follows: server { listen 80; server_name www.example.com example.com; location / { proxy_pass http://localhost:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } The web app works correctly when accessed through my domain (example.com), but in the browser's address bar, it displays the server's IP instead of the domain. I have purchased the domain through Netim.com and configured the DNS records accordingly to point to my server's IP address. How can I configure Nginx so that when accessing the web app via the domain, it displays the domain in the address bar instead of the server's IP? I have tried several variations for /etc/nginx/sites-available for example: server { listen 80; server_name www.example.com example.com; location / { proxy_pass http://localhost:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect http://localhost:8000/ http://www.example.com/; } } However, I still get the same result. -
why docker-compose up is failing on windows?
below is my docker-compose.yml code version: "3.9" services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - ./app:/app command: docker-compose run --rm app sh -c "python manage.py runserver 0.0.0.0:8000" when I try docker-compose up it throw below error [+] Running 0/1 - Container recipe-app-api-app-1 Starting 0.7s Error response from daemon: failed to create task for container: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "docker-compose": executable file not found in $PATH: unknown when I replace the command with python manage.py runserver 0.0.0.0:8000 it work fine, or even I directly copy docker-compose run --rm app sh -c "python manage.py runserver 0.0.0.0:8000" and execute it work fine. I am using windows 11 terminal, and below is my Dockerfile, any help will be highly appreciated. FROM python:3.12.1-alpine3.19 LABEL maintainer="jtelemarketing.com" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt . COPY ./requirements.dev.txt . COPY ./app /app WORKDIR /app EXPOSE 8000 ARG DEV=false RUN python -m venv /py && \ pip install --upgrade pop && \ pip install -r /requirements.txt && \ if [ $DEV == "true" ]; \ then pip install -r /requirements.dev.txt ; \ fi ENV PATH="C:\Program Files\Python38\:$PATH" -
How to remove objects in writable nested serializer DRF
I create APIs for frontend operations with DRF I use serializers nested in 5 different models in one of these APIs. I have no problems with registration and updating, but I have problems with deletion. When I send a deletion request, out of 5 different models, only the rows in the model where the foreing keys are recorded are deleted, the rows in the other models remain constant. How can I delete the data in models linked to each other at the same time during the deletion process? Thank you to everyone who took the time model.py class İslemBilgi(models.Model): durum = models.CharField(max_length=1000, blank=False, null=True, verbose_name='durum', help_text='durum') islemTuru = models.CharField(max_length=1000, blank=False, null=True, verbose_name='İşlem Türü', help_text='İşlem Türü') islemBaslatan = models.CharField(max_length=1000, blank=False, null=True, verbose_name='işlem Başlatan', help_text='İşlem Başlatan') guncelleyen = models.CharField(max_length=1000, blank=False, null=True, verbose_name='guncelleyen', help_text='guncelleyen') arac = models.ForeignKey(AracBilgi, on_delete=models.CASCADE) kaporta = models.ForeignKey(KaportaTablo, on_delete=models.CASCADE) mekanik = models.ForeignKey(MekanikTablo, on_delete=models.CASCADE) alici = models.ForeignKey(AliciTablo, on_delete=models.CASCADE) satici = models.ForeignKey(SaticiTablo, on_delete=models.CASCADE) teminat = models.CharField(max_length=200, blank=False, null=True, verbose_name='Teminat Tutarı', help_text='Teminat Tutarı Giriniz') class MekanikTablo(models.Model): yakitturu = models.CharField(max_length=25, blank=False, null=True, verbose_name='Yakit Türü', help_text='Yakit Türü Giriniz') turbo = models.CharField(max_length=1000, blank=False, null=True, verbose_name='Turbo', help_text='Turbo Durumunu Giriniz') aracnotlari = models.CharField(max_length=2000, blank=False, null=True, verbose_name='Araç Notları', help_text='Araç Notları Giriniz') enjektor = models.CharField(max_length=1000, blank=False, null=True, verbose_name='Enjektör', help_text='Enjektör Durumunu … -
import module works fine with global interpreter but not with virtual environment's interpreter
I've set foot into Django framwork. I have a problem like this At first i created a project called PUDDLE and and app called "Core" then in the PUDDLE.urls i'm trying to import the views.py iside the core app like this importing core app I got an error showing up Pylance error Even this error is showing but when i run the command "python manage.py runserver" then it works fine Server works fine. But the error still there Notic that i'm using the virtual environtment's interpreter. Then i switch to the global interpreter then the error disappear + everything still works fine. I've tried to install Pylance in virtual environtment. I'ved try to set the PythonPATH. I've tried to reset the Python Language Server What i don't understand is why when i'm using the virtual environment's interpreter the error about Pylance showing + everything still works fine. I switch to global interpreter Pylance error disappear + everything still works fine. Why? and what are the differences between the global and virtual environment's interpreter -
Architecturing a django microservice project
I am trying to build a project using micro-service architecture. I have several Typescript services and I want to integrate the services from a Django project to my services. My Django project expose multiple URLs and some commands, and I would like to have a distinct service for each of these. Here is the file structure I expect for my services : ├── package.json ├── packages │ ├── service-1 │ │ ├── app │ │ │ ├── Dockerfile │ │ │ ├── // Typescript service │ │ ├── infrastructure │ │ │ ├── // Terraform resources │ │ ├── Makefile │ │ ├── project.json │ │ └── README.md │ ├── service-2 │ │ ├── app │ │ │ ├── // Typescript service │ │ ├── infrastructure │ │ │ ├── // Terraform resources │ │ ├── Makefile │ │ ├── project.json │ │ └── README.md │ ├── django-service-1 │ │ ├── app │ │ │ ├── // TODO : What would be the structure of my django service here ? │ │ ├── infrastructure │ │ │ ├── // Terraform resources │ │ ├── Makefile │ │ ├── project.json │ │ └── README.md │ ├── django-service-2 │ │ ├── app … -
Can't redirect to success page in Django + Stripe project
I'm developing my first test Django Stripe project, but I'm currently stuck at the point because the redirect on success page is not working. This is my views.py file import stripe from django.conf import settings from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django.views import View from django.views.generic import TemplateView from .models import Item stripe.api_key = settings.STRIPE_SECRET_KEY class ProductLandingPageView(TemplateView): template_name = 'landing.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) item_id = self.kwargs["id"] item = get_object_or_404(Item, id=item_id) context['item'] = item return context class CreateCheckoutSessionView(View): def get(self, request, *args, **kwargs): item_id = self.kwargs["id"] DOMAIN: str = 'http://127.0.0.1:8000' item = Item.objects.get(id=item_id) session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'usd', 'unit_amount': item.price * 100, 'product_data': { 'name': item.name, }, }, 'quantity': 1, }, ], payment_intent_data={ 'metadata': { 'item_id': item.id, }, }, mode='payment', success_url=DOMAIN + '/success/', cancel_url=DOMAIN + '/cancel/', ) return HttpResponse(session.id) class SuccessView(TemplateView): template_name = "success.html" class CancelView(TemplateView): template_name = "cancel.html" And this is my template.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Homepage</title> <script src="https://js.stripe.com/v3/"></script> </head> <body> <div class="description"> <h3>{{ item.name }}</h3> <h5>{{ item.display_price }} USD.</h5> </div> <button id="buy-button" data-item-id="{{ item.id }}">Buy</button> <script> document.getElementById('buy-button').addEventListener('click', function() { var itemId = this.getAttribute('data-item-id'); fetch('/buy/' … -
How to get the user details of the logged-in user in every view function in Django?
For my project, I use build-in user authentication of django. Then using that details I query a custom table to get additional details pertaining to that user. Actually, I need this user details in every view function in the project as these details are then carried forward through context variable to every template in the project. This is for setting the menu bar of the website using these user details accordingly. Now the thing is .. I have written a function named 'logged_user_details' for populating these details in to a context variable in that function, which is then passed to every other view functions in which it is called. Then this context variable is then appended with the context variable of that view function and forwarded to template. Somewhere..I think it is not suppose to be like this. The point is I need to call this function in every view function written in the project and then append context variable of this custom function with the context variable of that view function. I am new to django, Please help me. Thank You.. -
Unable to collect static files on google cloud
Hello All I am unable to render static files of my django project which is hosted on GCP. My configuration: #Static Files GS_BUCKET_NAME = 'my_bucket_name' GS_PROJECT_ID = 'my_id' DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') STATIC_URL = 'https://storage.googleapis.com/my_bucket_name/static/' GS_CREDENTIALS = service_account.Credentials.from_service_account_file(os.path.join(BASE_DIR, 'service_account.json')) #End I ran collectstatic. static files are copied on my gcp bucket but I am getting this error - Could not load Google Cloud Storage bindings. Error is coming at this line <link rel="stylesheet" href="{% static 'admin/css/main.css' %}">. Did not find specific solution. Any help would be really appreciated. -
Mocking external api client class for pytest
I want to mock client Class to external api: class ExternalApiClient: def __init__(self, request: HttpRequest): session = getattr(request, "session", None) self.cars = ExternalApiCarsClient(request) This is new feature in my application any my pytests need it to works again, beacuse views use this ExternalApiClient to every operatation f.e.: class CarView(viewsets.ModelViewSet): def update(self, request, *args, **kwargs): ...some_code... client = ExternalApiClient(request) client.cars.some_method() return Response(status=status.HTTP_200_OK) I read unittest.mock documentation and tried to do like this: @patch('path.to.file.ExternalApiClient', NewMockedClass) def test_car_update(self): ...some_code... self.client.patch(car_detail_url) # this patch using update method from CarView but it's not working. My CarView still uses ExternalApiClient instead NewMockedClass. Can I somehow mock whole ExternalApiClient or at least mock separately init method and other methods of this class? -
hindi text html into pdf in django encoding problem using xhtml2pdf library
enter image description here this is my problem it gives unreadable format of text------ like this wertwertwert wertwertwertwert vinita asdfasdf obj.0.mypswdasdfasdf ■■■■ ■■■■ ■■ ■■ ■■■■■■■■■■■■■■■■■■ ■■■■■■■■■■■■■■■ ■■■■■■■■ dfkasd this is my code def show_products(request): products = crudajax.objects.filter(delete_flag=False).all() template_path = 'pdf_report.html' context = {'products': products} response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="report.pdf"' template = get_template(template_path) html = template.render(context) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result, encoding='UTF-8') if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') if pdf.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response plz help me i want to resolve this problem , it become headache to me , my manager forcing me ... i tryed many library like ...html2pdf, reportlab, etc... but not resolev -
making two input forms in a webpage (Django)
I made two input forms(① and ②) in a webpage, but both did not work properly. in ① format,{{form_1.as_p}} is working well, but <input type="text“ name="user_input_income"...> isn't working in ② format, <input type="text" name="user_input_withdrawal"..> is not working. Actually, what I want to form is ② format. How can I change the code for ② format ? The problem is explained in more detail as the following image. please help and thank you for your help in advance. <views.py> def input(request): items_income= Memo_income.objects.all() items_withdrawal = Memo_withdrawal.objects.all() if request.method == 'POST': if 'user_input_withdrawal' in request.POST: form = InputForm2(request.POST, prefix='user_input_withdrawal') if form.is_valid(): # Get the ID from the form data item_id = request.POST.get('id') # Fetch the item by ID item = get_object_or_404(Memo_withdrawal,id=item_id) # Update the item with the new data from the form item.user_input_withdrawal = form.cleaned_data['user_input_withdrawal'] # Update other fields as needed item.save() return redirect('input') # Redirect to the table display page after updating elif 'user_input_income' in request.POST: form = InputForm1(request.POST, prefix='user_input_income') if form.is_valid(): item_id = request.POST.get('id') item = get_object_or_404(Memo_income,id=item_id) item.user_input_income = form.cleaned_data['user_input_income'] item.save() return redirect('input') else: #the logic for handling Http GET request form1=InputForm1(prefix='user_input_income') form2 = InputForm2(prefix='user_input_withdrawal') return render(request, 'report/input.html', {'items_income':items_income, 'items_withdrawal': items_withdrawal,'form1':form1,'form2':form2}) <input.html> <table> <tr> <th>적요(저장내역)</th> <th>입금 종류(저장내역)</th> <th>변경사항 입력</th> </tr> … -
Why are GAE appspot URLs routed to the default service?
I am deploying 3 different instances of my python/django application as 3 different services within my project. app-devl as a shared dev environment app-test as a test environment default for the production environment I have a custom domain aliases mapped to the various services via the dispatch.yaml (devl.myapp.com, test.myapp.com, and myapp.com). These all work just fine. But the 'built-in' appspot URLs for each service appear to be routed to the default service. As per the documentation https://cloud.google.com/appengine/docs/legacy/standard/python/how-requests-are-routed, URLs with this format: https://SERVICE_ID-dot-PROJECT_ID.REGION_ID.r.appspot.com should be routed to the specified service, but that just isn't happening. Both of these URLs (with the correct service-id) are being routed to the default service: app-devl-dot-{project-id}.nn.r.appspot.com app-test-dot-{project-id}.nn.r.appspot.com Even clicking on the service in the GAE console (https://console.cloud.google.com/appengine/services) appears to be routed to the default service. While users can go to the custom domain and hit the correct environment, other google cloud services (e.g. Cloud Tasks) that target a specific service use the appspot URLs and those are being routed to the wrong environment. Any thoughts? -
File "<frozen importlib._bootstrap>", line 216, in _lock_unlock_module Error
I am hosting my Django site in C panel and I am getting the above error when I try to migrate the database to create tables and schema. What could be the issue? I have never encountered such an error before. I did an online research on the problem and I am not able to get the solutions to the exact problem. In what circumstances do errors occur? Also, what could be the problem with my codebase to trigger the error? Below is the full error log: stderr: OpenBLAS blas_thread_init: pthread_create failed for thread 23 of 24: Resource temporarily unavailable OpenBLAS blas_thread_init: RLIMIT_NPROC -1 current, -1 max Traceback (most recent call last): File "/home/albaalaw/public_html/family_tree_backend/manage.py", line 22, in <module> main() File "/home/albaalaw/public_html/family_tree_backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/albaalaw/virtualenv/public_html/family_tree_backend/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/albaalaw/virtualenv/public_html/family_tree_backend/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/albaalaw/virtualenv/public_html/family_tree_backend/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/albaalaw/virtualenv/public_html/family_tree_backend/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 393, in execute self.check() File "/home/albaalaw/virtualenv/public_html/family_tree_backend/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/home/albaalaw/virtualenv/public_html/family_tree_backend/3.10/lib/python3.10/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/albaalaw/virtualenv/public_html/family_tree_backend/3.10/lib/python3.10/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/albaalaw/virtualenv/public_html/family_tree_backend/3.10/lib/python3.10/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/albaalaw/virtualenv/public_html/family_tree_backend/3.10/lib/python3.10/site-packages/django/urls/resolvers.py", line 416, in check for pattern in self.url_patterns: … -
Django models Don't check fields Integrity
consider the model below class Faculty(models.Model): name = models.CharField(max_length=255) short_name = models.CharField(max_length=15) description = models.CharField(max_length=512) logo = models.ImageField(upload_to=faculty_upload_to, null=True) That I do Faculty.objects.create() Or faculty = Faculty() faculty.save() this creates an empty entry in the database >>> from universities.models import * >>> Faculty.objects.create() <Faculty: Faculty object (2)> why django doesn't give me an integrity error. I use django 5.0 -
StratifiedKFold results in missing labels?
I was using StratifiedKFold fold from scikit-learn and noticed missing labels. I had 7 labels initially, but after splitting using k fold cross validation, every fold had missed the labels '1', and '5'; but after training somehow my model's confusion matrix was 7x7 (for each fold separately), how? And if its stratified, then shouldn't all values labels get separated class-wise? X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.25, random_state=2024) print(y_train.value_counts()) y_train.value_counts().sum() OUTPUT[1]: Label 0 1422917 3 241329 2 6864 6 1607 5 1468 1 1081 4 27 Name: count, dtype: int64 1675293 Folds_split = StratifiedKFold(n_splits=2, shuffle=True, random_state=2024) for i, (train_index, test_index) in enumerate(Folds_split.split(X_train, y_train)): X_train_fold= X.iloc[train_index] X_test_fold = X.iloc[test_index] y_train_fold= y.iloc[train_index] y_test_fold= y.iloc[test_index] print(y_train_fold.value_counts()) print(len(y_train_fold)) print(y_test_fold.value_counts()) print(len(y_test_fold)) print(len(y_train_fold)+len(y_test_fold)) print(len(y_train_fold)/(len(y_train_fold)+len(y_test_fold))) OUTPUT[2]: Label 0 734822 3 97170 2 4547 6 1097 4 10 Name: count, dtype: int64 837646 Label 0 735395 3 96586 2 4605 6 1046 4 15 Name: count, dtype: int64 837647 1675293 0.4999997015447447 Label 0 735395 3 96586 2 4605 6 1046 4 15 Name: count, dtype: int64 837647 Label 0 734822 3 97170 2 4547 6 1097 4 10 Name: count, dtype: int64 837646 1675293 0.5000002984552553 Where are the counts for label '1' and '5'? -
Displaying image uploaded via Django FileField()
I have a Django model for coaching programs in my site, I want to be able to upload a thumbnail image for every program. I used FileField() for that and set the "upload_to=" to the static folder. I am trying to display the image in the site using django templates, I configured the 'scr' attribute in the tag but I am getting a 404 on GET response when the HTML tries to get the image: [01/Jan/2024 21:13:00] "GET /fit/static/fit/coaching/program_imgs/article_img.jpg HTTP/1.1" 404 3818 I just want to be able to display the images uploaded to the db in the site. When I acess the folder that the image was uploaded, the image is there just like it should be, I don't know why I can't display it in the HTML. Important note: I am creating the db objects for the articles directly via the django admin site. here is my models.py: class coaching_programs(models.Model): coach = models.ForeignKey(User,on_delete=models.CASCADE, related_name='coach') title = models.CharField(max_length=35, unique=True) description = models.CharField(max_length=120) price = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True) text = models.FileField(upload_to='fit/static/fit/coaching/program_text/',null=True,blank=True) # i will put md files in this filefield() above. img = models.FileField(upload_to='static/fit/coaching/program_imgs/',null=True,blank=True) my HTML/ django templates: {%for post in posts%} <div class="post"> {{post.img}} <img src="../../../{{post.img}}" alt=""> <p>{{post.title}}</p> <p>{{post.price}}</p> <p>{{post.description}}</p> </div> … -
MasterCard Token Fetch Error with ReactJs Frontend
I'm trying to fetch my token from this endpoint on mastercard (https://api.finicity.com/aggregation/v2/partners/authentication) from my react app and I keep getting the error "ccess to fetch at 'https://api.finicity.com/aggregation/v2/partners/authentication' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled." I've tried using https and set up a server on ngrok and it still doesnt work, when I use mode:'no-cors', I get no response. This is the relvant code const getMasterCardData = async() =>{ const token = authTokens.access; try { const response = await fetch('http://127.0.0.1:8000/api/mastercard/', { method: 'GET', headers: { 'Authorization': `Bearer ${token}`, }, }); if (response.ok) { const data = await response.json(); console.log(data); await getAccessToken(data); } else { alert('Failed to fetch data'); } } catch (error) { console.error('Error:', error); alert('Something went wrong'); } } const getAccessToken = async(data) => { try { const response = await fetch('https://api.finicity.com/aggregation/v2/partners/authentication', { method: 'POST', // Or any other method as required headers: { 'Content-Type': 'application/json', 'Finicity-App-Key': data.app_key, 'Accept': 'application/json', 'Access-Control-Allow-Origin': '*', "Access-Control-Allow-Methods": "OPTIONS, GET, POST, PUT, PATCH, DELETE", }, …