Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Join request in django between three tables and display all attributes
I have three models class A(models.Model): field1 = models.IntegerField() class B(models.Model): id_a = models.ForeignKey(A,on_delete=models.CASCADE) field1 = models.IntegerField() field2 = models.IntegerField() class C(models.Model): id_a = models.ForeignKey(A,on_delete=models.CASCADE) field1 = models.IntegerField() field2 = models.IntegerField() I want to write a request that looks like this: SELECT * FROM B,C,A WHERE B.id_a=C.id_a WHERE A.id_a=2 and display all the attributes of the two tablesHere is what I tried to do: a_id_att = 1 data = B.objects.filter(id_a=C.objects.filter(id_a=a_id_att)[0]) It does not work. How to write the join and make to display all the attributes of the tables? -
How to use patch with (from django.views.generic import View)
What patch method do I use while creating an API with the View , (from django.views.generic import View) Suppose I have a class like this : from django.views.generic import View class ArticleView(View): def patch(self, request, article_id, *args, **kwargs): # How can I patch data here pass def get(self, request, *args, **kwargs): pass def put(self, request, *args, **kwargs): pass -
how to update / replace a file in a Django FileField()
I have a Django model that holds a file like so: class Excel(models.Model): the_generated_file = models.FileField() I know want to access this file with an updated version of the file. If this was a int, foat or Json field etc I could use something like: File_to_update = Excel.objects.all() File_to_update.update(the_generated_file = my_new_excel_previously_defined) But for some reason as it is of type FiledField() there is no update operation. How can I replace the old file with a new file? -
Django how to get 0 instead of null
I'm filtering a query set to get the number of visitors and pageviews but when there is no data it returns None. How to get 0 instead of None when filtering a queryset when there is no data? yesterday_visitors = queryset.filter(date__gte=yesterday, page=None).aggregate(Sum('visitors')) yesterday_page_views = queryset.filter(date__gte=yesterday, page=None).aggregate(Sum('page_views')) -
How to register specific column(field) in models.py file in admin
this is my model i like to register field 'tag' in admin.py file class Content(models.Model): id=models.AutoField(primary_key=True) user=models.ForeignKey(User,on_delete=models.CASCADE) content_type = models.CharField(max_length=255) # show=models.CharField(max_length=255) show=models.ForeignKey(Show,on_delete=models.CASCADE) sponsor_link=models.CharField(max_length=255) status=models.BooleanField(default=False) added_on=models.DateTimeField(null=True) content_file=models.FileField(upload_to='media/') title = models.CharField(max_length=255) shows_name = models.CharField(max_length=255) subtitle = models.CharField(max_length=255) description = models.CharField(max_length=500) publish_now = models.BooleanField(default=False) schedule_release = models.DateField(null=True) expiration = models.DateField(null=True) tag = models.CharField(max_length=255) category = models.CharField(max_length=255) topic = models.CharField(max_length=255) def __str__(self): return self.title I've used tagset = Content.objects.all() def content_register(): for a in tagset: admin.site.register(a.tag) content_register() But i get this error AttributeError: 'str' object has no attribute '_meta' can anyone help me here -
how to get username form django session
i am trying to get user name from session by using request.user but i am getting AnonymousUser, how do i get user name def login_two(request): if request.method == 'POST': uname = request.POST.get('name2') pwd = request.POST.get('password2') check_user = User.objects.filter(username=uname, password=pwd) if check_user: request.session['user'] = uname return redirect('index') return render(request, 'login2.html') models.py class User(models.Model): username = models.CharField(max_length=30) password = models.CharField(max_length=50) -
Why django migrations crashes using collections instead typing?
I have a class in models: class UserFilters(typing.NamedTuple): enabled_exchanges: typing.Optional[list[Exchange]] = None enabled_coins: typing.Optional[list[Coin]] = None enabled_fiats: typing.Optional[list[Fiat]] = None enabled_paymethods: typing.Optional[list[Paymethod]] = None consider_volumes: typing.Optional[bool] = None consider_vendor_rating: typing.Optional[bool] = None I run: python3 manage.py makemigrations Seems good But when I run: python3 manage.py migrate Output is: Traceback (most recent call last): File "/Users/lifr0m/PycharmProjects/p2p/manage.py", line 22, in <module> main() File "/Users/lifr0m/PycharmProjects/p2p/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py", line 88, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/loader.py", line 214, in build_graph self.load_disk() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/loader.py", line 116, in load_disk migration_module = import_module(migration_path) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Users/lifr0m/PycharmProjects/p2p/authentication/migrations/0002_auto_20211213_1118.py", line 7, in <module> … -
Django, DRF, nginx, Jmeter: Sample Time becomes large even though there is no load on the CPU, etc
I am using Jmeter to load test the DRF, and even though the CPU and memory are not at 100%, the throughput and response time is slow. The Django + nginx and Postgres servers are separated, and both have the following specs 4CPU, 4GB memory. nginx is using docker's https-portal as shown below. version: "3" services: https-portal: image: steveltn/https-portal:1 ports: - "80:80" - "443:443" environment: DOMAINS: "my.domain.com -> http://backend:8000" STAGE: "production" volumes: - https-portal-data:/var/lib/https-portal - ./nginx/uwsgi_params:/etc/nginx/uwsgi_params - ./static:/static depends_on: - backend restart: always backend: build: . command: uwsgi --http :8000 --module privatine.wsgi --processes 4 volumes: - .:/usr/src/app - ./static:/usr/src/app/static expose: - 8000 env_file: - .env - .env.prod restart: always volumes: https-portal-data: Looking at the django logs, there doesn't seem to be anything wrong with django, what do you think could be causing this? generated 8302 bytes in 29 msecs (HTTP/1.0 200) 7 headers in 208 bytes (1 switches on core 0) Setting up Jmeter: Django + nginx server: DB(postgres) server: After 5 minutes of continuous loading. If there is any other information you need, please let me know. -
What's the correct way to use helpers to extend functionality in Django models?
I'm adding some extended functionallity to my models in Django. In order to not overload the model root interface (and file), i'm using some helpers as attributes of the model. What i want is to group the methods and properties into this helpers, and what i want is something like: class Product(models.Model): downloads = DownloadsHelper() # .... pass p = Product.objects.first() p.downloads.files_count(p) p.downloads.reset_permissions(p) # ... In order to not to have to pass the instance to the helper each time, I could use another approach. class Product(models.Model): def __init__(self, *args, **kwargs): super(Product, self).__init__(*args, **kwargs) self.downloads = DownloadsHelper(self) self.shipping = ShippingHelper(self) p = Product.objects.first() p.downloads.files_count p.downloads.reset_permissions() And finally, a more python-generic/conceptual way to do this stuff would be like: class Helper: def __init__(self, helped): self.helped = helped class Helper1(Helper): attribute_name = 'helloing' def hola(self): print("hola") class Helper2(Helper): attribute_name = 'goodbying' def chau(self): print("chau") class Helped: def __init__(self): self._install_helpers() def _install_helpers(self): for helper in self.helpers: setattr(self, helper.attribute_name, helper(self)) class MyHelped(Helped): helpers = [Helper1, Helper2] h = MyHelped() h.helloing.hola() h.goodbying.chau() And the question is: Is this last approach a correct way /good practice to do the stuff from a pythonic-OOP and "Djangoid" point of view. Has this any problem? Thanks for reading! -
Test database for Django + Heroku. Error creating the test database: permission denied to create database
I'm trying to run the tests for my Django project. I wrote this project some time ago, I had different settings then and tests were passing. Now I changed settings and deployed it on Heroku with Heroku Postgres database. Everything works fine already except I can't run tests. I've tried many different settings and nothing worked. Most of the time I'm getting this error: permission denied to create database My last setting is following the instruction from this article on medium Basically I have added 2nd Heroku Postgres database, add settings like below (but with valid variables of my heroku databases): if 'test' in sys.argv: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'd7osdssadag0ugv5', 'USER': 'lhwwasadqlgjra', 'PASSWORD': '1524f48a2ce41177c4ssdadasd3a11680b735302d14979d312ff36', 'HOST': 'ec2-54-75-2326-118.eu-west-1.compute.amazonaws.com', 'PORT': 5432, 'TEST': { 'NAME': 'd7osdssadag0ugv5', } } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'd7hasadas9hqts5', 'USER': 'nybkduadsdgqot', 'PASSWORD': 'bb535b9cdsfsdfdsfdsfac54851f267444dd8cc230b2a786ab9f446', 'HOST': 'ec2-54-247-132-38.eu-west-1.compute.amazonaws.com', 'PORT': 5432, 'TEST': { 'NAME': 'd7hasadas9hqts5', } } } Then run python manage.py test --keepdb in my venv. Then I get an error: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable … -
Passing Django variable to an accordion attribute in HTML
I am newbie to Django and apologize in advance for such a basic question to most of you, but I looked for similar questions all over and haven't encountered a workable solution. I am trying to create a Bootstrap Accordion for each item of a Django for-loop. So a list of items is displayed, and when you click on one item, the description of it will collapse to show. The segment currently looks like this using this template: <head> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </head> <body> {% for item in items %} <div class="accordion" id="accordionExample"> <div class="accordion-item"> <h2 class="accordion-header" id="headingOne"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-parent="#accordion" data-bs-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne"> {{ item }} </button> </h2> <div id="collapseOne" class="accordion-collapse collapse" aria-labelledby="headingOne" data-bs-parent="#accordionExample"> <div class="accordion-body"> {{ item.description }} </div> </div> </div> </div> </body> Now, this is giving the same value (collapseOne) to data-bs-toggle, aria-controls and id of accordion-collapseclass(collapsing element) for every for-loop item, resulting in all the accordion items collapsing when one of them is clicked though I want only the clicked one to collapse. So I tried to pass the Django variable as such: {{ item }} in place of collapseOne {{ forloop.counter }} in place of collapseOne The … -
db.sqlite3 continues working after having been deleted
I recently deleted my db.sqlite3 file because some data had become corrupted. I though that at the next run of python manage.py migrate it would have simply been recreated from stratch. Instead, Django is contuining to work off the old db.sqlite3 despite the file not existing anymore - I assume it's somehow cached? Specifically: python manage.py migrate works fine but it doesn't create a new db.sqlite3 file. There is no db.sqlite3 file anymore in my root. I already manually deleted all migrations. The app continues to work okay with all the previous data still there (e.g., users). In case it's useful, I'm coding on Replit. -
Is it impossible upload file in the different region from the region of s3 bucket? (IllegalLocationConstraintException)
I deployed my django project using AWS Elastic beanstalk and S3, and I tried to upload the profile avatar but it shows Server Error(500) My Sentry log shows me, "An error occurred (IllegalLocationConstraintException) when calling the PutObject operation: The eu-south-1 location constraint is incompatible for the region specific endpoint this request was sent to." I think this error appeared because I put my bucket on eu-south-1 but I try to access it and to create a new object in Seoul, Korea. Also, the AWS document said IllegalLocationConstraintException indicates that you are trying to access a bucket from a different Region than where the bucket exists. To avoid this error, use the --region option. For example: aws s3 cp awsexample.txt s3://testbucket/ --region ap-east-1. (https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html) but this solution might be just for when upload a file from AWS CLI... I tried to change my bucket policy by adding this but doesn't work. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "s3:PutObject", "Resource": "arn:aws:s3:::{BucketName}/*" } ] } I don't know what should I do and why they do not allow access from other regions? How to allow access to create, update and remove an object in my bucket from all … -
Login works in Django Rest Framework but not on frontend
I have the following views: login_view: @api_view(['POST']) def login_view(request): try: user_data = request.data username = user_data["username"] password = user_data["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) serializer = UserSerializer(user) return Response( { "user":serializer.data, "login": True }) else: return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST) except: raise Http404 logout_view: @api_view(['POST']) def logout_view(request): if request.user.is_authenticated: logout(request) return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_403_FORBIDDEN) and fetch function on frontend: const onSubmit = () => { fetch('http://127.0.0.1:8000/api/login/',{ method:"POST", headers: { 'Accept': 'application/json, text/plain', 'Content-Type': 'application/json; charset=UTF-8' }, body: JSON.stringify({ "username": values.Username, "password": values.Password }) }).then((response) => {response.json().then(data => { if(response.ok){ setError(''); console.log(data); } else{ setError(''); setError('Invalid Username or Password'); } })}); }; and the following problem: When I try to sign in on frontend I get an expected response: { user: {id: 4, username: 'Tester_1', date_joined: '2021-12-02T22:38:29.323393Z', trust_index: 0} login: true } but my user is not logged in Rest Framework and I can't use logout view on Frontend: After login on Frontend When I use Rest Framework panel for login, everything works fine, user is logged in and I can use logout view: After login in Rest Framework I've been struggling with this for a while. Any ideas how to solve this problem? -
Django unittest unique constraint failed for no reason
My problem is that when im creating users in unittest, it shows me UNIQUE CONSTRAINT FAILED. In this scenario, It's happening when Im creating user in setUp I have no idea what the problem is, especially that credentials are different for both users in both tests. When im not creating user in setUp it actually works with same credentials from picture above Also it throws me CONSTRAINT error in scenario when I want to create user with same credentials but in different test: I cant also create 2 users with same credentials in 2 different tests. I have absolutely no idea why this is happening. Especially that I've been doing same thing in different project and everything worked. Here is my user model: Please help me out, I am out of ideas why this might be happening. -
take screenshot of a website and return token screenshot for download in django?
i want to take a screenshot from a website and return token screenshot as https for download. I am using Html2Image lib. i am tring this code: def certification1(request, *args, **kwargs): hti = Html2Image() image = hti.screenshot(url='https://www.python.org', save_as='screenshot.png') response = HttpResponse(image, content_type='png') return response but it return url of saved image. like this how can i return token image for download? -
How to handle multiple ModelForm with CreateView (class based views) in Django
I have three models GalleryAlbum, GalleryImage and GalleryVideo. These models have their corresponding ModelForm. I want to handle these forms with a single CreateView model in views.py. Models GalleryImage and GalleryVideohave one-to-many relations with model GalleryAlbum models.py from django.db import models INSTITUTE_CHOICES = [ ("SC", "Shrinathji College"), ("SS", "Shrinathji School"), ] class GalleryAlbum(models.Model): title = models.CharField(max_length=255) date = models.DateField() thumbnail = models.ImageField( upload_to="gallery", default="gallery-album-default.jpg" ) institute = models.CharField(max_length=5, choices=INSTITUTE_CHOICES) def __str__(self): return self.title class GellaryImage(models.Model): album = models.ForeignKey( GalleryAlbum, on_delete=models.CASCADE, related_name="images" ) image = models.ImageField() class GellaryVideo(models.Model): album = models.ForeignKey( GalleryAlbum, on_delete=models.CASCADE, related_name="videos" ) url = models.URLField() forms.py from django import forms from django.forms.fields import DateField from django.forms.widgets import DateInput from gallery.models import GalleryAlbum, GellaryImage, GellaryVideo class GalleryAlbumForm(forms.ModelForm): created = DateField( input_formats=["%Y-%m-%d"], widget=DateInput(attrs={"type": "date"}), ) class Meta: model = GalleryAlbum fields = "__all__" def __init__(self, *args, **kwargs): super(GalleryAlbumForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs["class"] = "form-control" class GalleryImageForm(forms.ModelForm): class Meta: model = GellaryImage fields = "__all__" def __init__(self, *args, **kwargs): super(GalleryImageForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs["class"] = "form-control" class GalleryVideoForm(forms.ModelForm): class Meta: model = GellaryVideo fields = "__all__" def __init__(self, *args, **kwargs): super(GalleryVideoForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs["class"] = "form-control" views.py from django.urls import reverse_lazy … -
Avoid overwriting of cell in excel using python
I run my python file everyday, and each day when I run it it overwrites old previous rows and columns of 'daily.xlsx' excel file. It needs to continue where the last row stopped at. In excel file has 8 columns. (numbers, text, user_id,username,first_name,last_name,date,work). So, 'numbers' column's last number needs to be continued when I run python file. import telebot import openpyxl as xl API_TOKEN = '1111111111:BBBBBBBBBBBBBBBBAAAAAAAAAA-CCCCCCCC' bot = telebot.TeleBot(API_TOKEN) counter = 1 wbAll = xl.load_workbook('C:/Users/Administrator/PycharmProjects/TelegramBot/ActivationKey/daily.xlsx') sheetAll = wbAll['Sheet1'] wbActivation = xl.load_workbook( 'C:/Users/Administrator/PycharmProjects/TelegramBot/ActivationKey/activationKey.xlsx') sheetActivation = wbActivation['Лист1'] # Handle '/start' @bot.message_handler(content_types=['text']) def send_welcome(message): if (message.text[:4] == 'DGGA' or message.text[:4] == "KLAT") and message.text[4:6] == "03" and len( message.text) == 16 and message.text[7] == "1": global counter k = 0 # sending Activation code for i in range(1, sheetActivation.max_row + 1): if message.text == sheetActivation.cell(i, 1).value: print("Activation code place: {}".format(i)) bot.send_message(message.chat.id, sheetActivation.cell(i, 2).value) k += 1 print( "There is a key\tText: {}\tUsername ID: {}\tUsername: {}\tFirstName: {}\tLastname: {}".format( message.text, message.chat.id, message.chat.username, message.chat.first_name, message.chat.last_name)) print(counter) # for Daily report sheetAll.cell(counter, 1).value = counter sheetAll.cell(counter, 2).value = message.text sheetAll.cell(counter, 3).value = message.chat.id sheetAll.cell(counter, 4).value = message.chat.username sheetAll.cell(counter, 5).value = message.chat.first_name sheetAll.cell(counter, 6).value = message.chat.last_name wbAll.save('C:/Users/Administrator/PycharmProjects/TelegramBot/ActivationKey/daily.xlsx') counter += 1 if k == 0: print( "There is no … -
pagination in POST request in django rest api
in one of my django (rest api) project i have one requirement in which mobile team is passing some keys and data including page number through post request, according to that i need to return listing via pagination of their need. i know how to achieve above operation via GET request, but can not use it as mobile team will be passing very lengthy data, which will not be suitable for GET request Here is my code how do i do it via get request: from rest_framework.pagination import PageNumberPagination paginator = PageNumberPagination() paginator.page_size = 10 result_page = paginator.paginate_queryset(songs, request) if result_page is not None: songs_data = [] next = paginator.page.next_page_number() if paginator.page.has_next() else None previous = paginator.page.previous_page_number() if paginator.page.has_previous() else None for item in result_page: # required operation if anyone can help me how do i do it using page number received from the body of POST request, will be appreciated -
xhtml2pdf fonts for latin characters to renders pdf template
I am rendering pdf template dynamically using xhtml2pdf library in Django. The problem is with softening marks like ā, š, ķ etc. I have tried to use all suggested fonts from documentation. I can get fonts but not this softened characters. it looks like preview of pdf from django.template.loader import get_template from xhtml2pdf import pisa from io import BytesIO def quote_preview_pdf(request, pk, pk2): # subscription = stripeInfo(request) user = request.user user_company = UserCompany.objects.get(company_user=user) client_company = user.clientcompanies_set.get(id=pk) quote_nr = user_company.quotenumber_set.get(id=pk2) quote_nr = user_company.quotenumber_set.get(id=pk2) get_quoted_products = CompaniesQuote.objects.filter(quote_nr = quote_nr) get_only_quoted_products = CompaniesQuote.objects.filter(quote_nr = quote_nr).values_list('item__id', flat=True) calc_totals = get_only_quoted_products.annotate( calc_total_profit=(F('item__selling_price') * (1 - (F('discount') / 100)) * F('quantity')) - (F('item__buying_price') * F('quantity')), calc_total_sales_price = (F('item__selling_price') * F('quantity')), calc_total_sales_price_disc = (F('item__selling_price') * (1 - (F('discount') / 100)) * F('quantity')), calc_total_sales_price_vat = (F('item__selling_price') * ( 1 + (F('item__vat') / 100)) * F('quantity')), calc_total_sales_price_vat_disc = (F('item__selling_price')* (1 - (F('discount') / 100)) * ( 1 + (F('item__vat') / 100)) * F('quantity')), calc_total_vat = (F('item__selling_price')* (1 - (F('discount') / 100)) * ( 1 + (F('item__vat') / 100)) * F('quantity')) - (F('item__selling_price') * (1 - (F('discount') / 100)) * F('quantity')) ).aggregate( thesum=Sum('calc_total_profit'), sumsalles=Sum('calc_total_sales_price'), sumsallesdiscount=Sum('calc_total_sales_price_disc'), sumsallesvat=Sum('calc_total_sales_price_vat'), sumsallesvatdiscount=Sum('calc_total_sales_price_vat_disc'), sumvattotal = Sum('calc_total_vat'), ) template_path = 'quote_preview_pdf.html' context = { 'user_company': user_company, 'client_company': … -
Is there any way to set lifetime of refresh token to infinite in django-rest-framework-simplejwt?
I am using django-rest-framework-simplejwt for authentication for my Django project. I have done some research but could not find a solution for that. In the documentation, the format to set refresh token is in time delta. Is it possible to set the refresh token to not expire at all? -
How to escape HTML tags in NextJS
I have Django backend and Nextjs frontend. When I try to render content = models.TextField() from my Django backend to Nextjs frontend <p>{data.content}</p> , I get following rendered: <p>first&nbsp;first&nbs</p> I use django_summernote as the editor. Django has | safe method, that escapes rendering HTML, but I don't know what to use for NextJS. Any help is appreciated -
Django queryset filtering, comparing fields with fields
I would like to filter a queryset where the homecountry is the same as the residentcountry. I try to do something like this: users = User.objects.filter(homecountry=residentcountry) How can I make this work? -
How to add users with username using mozilla-django-oidc to auth_user table upon SSO login?
I'm using mozilla-django-oidc for SSO login with one of my django application. When each user logs in to the application using SSO, then the user is added to the auth_user table of postgres database(if the user is not already saved). The username column of the auth_user table is filled with the hash value of the email id. How can we save the actual value of the email id in the auth_user table instead of the hash value? A direction to achieve this is mentioned here in the official documentation page. -
How to display a ChoiceField's text through Django template to a user?
models.py: class Person(models.Model): title=models.CharField(max_length=11) name=models.CharField(max_length=100) gender=models.CharField(max_length=11) forms.py: class PersonForm(ModelForm): GENDER_SELECT = ( ('f', 'Female'), ('m', 'Male'), ('o', 'Other'), ) TITLE_SELECT = ( ('0', 'Mr.'), ('1', 'Mrs.'), ('2', 'Ms.'), ('3', 'Mast.'), ) title=forms.CharField(widget=forms.RadioSelect(choices=TITLE_SELECT, attrs={'class': 'form-check-inline'})) gender=forms.CharField(widget=forms.RadioSelect(choices=GENDER_SELECT, attrs={'class': 'form-check-inline'})) class Meta: model=Person fields='__all__' Now, below are the two ways that I tried to get the data-output to the web-page through but the first one returns nothing and the second one returns the database value of the choice, rather than the text that the user selected. I want the user to see Mr. or Mrs. or Ms. or Mast. and not 0/1/2/3. What is wrong here? template: 1 {% for rp in report %} <td class="design">{% if rp.title == 0 %} Mr. {% elif rp.title == 1 %} Mrs. {% elif rp.title == 2 %} Ms. {% elif rp.title == 3 %} Mast. {% endif %}</td> {% endfor %} 2 {% for rp in report %} <td class="design">{{rp.title}}</td> {% endfor %}