Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to optimize Django autoreload / startup process?
I am currently working on a very large Django project that includes many files and, more importantly, a substantial set of dependencies, including packages like Torch and Transformers. Since installing Torch, I have noticed that the autoreload feature and the entire startup process when using the development server have become very slow. It now takes 10-15 seconds before I can test my code, which is quite frustrating during development. Is there any way to optimize this process, such as telling Django to ignore certain imports or indexing when in DEBUG mode, or any other methods to speed up the autoreload and startup of the Django development server? -
Django Admin TabularInline: How do I hide the object name of a M2M through model?
How do I hide Unit_attribute object (3) from the admin display? admin.py: from django.contrib import admin from core.models import Attribute, Unit class UnitAttributeInline(admin.TabularInline): model = Unit.attributes.through @admin.register(Unit) class UnitAdmin(admin.ModelAdmin): inlines = [UnitAttributeInline] models.py: class Attribute(models.Model): name = models.CharField(max_length=45) class Unit(models.Model): attributes = models.ManyToManyField(Attribute) -
How to create users with different types of fields in django?
how to create models for different types of users with different types of fields in django? Suppose I have 2 users: doctors and nurses, and doctors have a doctor_id, and dept, apart from the fields common between nurses and doctors.How to proceed then? Searched everywhere and scratched my head, can anyone let me know how to approach this? I have tried to write something like this, but it doesnt work. from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): USER_TYPE_CHOICES = ( (1, 'doctor'), (2, 'nurse'), ) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES) class DoctorProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) doctor_id = models.CharField(max_length=6) dept = models.CharField(max_length=255, blank=False, null=False) def __str__(self): return self.user.username class NurseProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) nurse_id = models.CharField(max_length=6) def __str__(self): return self.user.username -
Django Models - trying to get the "best of both worlds" when it comes to copying a model vs subclassing it
Let's say I have a base class (Django model) called Character that looks something like class Character(models.Model): strength = models.blabla dex = models.blabla ... I can set that up with its attributes and hook it up to Admin and everything is lovely. Then I decide I want a NonPlayerCharacter model, which has everything the Character model has, plus a new field or two. I can think of at least two ways to do this, each with pros and cons. Option 1: # The basic obvious stupid-simple answer is just to copy the model and add the fields class NonPlayerCharacter(models.Model): strength = models.blabla dex = models.blabla ... faction = models.blabla Pros: Everything is kept very simple and easy to manage, and if the models need to diverge in the future, that's easy too. Cons: Obvious code duplication and keeping universal changes in sync. If I change a stat or add a method on one, I've got to duplicate it on the other. If I add another type of Character, like Mob, well then it triples the upkeep to keep the necessary parts in sync. Option 2: # The next most obvious solution is to subclass Character class NonPlayerCharacter(Character): faction = models.blabla … -
Django async aadd() not working on ManyRelatedManager models?
Recently I have been developing an app using Django ninja. I want to add Group to user groups, and statement seems have no effect. It does not commit to db. I tried atomic, and all solutions but it does not work. I have db for tests: settings.DATABASES["default"] = { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", "ATOMIC_REQUESTS": False, "TIME_ZONE": "America/Chicago", "CONN_HEALTH_CHECKS": True, "CONN_MAX_AGE": 0, "OPTIONS": {}, "AUTOCOMMIT": True } This is code: group = await cls.repository.get_group_by_name(name) assert group await user.groups.aadd(group) In Django documentation this should work just fine, but it does not. I use AsyncClient from Django to run tests. Any advice ? -
Django Migration Issue With Abstract User
I have created Django application it was working fine at start but now i am facing migration issue with abstract user i remove the migrations files and database from my project and then remigrate it the issue still exist Please any one help me to solve the problem -
Page not found 404 for about
This error is coming .Can someone please help me to come out from that GPage not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/about Using the URLconf defined in Hello.urls, Django tried these URL patterns, in this order: [name='home'] The current path, about, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. code related to that are: from django.shortcuts import render, HttpResponse # Create your views here. def index(request): return HttpResponse("This is Home Page") def about(request): return HttpResponse("This is About Page") from django.contrib import admin from django.urls import path from home import views urlpatterns = [ path("",views.index,name='home'), path("about/",views.about,name='about'), ] from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('home.urls')) ] normal page is working as This is home page.Admin page was also working but now it is also not working. -
Issue with changing name of my heroku app in heroku cli
I can't change name of my heroku app from heroku cli: (ll_env) [arch@archlinux dj_proj]$ heroku apps:rename my_learning_log › ModuleLoadError: [MODULE_NOT_FOUND] require failed to load › /usr/lib/heroku/lib/commands/apps/rename.js: Cannot find module 'tmp' › Require stack: › - /usr/lib/heroku/lib/lib/ci/git.js › - /usr/lib/heroku/lib/commands/apps/rename.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/module-loader.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/help/util.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/help/formatter.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/help/command.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/help/index.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/flags.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/cli-ux/styled/table.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/cli-ux/styled/index.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/cli-ux/index.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/command.js › - /usr/lib/heroku/node_modules/@oclif/core/lib/index.js › - /usr/lib/heroku/node_modules/@heroku-cli/command/lib/command.js › - /usr/lib/heroku/node_modules/@heroku-cli/command/lib/index.js › - /usr/lib/heroku/lib/global_telemetry.js › - /usr/lib/heroku/bin/run › Code: MODULE_NOT_FOUND I also tried change the name of the new name, but it didn't work. -
Issue with Google OAuth Login using Django Allauth - Bland Account Selection UI
I'm working on a Django project where I've integrated Google OAuth login using the django-allauth package. The functionality works in terms of authentication, but I'm encountering an issue with the user interface during the Google account selection process. please do tell me where i've made a mistake ,i'm a student please dont expect me to have good knowledge about django Problem: When users click on the "Sign in with Google" button, they are redirected to a Google page for authentication. However, instead of the usual Google account selection UI (which typically shows account avatars and a modern design), the page appears bland and basic, lacking any styling or proper UI elements. -
what is the best approach to generate sitemap with django rest_framework and nextjs?
I've come across similar questions on Stack Overflow, but none of the solutions worked for me. I'm looking to create an XML sitemap for my website, which has a Django-Rest-Framework backend and a Next.js frontend. I'm considering two options: Generating a sitemap using django-sitemap on the backend and then routing the URL to be displayed in https://mywebsite/sitemap.xml on the Frontend. Fetching the list of all articles and courses from the API, which is paginated with a max limit of 100. This would require multiple calls to the list API to generate the sitemap on the Frontend. I'm unsure about which option is the best choice. Is fetching the list of objects from the API suboptimal? How do large websites like Stack Overflow generate their sitemaps? I'd appreciate any guidance and please let me know if I'm on the wrong track. -
django consistently fails to load css on deployment
I was deploying a simple django application to kubernetes and encountered the error of not being able to load css and js. I have tried several times to change the dockerfile,change the volume path, but I can't fix it. I've spent 1 week still not finding the error, am I overlooking something? Here are my files and code main/settings.py BASE_DIR = Path(__file__).resolve().parent.parent env.read_env(os.path.join(BASE_DIR, 'main/.env')) .... STATIC_URL = '/static/' STATIC_ROOT = '/app/static' Dockerfile # Use the official Python image as the base image ARG ARCH= FROM ${ARCH}python:3.12-slim as builder WORKDIR /app COPY requirements.txt . RUN pip install --default-timeout=100 --no-cache-dir -r requirements.txt COPY . . FROM ${ARCH}python:3.12-slim WORKDIR /app COPY --from=builder /app /app COPY --from=builder /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages COPY --from=builder /usr/local/bin /usr/local/bin EXPOSE 8080 ENV PYTHONUNBUFFERED 1 # Specify the command to run your Django app CMD ["gunicorn", "--workers=3", "--bind=0.0.0.0:8080", "main.wsgi:application" ] deployment.yaml apiVersion: v1 kind: PersistentVolume metadata: name: static-files-pv spec: capacity: storage: 0.5Gi accessModes: - ReadWriteOnce hostPath: path: /mnt/static-files storageClassName: do-block-storage --- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: static-files-pvc spec: accessModes: - ReadWriteOnce resources: requests: storage: 0.5Gi storageClassName: do-block-storage --- apiVersion: v1 kind: ConfigMap metadata: name: auth-db-config data: DB_NAME: auth DB_HOST: patroni.default.svc.cluster.local DB_PORT: "5432" --- apiVersion: v1 kind: Secret metadata: name: auth-db-secret … -
Error initializing boto3 session in Django application using DigitalOcean Spaces
I'm having an issue with my Django application when trying to configure it to use DigitalOcean Spaces for static and media files. Here is the relevant part of my settings.py file: import boto3 from botocore.exceptions import NoCredentialsError, PartialCredentialsError from botocore.client import Config from os import getenv AWS_ACCESS_KEY_ID = getenv('SPACES_KEY') AWS_SECRET_ACCESS_KEY = getenv('SPACES_SECRET') AWS_STORAGE_BUCKET_NAME = getenv('BUCKET_NAME') AWS_S3_REGION_NAME = "region" AWS_S3_ENDPOINT_URL = f"https://{AWS_S3_REGION_NAME}.digitaloceanspaces.com" AWS_S3_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_DEFAULT_ACL = 'public-read' AWS_S3_SIGNATURE_VERSION = 's3v4' STATIC_URL = f"{AWS_S3_ENDPOINT_URL}/{AWS_STORAGE_BUCKET_NAME}/static/" MEDIA_URL = f"{AWS_S3_ENDPOINT_URL}/{AWS_STORAGE_BUCKET_NAME}/media/" STATICFILES_STORAGE = 'name.custom_storages.StaticStorage' DEFAULT_FILE_STORAGE = 'name.custom_storages.MediaStorage' # Ensure the credentials are explicitly set for boto3 session = boto3.session.Session() s3_client = session.client( 's3', region_name=AWS_S3_REGION_NAME, endpoint_url=AWS_S3_ENDPOINT_URL, aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, config=Config(signature_version='s3v4') ) # Test connection to S3 def test_s3_connection(): try: print("Connecting to S3...") response = s3_client.list_objects_v2(Bucket=AWS_STORAGE_BUCKET_NAME) print("Connection successful. Contents:") for obj in response.get('Contents', []): print(obj['Key']) except NoCredentialsError: print("Error: No credentials found.") except PartialCredentialsError: print("Error: Incomplete credentials.") except Exception as e: print(f"Error: {e}") test_s3_connection() When I run the server using python3 manage.py runserver, I get the following error: Traceback (most recent call last): ... File "/Users/User/.aws/credentials" botocore.exceptions.ConfigParseError: Unable to parse config file: /Users/User/.aws/credentials I don't want boto3 to use the credentials from the ~/.aws/credentials file because I'm not using AWS, I'm using DigitalOcean Spaces. Any help … -
authentication method for django rest framework to mitigate XSS and CSRF attacks
I am using django rest framework for my backend and react for my front and they serve in different domain and subdomain and now I am completely confused what should I do for securing my APIs from XSS and CSRF attacks. I wish to use simple-JWT for the application but my research showed that it is vulnerable to XSS. and if I store them in http-only cookies they can't be accessible in front end to add them in authorization header and it would be like using sessions, what should I do? and what is the best practice for securing APIs? I would be glad to hear your suggestions -
How to handle multiform /form data and nested serializer in django rest framework
I have a Tender model and a Product model. There is a foreign key relationship between Tender and product. Now I want to update a tender instance where I provide tender and product data. The data format is multipart/form-data. But every time get the following error { "products": [ "This field is required." ] } I am providing the code so that you guys can understand things properly This is the view class @extend_schema(tags=[OpenApiTags.TMS_TENDER]) class TenderUpdateView(generics.UpdateAPIView): permission_classes = [] queryset = Tender.objects.all() serializer_class = TenderPreSubmissionSerializer lookup_field = "id" parser_classes = [MultiPartParser] def get_queryset(self): id = self.kwargs.get("id") return Tender.objects.filter(id=id) This is the serializer class TenderPreSubmissionSerializer(serializers.ModelSerializer): products = ProductSerializer(many=True) class Meta: model = Tender fields = [ "products", "is_open", "procuring_entity", "ministry", "bg_amount", "bg_attachment", "bg_issue_date", "bg_validity_date", "is_bg_extended", ] def update(self, instance, validated_data): # Extract products data products_data = validated_data.pop("products") # Update tender instance instance = super().update(instance, validated_data) # Create a mapping of existing products by ID existing_products = {product.id: product for product in instance.products.all()} # Update or create products for product_data in products_data: product_id = product_data.get("id") if product_id and product_id in existing_products: # Update existing product product = existing_products.pop(product_id) for attr, value in product_data.items(): setattr(product, attr, value) product.save() else: # Create new product … -
Ready-Made Restaurant Ordering System with POS, Loyalty Programs, Third Party Delivery Integrations
This will probably get taken down but we are in urgent need and I am freaking out and I don't know where else to go for a solution. We urgently need a comprehensive restaurant ordering system, similar to Restoplus, with essential features like restaurant login/signup, customizable menus with item variations, a POS interface, and access to sales data. The system must support both in-store pickup and dine-in notifications via SMS, as well as integrate with delivery services like Uber/DoorDash. Additionally, it should include a robust rewards system for users, allowing them to earn points with purchases and redeem them, similar to major fast-food chains' loyalty program. Instant receipt printing and order processing capabilities, mirroring the efficiency of modern restaurant system. We are looking to purchase a ready-made solution immediately, with a strong preference for off-the-shelf systems to meet our critical timeline. We need at least a partial deployment within the next 2 days. If you have an existing solution that fits these requirements, please contact us ASAP. Speed is of the essence in this project. We are looking for a ready-made solution that can be deployed immediately, with at least partial functionality within the next 2 days. The system must … -
Running Django on Google Colab: Error 204 Forbidden
I am trying to do some tests on Colab of my Python program and to use Django. I followed the instructions from this link . I made sure this is set in settings.py ALLOWED_HOSTS = ['*'] Ran this to get the link https://randomstrings.colab.googleusercontent.com/ from google.colab.output import eval_js print(eval_js("google.colab.kernel.proxyPort(8000)")) And then !python manage.py runserver 8000 which gave me a successful output, System check identified no issues (0 silenced). July 28, 2024 - 05:49:17 Django version 5.0.7, using settings 'test.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. However when opening the link https://randomstrings.colab.googleusercontent.com/ printed above, I get a 403. That's an error page. Is there any other settings that I have to do or steps that I missed? -
Country field not being populated on sign up in Django
When the user signs up, I want to add their country to their profile. But, the field remains blank in the database and doesn't get populated with the country. I am new to authentication in Django, so it may be wrong in other ways.I think the order may be the problem? I am really unsure. Views.py def get_country(ip): if ip in ['127.0.0.1', 'localhost', '::1']: return 'Localhost' # Perform GeoIP lookup g = GeoIP2() try: result = g.city(ip) country = result["country_name"] except Exception as e: print(f'Error: {e}') country = "Unknown" return country def signup_view(request): if request.method == 'POST': form = UserCreateForm(request.POST) if form.is_valid(): user = form.save() # Get the user's IP address x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0].strip() else: ip = request.META.get('REMOTE_ADDR') # Determine the user's country country = get_country(ip) # Create the profile with the country information username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') Profile.objects.create(user=user, country=country) user = authenticate(username=username, password=raw_password) login(request, user) return redirect('/') else: form = UserCreateForm() return render(request, 'signup.html', {'form': form}) models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField( default='profile_pics/default.jpg', upload_to='profile_pics') country = models.CharField(max_length=100) def __str__(self): return f'{self.user.username} Profile' … -
Google Picker API giving Null user before completing authorization
I am using the google picker api example code from https://developers.google.com/drive/picker/guides/sample and when I tried authenticating with google, it always gives me back a null access token before I even complete the authorization part. Here is the following code I used for authorizing: let tokenClient; let accessToken = null; let pickerInited = false; let gisInited = false; document.getElementById('authorize_button').style.visibility = 'hidden'; document.getElementById('signout_button').style.visibility = 'hidden'; /** * Callback after api.js is loaded. */ function gapiLoaded() { gapi.load('client:picker', initializePicker); } /** * Callback after the API client is loaded. Loads the * discovery doc to initialize the API. */ async function initializePicker() { await gapi.client.load('https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'); pickerInited = true; maybeEnableButtons(); } /** * Callback after Google Identity Services are loaded. */ function gisLoaded() { tokenClient = google.accounts.oauth2.initTokenClient({ client_id: CLIENT_ID, scope: SCOPES, callback: '', // defined later }); gisInited = true; maybeEnableButtons(); } /** * Enables user interaction after all libraries are loaded. */ function maybeEnableButtons() { if (pickerInited && gisInited) { document.getElementById('authorize_button').style.visibility = 'visible'; } } /** * Sign in the user upon button click. **/ function handleAuthClick() { tokenClient.callback = async (response) => { if (response.error !== undefined) { throw (response); } accessToken = response.access_token; document.getElementById('signout_button').style.visibility = 'visible'; document.getElementById('authorize_button').innerText = 'Refresh'; await createPicker(); … -
Building a Dynamic Quest and Badge Evaluation System in Django
Models Quest class Quest(models.Model): name = models.CharField(max_length=255) description = models.TextField(blank=True) criteria = models.JSONField() # Store criteria as JSON reward_points = models.IntegerField(default=0) def __str__(self): return self.name Badge class Badge(models.Model): name = models.CharField(max_length=255) description = models.TextField(blank=True) criteria = models.JSONField() # Store criteria as JSON reward_points = models.IntegerField(default=0) def __str__(self): return self.name UserQuestProgress class UserQuestProgress(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) quest = models.ForeignKey(Quest, on_delete=models.CASCADE) current_value = models.IntegerField(default=0) target_value = models.IntegerField() completed = models.BooleanField(default=False) completed_at = models.DateTimeField(null=True, blank=True) def save(self, *args, **kwargs): if self.current_value >= self.target_value: self.completed = True if not self.completed_at: self.completed_at = timezone.now() super().save(*args, **kwargs) UserBadgeProgress class UserBadgeProgress(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) badge = models.ForeignKey(Badge, on_delete=models.CASCADE) current_value = models.IntegerField(default=0) target_value = models.IntegerField() completed = models.BooleanField(default=False) completed_at = models.DateTimeField(null=True, blank=True) def save(self, *args, **kwargs): if self.current_value >= self.target_value: self.completed = True if not self.completed_at: self.completed_at = timezone.now() super().save(*args, **kwargs) I'm working on a social media platform where users can earn rewards (quests and badges) based on their activities. My goal is to create a flexible system that can evaluate these rewards dynamically, without needing to hardcode new conditions every time we introduce a new quest or badge. What We Have Done So Far: Models for Quests and Badges: We have defined models for Quest, … -
Static Files Not Loading in Production with Django and Docker
I'm running a Django application in a Docker container, and I'm having trouble serving static files in production. Everything works fine locally, but when I deploy to production, the static files don't load, and I get 404 errors. Here are the relevant parts of my setup: Django settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], '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', ], }, }, ] STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = '/vol/web/static' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'build', 'static')] After running collectstatic, the volume /vol/web/static is correctly populated. However, the browser shows 404 errors for the static files, e.g., GET https://www.aloconcursos.com/static/js/main.db771bdd.js [HTTP/2 404 161ms] GET https://www.aloconcursos.com/static/css/main.4b763604.css [HTTP/2 404 160ms] Loading failed for the <script> with source “https://www.aloconcursos.com/static/js/main.db771bdd.js”. These files exist in the build/static directory, but I thought the browser should use the static files collected into /vol/web/static. Nginx Configuration: server { listen ${LISTEN_PORT}; location /static { alias /vol/static; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } Dockerfile: FROM python:3.9-alpine ENV PYTHONUNBUFFERED 1 ENV PATH="/scripts:${PATH}" RUN pip install --upgrade "pip<24.1" COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache postgresql-client jpeg-dev \ && apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev … -
'SignInForm' object has no attribute 'request'
I'm trining to set remember_me in forms.py insted of views.py via def clean_remember_me. but it dosn't work and give me error ! remember_me = forms.BooleanField(widget=forms.CheckboxInput(),label=_('Remember me'), required=False) def clean_remember_me(self): remember_me = self.cleaned_data['remember_me'] if not remember_me: self.request.session.set_expiry(0) -
can I use the slug from a different urls.py file?
I'm trying to access a slug field from a different urls.py file, and I'm getting this error FieldError at /new-api/tournaments/fifa-world-cup/teams/ Unsupported lookup 'custom_url' for ForeignKey or join on the field not permitted. I'm wondering if the reason I'm getting this error is because you cant do that or if it's another reason I have 2 files for urls, one includes the other in it, urls.py (tournament) urlpatterns = [ path("", views.getNewTournaments, name="tournaments"), path("<slug:custom_url>/", views.getNewTournament, name="tournament"), path("create/", views.postNewTournament, name="post-tournament"), path("<slug:custom_url>/teams/", include("teams.urls"), name="tournament-teams"), ] urls.py (teams) urlpatterns = [ path("", views.teams.as_view(), name="teams"), ] Here are the views.py files views.py (tournaments) @api_view(["GET"]) def getNewTournaments(request): tournaments = NewTournament.objects.all() serializer = NewTournamentSerializer(tournaments, many=True) return Response(serializer.data) views.py (teams) class teams(APIView): def get(self, request, custom_url): teams = Team.objects.filter(tournament__custom_url=custom_url) serializer = TeamSerializer(teams, many=True) return Response(serializer.data) -
Django JWT authentication TokenObtainPairView issue
I am trying to use CustomTokenObtainPairView to receive my username in token. #views: `if user.check_password(password): # refresh = RefreshToken.for_user(user) # refresh.access_token['username'] = user.username # token = str(refresh.access_token) request.data = { 'username': username, 'password': password } token_response = CustomTokenObtainPairView.post(request=request.data) response = Response() response.set_cookie(key='jwt', value=token_response.data['access'], httponly=True, secure=True) response.data = { 'access': token_response.data['access'] } return response else: return Response({'message': 'Wrong password!'}, status=400)` I tried to generate token and adding username in it but it didnot work. If anybody knows how to use TokenObtainPairView in correct way in your function please help. -
How to properly assign a value to a Django choice field
I am trying to assign a value to a ChoiceField in a Django form. # forms.py MONTH_CHOICES = ( ("JANUARY", "January"), ("FEBRUARY", "February"), #... ("DECEMBER", "December"), ) class SomeMonthSelectingform(forms.Form): month = forms.ChoiceField(choices=MONTH_CHOICES) def __init__(self, *args, **kwargs): month = kwargs.pop("month") super(SomeMonthSelectingform, self).__init__(*args, **kwargs) self.fields['month'] = month The selected value of the choice field named month should be the actual month (e.g. right now it would be 'JULY') # views.py def month_view(request: HttpRequest): month = datetime.now().month monthIndex = month - 1 monthChoice = MONTH_CHOICES[monthIndex][0] monthForm = SomeMonthSelectingform(month=monthChoice) if request.method == 'POST': filledForm = SomeMonthSelectingform(data=request.POST) if not filledForm.is_valid(): raise Exception("Month form was invalid") monthForm = filledForm args = { 'monthForm': monthForm } return render(request, 'month.html', 'args') <!-- month.html --> {% extends 'base.html' %} {% block content %} <h2>Month</h2> <form action="{% url '...' %}" method="post"> {% csrf_token %} {{ monthForm }} <input type="submit" name="..." value="Show"> </form> {% endblock %} Sadly, I keep getting the error 'str' object has no attribute 'get_bound_field'. I am quite sure it is because, I should not assign 'JULY' to self.fields['month'] inside the constructor of the form. But I can not find another solution. -
How To Redirect In Post Request Response
i wanna redirect to success page but it seems i should use different way in post request response. views.py : def uploader(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): return redirect("download",link = 'test') else: form = UploadFileForm() return render(request, 'uploader/pages/upload.html', {'form': form}) def downloader(request,link) : return render(request, 'uploader/pages/download.html',) urls.py : urlpatterns = [ re_path(r'^admin/', admin.site.urls), re_path(r'^$', views.uploader, name='upload'), re_path(r'^(?P<link>[\w-]+)/', views.downloader, name='download'), ] log in terminal : [27/Jul/2024 17:43:37] "POST / HTTP/1.1" 302 0 [27/Jul/2024 17:43:37] "GET /test/ HTTP/1.1" 200 46 I've tried HttpResponseRedirect('test') and HttpResponseRedirect(reverse('download', kwargs={'link': 'link'})) to