Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'django.utils'
I was trying to setup one of the open source project,During this when I run make postgres cmd on ubuntu terminal then I am getting following error -> Configure PostgreSQL database -> Create database user 'vulnerablecode' sudo -u postgres createuser --no-createrole --no-superuser --login --inherit --createdb vulnerablecode || true createuser: error: creation of new role failed: ERROR: role "vulnerablecode" already exists sudo -u postgres psql -c "alter user vulnerablecode with encrypted password 'vulnerablecode';" || true ALTER ROLE -> Drop 'vulnerablecode' database sudo -u postgres dropdb vulnerablecode || true -> Create 'vulnerablecode' database sudo -u postgres createdb --encoding=utf-8 --owner=vulnerablecode vulnerablecode make[1]: Entering directory '/mnt/c/Users/admin/Desktop/pankaj/About Code NextB/vulnerablecode' -> Apply database migrations venv/bin/python manage.py migrate Traceback (most recent call last): File "/mnt/c/Users/admin/Desktop/pankaj/About Code NextB/vulnerablecode/manage.py", line 6, in <module> command_line() File "/mnt/c/Users/admin/Desktop/pankaj/About Code NextB/vulnerablecode/vulnerablecode/__init__.py", line 22, in command_line from django.core.management import execute_from_command_line File "/mnt/c/Users/admin/Desktop/pankaj/About Code NextB/vulnerablecode/venv/lib/python3.10/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version ModuleNotFoundError: No module named 'django.utils' make[1]: *** [Makefile:92: migrate] Error 1 make[1]: Leaving directory '/mnt/c/Users/admin/Desktop/pankaj/About Code NextB/vulnerablecode' make: *** [Makefile:103: postgres] Error 2 In the above error,the main thing to emphasis is No module named 'django.utils' but after seeings I tried to install it using sudo-apt-get install django-utils then I am … -
UNIQUE constraint failed: products_category.id
I override Django model save method and it gives error when I am trying to edit some fileds existing post from admin panel. -
How to trigger a javascript animation when scrolled to that div on screen?
I am trying to trigger a simple typing animation when the user scrolls to that div on the screen. Here is my html: <div class="text-8xl"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Harum voluptas eveniet nulla sapiente libero sequi ipsam voluptatem ex porro nostrum laudantium modi, aliquam, est quia veritatis quod. Quas, voluptas neque. </div> <div class="flex justify-center items-center"> <h1>I am <span class="auto-type"></span></h1> </div> <div class="text-8xl"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Harum voluptas eveniet nulla sapiente libero sequi ipsam voluptatem ex porro nostrum laudantium modi, aliquam, est quia veritatis quod. Quas, voluptas neque. </div> And here is my javascript: <head> <script src="https://cdn.jsdelivr.net/npm/typed.js@2.0.12"></script> </head> ... <body> <script> var typed = new Typed(".auto-type", { strings: ["a person", "Sleeping", "coding"], typeSpeed: 150, backSpeed: 150, loop: true, }) </script> </body> How can you trigger this animation when this div enters the screen after scrolling? Thank you, and please leave any questions below. -
Why is my javascript for a simple on-scroll number counter not working?
My javascript is supposed to create the counter effect for numbers when scrolled down. However, it doesn't seem to work, and I can't seem to know why. Here is my brief html code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title></title> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <style> .fake-div { width:100%; height: 1280px; position:relative; } </style> </head> <body> <div class="fake-div"> </div> <div id="counter"> <div class="counter-value" data-count="300">0</div> <div class="counter-value" data-count="400">100</div> <div class="counter-value" data-count="1500">200</div> </div> <div class="fake-div"> </div> <script> var a = 0; $(window).scroll(function() { var oTop = $('#counter').offset().top - window.innerHeight; if (a == 0 && $(window).scrollTop() > oTop) { $('.counter-value').each(function() { var $this = $(this), countTo = $this.attr('data-count'); $({ countNum: $this.text() }).animate({ countNum: countTo }, { duration: 2000, easing: 'swing', step: function() { $this.text(Math.floor(this.countNum)); }, complete: function() { $this.text(this.countNum); //alert('finished'); } }); }); a = 1; } }); </script> </body> </html> The code is taken from the website below. Although it is the exact same code, it doesn't seem to work on my desktop. https://codepen.io/dmcreis/pen/VLLYPo Thank you, and please leave any questions below. -
django-fsm: dynamically-generated value based upon model instance in the custom properties for transition decorator
I'm incorporating django-fsm into a Django project containing a model that will include a number of state transitions, like so: from django_fsm import FSMField, transition class Record(models.Model): state = FSMField(default='new') @transition( field=state, source=['new', 'flagged'], target='curated', custom=dict( verbose="Curate as trustworthy", explanation=("This record is deemed trustworthy."), url_path="curate/", #url_path=reverse("record-curate", kwargs={"pk": self.pk}), ), ) def curate(self, by=None, description=None): """This record is deemed trustworthy. """ return def get_curate_url(self): return reverse("record-curate", kwargs={"pk": self.pk}) I am now at the point of wanting to connect up some views to activate transition changes for an instance of Record. In the example above, url_path is a hardcoded path to the view whereas I would like to dynamically generate the path value based upon the pk attribute of the parent Record instance. I understand that I can't access self within the decorator, but is there any way for me to get access to an attribute value of the class instance of the decorated curate method? For reference, here is the URL to the django-fsm project: https://github.com/viewflow/django-fsm#custom-properties -
is it possible to access javascript variable in jinja?
How can I access javascript variables in the jinja template? example: <script> let data_str = "video1"; let url = `{% url "renderVideo" args="${data_str}" %}` </script URL: path("videoplay/<str:args>", views.videoplay, name="videoplay") traceback: Internal Server Error: /videoplay/${data_str} I'm expecting /videoplay/video1 but it is not parsing javascript variable, is there any way to do this if you know please let me know. -
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 …