Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Failing to authenticate my React frontend with backend using google-auth-login: Failing likely due to polyfills missing in react-scripts 5
I deployed both my backend (Django) and frontend (React create-app) services to Google Cloud Run. As long as my Django service doesn't require authentication, everything works great. I've tried following this doc on authenticating service-to-service but without any success. As soon as I import google-auth-login, my react app errors out with a series of dependency missing (browserify, url, crypto, etc). I've read from other questions that this is due to react-scripts 5 missing polyfills. I've tried to download them and add the fallbacks to my webpack.config.js as directed by the error messages but even when I add them all and resolve this issue I run into a series of warnings/errors , failing to parse different modules like: 'node_modules/https-proxy-agent/src/agent.ts', 'node_modules/google-auth-library/build/src/auth/oauth2client.js.map', 'node_modules/google-auth-library/build/src/auth/iam.js.map' etc. What am I doing wrong? Are there alternatives to using google-auth-login to authenticate my frontend service? Should I just deploy those outside of Google Cloud Run? -
Django Heroku Server Error (500) when I set Debug - False. When Debug - True it is working good
I get error 500 when debug = False. But when my debug = True it is workd fine. My settings.py: import os from pathlib import Path from decouple import config import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'blog', 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware' ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], # Before: 'DIRS': ['templates'] 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': '127.0.0.1', 'PORT': '5432', } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ … -
How to access specific value from model choice field in django
So i have this material models which contain 3 values and can be selected from dropdown menu in the template, how can access this exact "tegangan_tarik" and "tegangan_values to be included in my output page models.py class Materials(models.Model): SAE_Number = models.CharField(max_length=64) tegangan_tarik = models.FloatField() tegangan_luluh = models.FloatField() def __str__(self): return f"{self.SAE_Number}: Su = {self.tegangan_tarik} MPa; Sy = {self.tegangan_luluh} MPa" forms.py from django import forms from .models import * class MyForm(forms.Form): N = forms.FloatField(label="Faktor Keamanan ", widget=forms.NumberInput(attrs={'value': '2.0', 'min': '0'})) T = forms.FloatField(label="Momen Puntir / Torsi ", widget=forms.NumberInput(attrs={'placeholder': 'N-mm', 'min': '0'})) Material = forms.ModelChoiceField( label = "Pilih Bahan :", queryset = Materials.objects.all()) Ft = forms.FloatField(label="Gaya Tangensial Pada Elemen (Ft) ", widget=forms.NumberInput(attrs={'placeholder': 'N', 'min': '0'})) Fr = forms.FloatField(label="Gaya Radial Pada Elemen (Fr) ", widget=forms.NumberInput(attrs={'placeholder': 'N', 'min': '0'})) AB = forms.FloatField(label="Jarak Antara Bantalan A ke Elemen B (AB) ", widget=forms.NumberInput(attrs={'placeholder': 'mm', 'min': '0'})) BC = forms.FloatField(label="Jarak Antara Bantalan C ke Elemen B (BC) ", widget=forms.NumberInput(attrs={'placeholder': 'mm', 'min': '0'})) views.py from django.shortcuts import render from .forms import * import math # Create your views here. def input(request): return render(request, "shaft/input.html", { "form": MyForm(), }) def output(request): N = float(request.POST['N']) T = float(request.POST['T']) Sy = #how to access this tegangan_tarik value from the models Su … -
Using MSAL Python/Django, how do I get Authenticated event?
I have a working Django app that uses the MSAL library ms-identity-python-utilities@main. I can successfully sign in to Azure AD. I need to however load the local user object from my database on successful sign in, like I used to do in my old /login URL endpoint, to call auth_login(request, user). This should happen after the OAuth2 flow succeeded. Intent is to use OAuth2 as SSO. How do I intercept this event? I.e. after successful OAuth2 authentication, call a method that can call auth_login(request, user) and set the user object into the session for future use? I could not find any references in the samples / forums. @ms_identity_web.login_required works to ensure authentication for views, but I want a decorator or class I can extend to intercept signed on event. -
What is meaning of 'use_in_migrations' used in UserManager class of django?
What is meaning of 'use_in_migrations' used in UserManager class of django? class MyUserManager(BaseUserManager): ... use_in_migrations = True ... I want to know about meaning of the keyword 'use_in_migrations' used in UserManager class of django. -
django-admin runserver doesn't work is throw this error You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings?
I´m trying to do runserve in my project using Pycharm but the follow error is throw: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. however i set the enviroment variable but is not working. enter image description here environment variable enter image description here -
Convert Django model array into alpine.js array
I try to convert Django model ArrayField into Alpine.js array. How to solve this problem? x-on:click="offer_1 = !offer_1; currentJob={ title: '{{ job.title }}', responsibilities: [{{ job.responsibilities }}] ???????, }"> and then I want display it: <template x-for="responsibility in responsibilities"> <li class="text-sm text-darkPurple font-light pl-5 bg-[url('../img/plus.svg')] bg-no-repeat bg-[top_4px_left] mb-4" x-text="responsibility"> </li> </template> -
nginx dot'n static in django project
After settings nginx in server static has disappeared from the site. If you work only with gunicorn, all everything is successful. Command "python manage.py collectstatic " executed : 440 static files copied to '/home/v_n_kich/Project_LAWboard/static'. settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') sudo nano /etc/nginx/sites-enabled/default server { listen 80; listen 51.250.71.28; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/v_n_kich/Project_LAWboard/; } location /media/ { root /home/v_n_kich/Project_LAWboard/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) sudo less /var/log/nginx/error.log: 2023/02/20 22:59:11 [error] 861#861: *14 open() "/home/v_n_kich/Project_LAWboard/static/bootstrap/dist/js/bootstrap.min.js" failed (13: Permission denied), client: 178.71.105.162, server: , request: "GET /static/bootstrap/dist/js/bootstrap.min.js HTTP/1.1", host: "51.250.71.28", referrer: "http://51.250.71.28/auth/signup/ -
Getting Django 500 errors flagged by sentry
We are paying for sentry, but evidently that doesn't qualify us for timely support. I've created a minimum reproduction repo. This case has been open with them for a couple of days now but they just aren't responding. running runserver with settings.DEBUG=0 and sentry_sdk.debug=True Basically what happens is that this: System check identified no issues (0 silenced). February 20, 2023 - 22:51:50 Django version 4.1.7, using settings 'sentry_problem.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [sentry] DEBUG: [Tracing] Adding `sentry-trace` header 4aa953c03dfa443cb06e0f0ecd8bedf2-b08d08fd5102560a- to outgoing request to https://o976653.ingest.sentry.io/api/4504707199270912/store/. [sentry] DEBUG: [Tracing] Discarding <http.server> transaction <generic WSGI request> because traces_sample_rate is set to 0 ERROR - [2023-02-20 22:52:02] - blowup.views.boom:10 - This is before the boom [sentry] DEBUG: Sending event, type:null level:error event_id:f2cdc3f26dd24509929e1129558116bf project:4504707199270912 host:o976653.ingest.sentry.io [sentry] DEBUG: [Tracing] Adding `sentry-trace` header f8e5e532ef6a4a7b90d634fb1bda417f-b540c108bc09311b-0 to outgoing request to https://o976653.ingest.sentry.io/api/4504707199270912/store/. [sentry] DEBUG: [Tracing] Adding `baggage` header sentry-trace_id=f8e5e532ef6a4a7b90d634fb1bda417f,sentry-environment=production,sentry-release=20dadf61a55e11789e96ad7171fd17445baee6d3,sentry-public_key=d7b21f46c2b74e1b80342cb97fde024e,sentry-transaction=/,sentry-sample_rate=0.0 to outgoing request to https://o976653.ingest.sentry.io/api/4504707199270912/store/. ERROR - [2023-02-20 22:52:02] - django.request.log_response:241 - Internal Server Error: / Traceback (most recent call last): File "sentry-problem/lib/python3.11/site-packages/django/core/handlers/exception.py", line 56, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "sentry-problem/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "sentry-problem/lib/python3.11/site-packages/sentry_sdk/integrations/django/views.py", line 85, in sentry_wrapped_callback return callback(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File … -
Django form. POST request
When user cannot log in(because he entered a wrong password for example) page reloads and shows that password incorrect, then, when user reloads page again the same form with the same completed fields and with the same error will be generated on the page. Problem is, that somehow after reloading method is still POST. Why? I wanna form to clear itself when I reload a page. I'm new at Django, so, I hope somebody can help me! views.py from django.forms import ValidationError from django.shortcuts import render, redirect from .forms import LogInForm, SignUpForm from django.contrib.auth.decorators import login_required from django.contrib.auth.hashers import make_password from django.contrib.auth import authenticate, logout, login as auth_login from django.contrib import messages from django.http import HttpResponseRedirect, HttpResponse # Create your views here. def login(request): logInForm = LogInForm() if request.method == 'POST': form = LogInForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate( username=cd['username'], password=cd['password']) if user is not None: auth_login(request, user) return redirect("home") else: messages.error(request, "Invalid login or password") return render(request, 'logIn.html', {"form": form}) else: return HttpResponse("afs") else: return render(request, 'logIn.html', {"form": logInForm}) def logout_view(request): logout(request) return redirect('login') @login_required def profile(request): return render(request, 'profile.html') @login_required def toDoList(request): current_user = request.user username = current_user.username return render(request, 'toDoList.html', {'username': username}) def signUp(request): … -
Unable to get params from axios post request in Django view
I am currently sending an axios POST request like this from a react frontend to a Django backend const data = { 'username': username, 'first_name': first_name, 'last_name': last_name, 'email': email, 'password1': password1, 'password2': password2, } const user_response = axios.post(process.env.REACT_APP_API_BACKEND_URL + '/users/create', data); and attempting to get get these parameters in a Django view like so: class create_user(APIView): def post(self, request): print('request: ', request.POST) return JsonResponse({'status': 'success'}, status=status.HTTP_200_OK) However, this returns an empty dictionary. request: <QueryDict: {}> How do I successfully get the POST request parameters? -
Set Empty Fields After Submission Using FormView
Currently I have a django project which includes a RegisterForm and a RegisterView these appear as the following: class RegisterView(FormView): ... def form_valid(self, form): ... return HttpResponseRedirect(...) Similarly, class RegisterForm(forms.Form): ... def clean(self): ... return data At the submission page of the RegisterForm I've come to realize that it doesn't run form_valid() until not a single error appears in clean(). My only issue with this is that, if any errors occur I want to be able to set certain fields to empty on submission. How can I do this? For more details, I want to keep all the values on the page but remove some of them, the code already does this perfectly but it keeps everything until its validated and I can't seem to remove some of them. I tried passing through self.request to my RegisterForm to see if I could update the self.request.session[...] = '' but this doesn't seem to work. I also tried updating the initial value inside clean() by doing self.initial[...] = '' but this doesn't seem to be working either. I'm kind of stuck and worried I might have to change the design of my program (which I don't want to have to do because … -
How to render pdfs separately based on a OneToMany model using DRF?
I have a OneToMany model where a Contest can have many Documents. Each document has a PDF file, and I need to render each PDF file separately for a given contest. To achieve this, I created a Document model with a ForeignKey to Contest and a FileField to upload the PDF file. I also created a DocumentViewSet with a custom action to upload a PDF file to a document. Finally, I created the necessary URLs to handle the requests. I wrote a test case to upload a PDF file, but it gives me the following error: {'detail': ErrorDetail(string='Not found.', code='not_found')} Here is the code for my attempt: models.py class Document(models.Model): contest = models.ForeignKey(Contest, on_delete=models.CASCADE, related_name='documents') pdf = models.FileField(null=True, upload_to=contest_pdf_file_path) uploaded_at = models.DateTimeField(auto_now_add=True) document_slug = models.SlugField(max_length=255, blank=True) def __str__(self): return f"Document for {self.contest.title}" views.py class DocumentViewSet(viewsets.ModelViewSet): serializer_class = serializers.DocumentSerializer queryset = Document.objects.all() authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] lookup_field = 'document_slug' def get_queryset(self): return self.queryset.order_by('-id') def perform_create(self, serializer): serializer.save() def get_serializer_class(self): if self.action == 'upload_pdf': return serializers.DocumentSerializer return self.serializer_class @action(methods=['POST'], detail=True, url_path='contests/(?P<contest_slug>[-a-zA-Z0-9_]+)/upload_pdf') def upload_pdf(self, request, contest_slug=None, document_slug=None): document = self.get_object() serializer = self.get_serializer(document, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py router = DefaultRouter() router.register('contests', views.ContestViewSet) router.register('tags', views.TagViewSet) … -
where'is the problem authentificat error ,How can I redirect users login to different pages based on session data in django
in login user.save() ^^^^ UnboundLocalError: cannot access local variable 'user' where it is not associated with a value here is my code in html: {% extends "base.html" %} {% block content %} <h1><h1><b>Connexion</b></h1></h1> {% csrf_token %} <b>Email</b> </div> <br> <div class="form-group"> <label for="exampleInputPassword1"><b>Password</b></label> <input type="password" class="form-control" id="Password"> </div> <br> <button class="btn btn-primary-orange register-newsletter text-white" type="submit" id="button-addon" style="background-color: #fd7e14;" href="{% url 'etudiant' %}"><b>Je me connecte</b></button> <p class="mb-0 "><a style="color: coral;" href="{% url 'etudiant' %}" class="text-orange"><b>J'ai un compte</b></a></p> </form> {% for msg in messages %} {{messages}} {% endfor %} </div> <div class="col-md-9 col-lg-6 col-xl-5"> <img src="https://mdbcdn.b-cdn.net/img/Photos/new-templates/bootstrap-login-form/draw2.webp" class="img-fluid img-reponsive" alt="Sample image" width=200% height=50%> </div> </div> {% endblock %} here is my code in views: def login(request): if request.method=="POST": user =User() user.Email=request.POST['Email'] user.Password=request.POST['Password'] else: user.save() return render(request, 'authentification/login.html') signup: def signup(request): if request.method=="POST": user =User() user.Name=request.POST['Name'] user.Email=request.POST['Email'] user.Password=request.POST['Password'] user.Confirm_password=request.POST['Confirm_password'] if user.password !=user.Confirm_password: return redirect('signup') elif user.Name=="" or user.password =="": messages.info(request,'some fields are emply') return redirect('signup') else: user.save() return render(request, 'authentification/signup.html') I don't know why user (I have two teacher and student models and a default user model) does not enter the application with his login -
Nested Serializer in DRF is not showing field names
I have 2 serializers, Serializer2 is nested in Serializer1 class Serializer1(): field1 = serializers.CharField() field2 = serializers.CharField() class Serializer2(): field3 = Serializer1() When I am sending a response using Serializer2, the response is coming fine, but I don't know why the field name for Serializer1 is not coming, and brackets for field 3 is coming like a list rather than a dictionary expected response { field3: { field1: 'string1', field2: 'string2' } } but actual response is like { field3: [ 'string1', 'string2' ] } I don't know why the actual response field3 has brackets like a list rather than like a dict in expected response. And field name for Serializer 1 is also not coming. -
On delete set default many-to-many field django
Whenever a Foreign key relation is created in django, you have an option to set that column to null, or default using the on_delete option. What i want to know is if it is possible to achieve the same thing with ManyToManyField Such that when the referenced column in Model A is deleted from database, the column with the ManyToManyField in Model B is set to default -
How to make variables sort and not repeating itself in Python-Django HTML page
So I do have 2 variables that I need to sort and make not to repeat itself and I have some difficulties to solve that: Problem is that I have {{user.followers.all}} that gave me that <QuerySet [<Follow: user1 started following admin>, <Follow: user2 started following admin>]> Problem is that I have {{new.likes.count}} that gave me just: 1 4 5 8 .... I am assuming that I got those variables from this: def __str__(self) -> str: return f"{self.followed_by.username} started following {self.followed.username}" So from that I tried to use basic logic something like {{user.followers.all}} has {{user.followers.all}} that gave me that <QuerySet [<Follow: user1 started following admin>, <Follow: user2 started following admin>]> "new in news" this is Blog Post {% for n in user.followers.all %} {% for new in news|slice:"5" %} //Here I want that it so that new in news shows only blog post of followers {% endfor %} {% endfor %} Second problem def like_news(request, pk): context = {} new = get_object_or_404(News, pk=pk) if request.user in new.likes.all(): new.likes.remove(request.user) context['liked'] = False context['like_count'] = new.likes.all().count() else: new.likes.add(request.user) context['liked'] = True context['like_count'] = new.likes.all().count() return JsonResponse(context, safe=False) {{new.likes.count}} variable has 4 5 1 6 8... I tried {% for n in new.likes.count %} … -
How to group filtering elements into groups in Django?
I need to do dynamic product filtering.I need to do dynamic product filtering. I had a problem, how to group filtering elements by categories. My model class CategoryCharacteristic(models.Model): category = models.ForeignKey("mainapp.Category", verbose_name='category', on_delete=models.CASCADE) feature_filter_name = models.CharField(verbose_name='name_of_filter', max_length=50) unit = models.CharField(max_length=50, verbose_name='unit_of_measurement', null=True, blank=True) class Meta: unique_together = ('category', 'feature_filter_name') ordering = ('id',) def __str__(self): return f"{self.category.title}-{self.feature_filter_name}-{self.unit}" class ProductCharacteristic(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='characteristics') feature = models.ForeignKey(CategoryCharacteristic,verbose_name='name_of_filter', on_delete=models.CASCADE) value = models.CharField(max_length=100) def __str__(self): return f'{self.feature.feature_filter_name} {self.value}' My forms class ProductFilterForm(forms.Form): min_price = forms.DecimalField(required=False) max_price = forms.DecimalField(required=False) characteristics = forms.ModelMultipleChoiceField( queryset=ProductCharacteristic.objects.all(), widget=forms.CheckboxSelectMultiple, required=False ) def filter_queryset(self, queryset): min_price = self.cleaned_data.get('min_price') max_price = self.cleaned_data.get('max_price') characteristics = self.cleaned_data.get('characteristics') if min_price: queryset = queryset.filter(price__gte=min_price) if max_price: queryset = queryset.filter(price__lte=max_price) if characteristics: characteristic_query = Q() for characteristic in characteristics: characteristic_query |= Q(characteristics=characteristic) queryset = queryset.filter(characteristic_query) return queryset view class ProductListView(ListView): model = Product template_name = 'mainapp/product_list.html' def get_queryset(self): self.category = get_object_or_404(Category, slug=self.kwargs['category_slug']) queryset = super().get_queryset().filter(category=self.category) filter_form = ProductFilterForm(self.request.GET) if filter_form.is_valid(): queryset = filter_form.filter_queryset(queryset) return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter_form'] = ProductFilterForm(self.request.GET) context['product'] = self.get_queryset() return context As a result, I want to get enter image description here I have no idea how to implement it -
Overriding serializers __init__ method to create nested serializers with custom parameters
I have created basic serializer in Django Rest Framework for model containing an ImageField. # images/models.py from django.db import models def upload_to(instance, filename): """Generate file path for the new image""": return 'changeit' class Image(models.Model): img = models.ImageField(upload_to=upload_to) user = models.ForeignKey('users.User', on_delete=models.CASCADE) # images/serializers.py """ Serializers for uploading images. """ import os from rest_framework import serializers from images.models import Image from images.utils import resize_image class ImageSerializer(serializers.Serializer): """Serializer for Image model.""" def __init__(self, instance=None, height=None, **kwargs): """Add height parameter to serializer contructor.""" super().__init__(**kwargs) self.height = height id = serializers.IntegerField(read_only=True) img = serializers.ImageField() def create(self, validated_data): """Assign uploaded image to authenticated user.""" return resize_image( user=self.context['request'].user, height=self.height, image=validated_data['img'] ) def validate_img(self, value): """Validate file extension.""" _, extension = os.path.splitext(value._get_name()) if extension not in ('.jpg', '.png'): raise serializers.ValidationError('Invalid file extension.') return value class BasicTierUserSerializer(ImageSerializer): """Serializer for Basic tier user.""" thumbnail_200px = serializers.SerializerMethodField() def get_thumbnail_200px(self, obj): return ImageSerializer(obj, height=200).data # images/utils.py """ Utility functions for manipulating uploaded images. """ from PIL import Image from config import celery_app from images.models import Image @celery_app.task(bind=True) def resize_image(self, user, image, height): if not height: return Image.objects.create( user=user, img=image, ) new_height = height new_width = int(image.width * (new_height / image.height)) return Image.objects.create( user=user, img=image.resize((new_height, new_width)), ) I want to return response … -
Deploying a Django-React app to Heroku: how to run npm and webpack
I'm currently trying to deploy a Django-React application to heroku using their build manifest approach. I have been roughly following this tutorial for configuring the relationship between React and Django. Everything works well locally with my React application rendering correctly and sending/receiving HTTP requests from the Django backend as expected. The problem comes when I try to deploy to production using the heroku build manifest. I can build and deploy to Heroku just fine, but the heroku app cannot find my "main.js" static file, which is the entry point to my react application. heroku.yml file looks as follows: build: docker: web: dockerfile: Dockerfile.heroku release: image: web command: - cd front_end && npm run dev run: web: gunicorn focal_point.wsgi:application --bind 0.0.0.0:$PORT where Dockerfile.heroku looks as follows: FROM python:3.9 AS back_end ENV NODE_VERSION=16.13.0 RUN apt install -y curl RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash ENV NVM_DIR=/root/.nvm RUN . "$NVM_DIR/nvm.sh" && nvm install ${NODE_VERSION} RUN . "$NVM_DIR/nvm.sh" && nvm use v${NODE_VERSION} RUN . "$NVM_DIR/nvm.sh" && nvm alias default v${NODE_VERSION} ENV PATH="/root/.nvm/versions/node/v${NODE_VERSION}/bin/:${PATH}" RUN node --version RUN npm --version WORKDIR /focal-point/front_end/ COPY ./front_end/package*.json /focal-point/front_end/ RUN npm install COPY ./front_end /focal-point/front_end/ EXPOSE 3000 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV DEBUG 1 WORKDIR /focal-point COPY ./Pipfile … -
How to hook up DRF ModelViewset to the app's root
I have a small django app with a single ViewSet that extends DRF's ModelViewSet. I've tried attaching it to the app's root url like so urlpatterns = [ path(r"", NotificationViewSet.as_view(), name="company"), ] But this is causing an error: TypeError: The actions argument must be provided when calling .as_view() on a ViewSet. For example .as_view({'get': 'list'}) The error is helpful enough to show how to map the get method and github copilot suggests: urlpatterns = [ path( r"", NotificationViewSet.as_view( { "get": "list", "post": "create", "patch": "partial_update", "delete": "destroy", } ), name="company", ), ] But I'm not sure this is correct. And this doesn't appear to handle retrieve which would require a URL parameter. I am surprised I have to be so explicit. Surely there is an easier way. -
Can't submit options in dropdown using bootstrap 5 in Django
I will use the dropdown in the registration system and the menus will have business and customer, how can I present them separately? enter image description here this register page enter image description here this register page views.py folder -
Call a viewset in another viewset with POST method
I want to call a function of a viewset in another viewset, with POST method. I succeed this with GET : params = {"number" : 44} zm = ZoneViewSet.as_view({"get": "zm"})(request._request, **params).render().content but, I can't with POST, I don't known how to do that :(, I've this error "GET method not allowed" : params = { "target": datetime.now().strftime(self.format_date), "value": 9, "origin": "auto", } post_zm = AccessViewSet.as_view({"post": "add"})(request._request, **params).render().content Can you help me please ? Thanks F. -
Pass in dynamic href using Django include template tag AND url tag
I'm trying to reuse a component and invoke it multiple times using the include tag. But when I want to pass in a url, I can't figure out the syntax. Usually it would be something like: <a href="{% url 'slug' %}">{{link_title}}</a> But as I'm already using an include, I want to do something equivalent to: # parent template: {% include 'my-template.html' with slug='someslug' link_title='My Link Title' %} # include template: <a href="{% url '{{slug}}' %}">{{link_title}}</a> I currently get django.urls.exceptions.NoReverseMatch from this code -
nginx+uwsgi stops responding after auto reload
I have a docker container based off Alpine 3.16 It runs nginx/uwsgi with supervisord for a django based app. This Dockerfile has been pretty much the same for several years now. Auto reload worked fine. Suddenly today after the container rebuilt, auto-reload fails in a strange way - it get hung up for minutes and then works - here is the log: 2023-02-20 14:57:28,771 INFO RPC interface 'supervisor' initialized 2023-02-20 14:57:28,771 INFO RPC interface 'supervisor' initialized 2023-02-20 14:57:28,771 INFO supervisord started with pid 1 2023-02-20 14:57:28,771 INFO supervisord started with pid 1 2023-02-20 14:57:29,774 INFO spawned: 'nginx' with pid 7 2023-02-20 14:57:29,774 INFO spawned: 'nginx' with pid 7 2023-02-20 14:57:29,777 INFO spawned: 'uwsgi' with pid 8 2023-02-20 14:57:29,777 INFO spawned: 'uwsgi' with pid 8 [uWSGI] getting INI configuration from /usr/lib/acme/lib/wsgi/uwsgi.ini 2023-02-20 14:57:29 - *** Starting uWSGI 2.0.21 (64bit) on [Mon Feb 20 14:57:29 2023] *** 2023-02-20 14:57:29 - compiled with version: 12.2.1 20220924 on 15 February 2023 09:44:04 2023-02-20 14:57:29 - os: Linux-6.1.11-arch1-1 #1 SMP PREEMPT_DYNAMIC Thu, 09 Feb 2023 20:06:08 +0000 2023-02-20 14:57:29 - nodename: b5d838731ef0 2023-02-20 14:57:29 - machine: x86_64 2023-02-20 14:57:29 - clock source: unix 2023-02-20 14:57:29 - pcre jit disabled 2023-02-20 14:57:29 - detected number of …