Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add Bearer {JWT} in swagger django?
when I authorize myself in Swagger UI, I have to write "Bearer {then I write JWT} here" How can I add the string "Bearer" automatically before the JWT token in swagger UI? Here is my Swagger Settings: SWAGGER_SETTINGS = { "SECURITY_DEFINITIONS": { "JWT [Bearer {JWT}]": { "name": "Authorization", "type": "apiKey", "in": "header", } }, "USE_SESSION_AUTH": False, } FORCE_SCRIPT_NAME = "/" -
Django: user visits package selection
What is the difference between the following packages: django-visits 0.1.6 (released on Jun 16,2014) and django-user-visit 0.5.1 (released on Sep 29, 2021)? If I simply want to record the number of all visitors in my django application, should I use the latest package django-user-visit? Also, which of the above packages (if any) can also record anonymous visitors in addition to logged users? -
How to django orm object to pydantic list object
i'm using django channels and pydantic how to this django orm object to pydantic response class ExchangeRateSchema(BaseSchema): currency: str sales_rate: str fix_time: datetime created_at: datetime @validator("currency") def validate_currency(cls, v): return v.split()[0] @validator("fix_time") def validate_fix_time(cls, v): return v.strftime("%Y.%m.%d %H:%M") # query_set list(ExchangeRate.objects.filter(*args, **kwargs)) How to this ExchangeRateSchema to list data [ { "currency": "USA1", "sales_rate": "1150.40", "fix_time": "2022.05.06 08:54", "created_at": "2022-05-06T08:55:07.998Z" }, { "currency": "USA2", "sales_rate": "1150.40", "fix_time": "2022.05.06 08:54", "created_at": "2022-05-06T08:55:07.998Z" } ] other using code ExchangeRateSchema ExchangeRate.objects.filter(*args, **kwargs).latest(latest) ExchangeRateSchema(**exchange.dict) { "currency": "USA", "sales_rate": "1150.40", "fix_time": "2022.05.06 08:54", "created_at": "2022-05-06T08:55:07.998Z" } -
How can I make add-to-cart fuctionality in django easily?
How can I make add-to-cart fuctionality in django easily? Hello friends, Currently I'm working on a django ecommerce project. I want users to add items in their shopping cart and then checkout to buy the products but I'm so confused how can I make it easily with only backend (no javascript ). Is it possible? I want my project not to be so much complex. So please tell me how to give add-to-cart funtionality to a django project without javascript and without complexity. please provide me helpful tutorial links for making cart system in django. Thank You! -
Django related_name import object instead of foreigne_key
When I importing my CSV file in db.sqlite3, I don't know how to import foreign_key instead of "Object". This is what I've tried. # import_csv.py (manage.my custom command) import csv from django.core.management.base import BaseCommand from models import Site, Association class Command(BaseCommand): help = "Import Command" def handle(self, *args, **options): with open(_file, newline='') as csvfile: reader = csv.DictReader(csvfile, delimiter=";") for row in reader: localsite, created = Site.objects.get_or_create(name=row["locSite"]) distantsite, created = Site.objects.get_or_create(name=row["disSite"]) csv_line, created = Association.objects.get_or_create( localName=row["Name"], locSite=localsite.id, disSite=distantsite.id, ... ) # models.py class Site(models.Model): name = models.CharField(max_length=5, unique=True, help_text="Site Local") objects = models.Manager() class Association(models.Model): localName = models.CharField(max_length=50, help_text="Nom Local") locSite = models.ForeignKey(Site, null=True, on_delete=models.SET_NULL, related_name='local_site_set') disSite = models.ForeignKey(Site, null=True, on_delete=models.SET_NULL, related_name='distant_site_set') Django Admin panel : add record Thx for help -
How do I Concatenate or Combine the dictionary of same data to One
I have the below set of 7 Dictionaries {'empid':785, 'empname':'Ibrahim', 'date(2022,5,1)':'Unmarked'} {'empid':785, 'empname':'Ibrahim', 'date(2022,5,2)':'Unmarked'} {'empid':785, 'empname':'Ibrahim', 'date(2022,5,3)':'Present'} {'empid':785, 'empname':'Ibrahim', 'date(2022,5,4)':'Unmarked'} {'empid':785, 'empname':'Ibrahim', 'date(2022,5,5)':'Unmarked'} {'empid':785, 'empname':'Ibrahim', 'date(2022,5,6)':'Absent'} {'empid':785, 'empname':'Ibrahim', 'date(2022,5,7)':'Unmarked'} I want to convert into the below format. {'empid':785, 'empname':'Ibrahim', 'date(2022,5,1)':'Unmarked', 'date(2022,5,2)':'Unmarked', 'date(2022,5,3)':'Present', 'date(2022,5,4)':'Unmarked', 'date(2022,5,5)':'Unmarked', 'date(2022,5,6)':'Absent', 'date(2022,5,7)':'Unmarked'} How can i do this? -
How to prevent django admin login and logout sessions from reflecting in actual website?
I'm quite new to django. I've made a website that makes use of user auth for login, logout and registration. Whenever I log into the admin panel, it also gets reflected in the actual website. The admin account gets logged into the website on its own. I know this is the default behaviour of the django auth system, but I want to separate the auth session of admin panel and the actual website. How can I do so? The screenshots below show the thing which I'm talking about. 👇 Here I've logged into the Admin panel. 👇 The Admin account got logged into the website on its own by using the admin session.. I just want that both admin panel and website should have separate auth sessions and shouldn't be linked to each other. The website is hosted online here Thanks in advance! -
Best way to pass random answers in Django Quiz App
I'm trying to build quiz app based on Cornell Notes, where the keywords will be the question with 4 answers (one correct answer and three random from other keys) My models: class Note(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=128) summary = models.CharField(max_length=500) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.title) class Record(models.Model): note = models.ForeignKey(Note, on_delete=models.CASCADE, null=True, blank=True) key = models.CharField(max_length=100, blank=False, null=False) value = models.CharField(max_length=300, blank=False, null=False) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return f'{self.key} | {self.value}' e.g. Note is called "Children of Zeus" and has 4 records (4 key and value pairs): key: value Apollo: Twin of Artemis. Is the god of the sun, music, medicine, and poetry. Ares: god of war Hermes: the god of boundaries and the travelers who cross them and the son of Zeus and Maia. Hephaestus: god of blacksmiths, craftsmen, artisans, sculptors, and fire. The question is, how can I easily generate 4 (number of records) questions in HTML with one correct and three incorrect answers each question using views.py and djagno templates? -
django create a field that hold array of tupels or array of array
I want to add a field in my models that hold value like this field = [(1,2,3),(6,5,4),(5,6,7)] or field = [[1,2,3],[6,5,4],[5,6,7]] I am using postgresql db. how to achieve this. -
i am not get linkedin profile picture url in extra data using django allauth linkedin login
i can't get linkedin profile image in extra data when login using django-allauth. in extra data, profile picture url does't exist. i am using django==4.0.4, django-allauth==0.50.0. this is my setting.py of django application. #in setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'ReviewLink', 'Users', # alluth 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', #social account providers 'allauth.socialaccount.providers.linkedin_oauth2', ] SOCIALACCOUNT_PROVIDERS = { 'linkedin': { 'SCOPE': [ 'r_liteprofile', 'r_emailaddress' ], 'PROFILE_FIELDS': [ 'id', 'first-name', 'last-name', 'email-address', 'picture-url', 'public-profile-url', ] } } SITE_ID = 2 SOCIALACCOUNT_ADAPTER = 'Users.my_adapter.MySocialAccountAdapter' #my_adapter.py class MySocialAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): if sociallogin.is_existing: print("the social account already exists") return def populate_user(self, request, sociallogin, data): print(f" Social login account profile data IN POPULATE-USER FUNCTION : {sociallogin.account.extra_data}") dictionaryData = sociallogin.account.extra_data x = dictionaryData['elements'] fname = dictionaryData['firstName'] lname = dictionaryData['lastName'] country = fname['preferredLocale'] print(f"Data = {data}") print(f'provided provided data = {data["first_name"]}') print(f'provided provided data = {data["last_name"]}') print(f'provided provided data = {data["email"]}') #data is a dictionaty {first_name, Last_name, email} try: #if the person with this email exists in the database dont do anything # person = Person.objects.get(email = data["email"]) email = PersonEmails.objects.get(email = data["email"]) return except: #else add the person person = Person() person.email = data["email"] person.firstname = data["first_name"] person.lastname = data["last_name"] person.country … -
Django rest framework using Template to send an e-mail
I want to send a styled email using HTML tags. The mail is sent successfully but without style and the HTML tags are presented as a text in the email. handles.py @receiver(order_created) def on_order_created(sender, **kwargs): order=kwargs['order'] capture_email= order.customer.user.email name= order.customer.user.username title= 'Thank you ' + name order_items=OrderItem.objects.filter(order=order) template= render_to_string('index.html',{'order_items':order_items,'name':name}) # text_content = strip_tags(template) email =EmailMessage( title, template, settings.EMAIL_HOST_USER, [capture_email], ) email.fail_silently=False, email.send() -
What Causes 400 Bad Request In Django Graphene and NextJs Using The useMutation Hook?
I am trying to build a simple todo app using Django, Graphene and NextJs. I was able to create todos in graphiQL and postman, however when I try to create a todo in the NextJs, I get a 400 Bad Request from the server. I have tried to do same using plain ReactJs but I still get the same error. Below is the error This is my models.py file from django.db import models class Todo(models.Model): title = models.CharField(max_length=255) completed = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title This is my todos/schema.py file import graphene from graphql import GraphQLError from .models import Todo from graphene_django import DjangoObjectType class TodoType(DjangoObjectType): class Meta: model = Todo class Query(graphene.ObjectType): todos = graphene.List(TodoType) def resolve_todos(self, info): return Todo.objects.all() class CreateTodo(graphene.Mutation): todo = graphene.Field(TodoType) class Arguments: title = graphene.String() def mutate(self, info, title): user = info.context.user if user.is_anonymous: raise GraphQLError('Login to add a todo!') todo = Todo(title=title) todo.save() return CreateTodo(todo=todo) class Mutation(graphene.ObjectType): create_todo = CreateTodo.Field() this is my apollo-client.js file import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client"; const httpLink = createHttpLink({ uri: "http://localhost:8000/graphql", }); const client = new ApolloClient({ link: httpLink, credentials: "include", cache: new InMemoryCache(), }); export default client; This … -
Visual geograph map with coordinates using Django in html/js?
I made the following function in views.py to return a json response of coordinates. The function is: def dispatch(request): events = Event.objects.filter(description="Dispatch").values("element") starts = Start.objects.all() ends = End.objects.all() d_starts = { s['start_id']: s for s in start } d_ends = { c['end_id']: c for c in end } d_start_end_ids = [ { 'start': d_starts[e['element'][52:58]], 'end': d_ends[e['element'][69:75]] } for e in events ] for d in d_start_end_ids: dispatch_data = {'[%s, %s] -> [%s, %s]' % (d['start']['latitude'], d['start']['longitude'], d['end']['latitude'], d['end']['longitude'])} JsonResponse(dispatch_data) The json response of coordinates with the following structure start -> end: [53.5011961270582, -1.12708338945015] -> [53.34474, -3.01101] [53.5011961270582, -1.12708338945015] -> [53.34474, -3.01101] [52.0406164854484, -0.665507269164437] -> [51.90829, -0.5127] [52.0406164854484, -0.665507269164437] -> [51.90829, -0.5127] [52.0406164854484, -0.665507269164437] -> [51.90829, -0.5127] Whats the best way of showing each line from start to end on a geomap ideally using OpenLayers? Is this a good way of going abuot it? Thanks! -
Trying to migrate an old project from python2 to python3 and got stuck in this error in urls.py
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html']) *File "C:\Users\DSS-WT\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\urlpatterns.py", line 112, in format_suffix_patterns return apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required, suffix_route) File "C:\Users\DSS-WT\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\urlpatterns.py", line 59, in apply_suffix_patterns regex = urlpattern.pattern.regex.pattern.rstrip('$').rstrip('/') + suffix_pattern AttributeError: 'tuple' object has no attribute 'pattern'* -
Need to override save method for image field and save it as base64 string using django
models.py class Organisation(models.Model): org_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True) org_name = models.CharField(unique=True,max_length=100) org_code = models.CharField(unique=True,max_length=20) org_mail_id = models.EmailField(max_length=100) org_phone_number = models.CharField(max_length=20) org_address = models.JSONField(max_length=500, null=True) product = models.ManyToManyField(Product, related_name='products') org_logo = models.ImageField(upload_to=upload_org_logo, null=True, blank=True,) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I need to save an image which I get in image field on org_logo as a base64 string and upload it to the s3 bucket which I have given as file storage using django storages. Note: File object will be the input I will be getting from the frontend(React). I need to override the save method to save it as base64 string. I have referred many data but I couldn't able to get it properly. Can anyone please guide me to what exactly needs to be changed and where so that I could understand better. -
Only accept 2 digits integer array in django model form
How to make a form field that accept 2 digit numeric array in frontend. if someone enter more then 2 digit or string then The input value is automatically validated to ensure it is a properly formatted 2 digit integer array. right wrong below My work models.py class Jodi(models.Model): numb = ArrayField(models.IntegerField(null=True, blank=True), null=True, blank=True) forms.py from django import forms from .models import Jodi class MyModelForm(forms.ModelForm): class Meta: model = Jodi fields = ['numb',] views.py if request.method=='POST': fm = MyModelForm(request.POST) if fm.is_valid(): numbers = fm.cleaned_data['numb'] numbers1 = [] for x in numbers: if x: numbers1.append(x) X=Jodi.objects.create(numb=numbers1,) X.save() else: fm = MyModelForm() return render(request,'myapp/home.html',{'form':fm}) home.html <form action="" method="post">{% csrf_token %} {{ form.as_p }} -
Get working link in 'currently' field of a file field django admin
I have a model with a FileField and when I go on the admin page and want to modify the file, this page show up. On the 'file' field there is a link which you'd think would either download the file or display its content, but by clicking on it, it tries to go to the displayed link instead of going to the actual file link : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/media/media/scripts/Script%20hello/hello.py Using the URLconf defined in Website.urls, Django tried these URL patterns, in this order: scripts/ admin/ __reload__/ The current path, media/media/scripts/Script hello/hello.py, didn’t match any of these. Is it possible to modify the link in order to download the file ? -
how to have multiple user types in django
this app is a school management system with django i have three types of user in my web app, my problem is how to authorize these and give them permissions. users are: teacher, student, school staff(admins) i need to have different pages(apps) for each of them, like: teacher -> login -> teacher_app. student -> login -> student_app. im new in django my models are something like this: class Student(models.Model) : national_id = models.CharField( max_length=50, unique=True, ) name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone_number = models.CharField(max_length=50) class Teacher(models.Model) : personal_id = models.CharField( max_length=50, unique=True, ) name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone_number = models.CharField( max_length=50, unique=True, ) email = models.EmailField( max_length=250, unique=True, ) class Class(models.Model): name = models.CharField(max_length=50) start_time = models.TimeField( auto_now=False, auto_now_add=False, default=DEFAULT_START_TIME, ) end_time = models.TimeField( auto_now=False, auto_now_add=False, default=DEFAULT_END_TIME, ) # Relations teacher = models.ForeignKey( Teacher, on_delete=models.CASCADE ) students = models.ManyToManyField(Student) admins will create classes and add students and teachers. -
Can I change model admin verbose name based on user group login in django?
I am aware of the Model Meta tag to specify the verbose_name, verbose_name_plural. But require the verbose name in model admin based on user login based on the group he is in. How can we override this attribute? -
Selectively hit the update signal for a model
I have a model called as nodes: class node(models.Model): name = models.CharField(max_length=200) status = models.CharField( max_length=32, choices=[], # some list of choices ) created_on = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) def __str__(self): return self.name A node has a status. There can be nodes which are dependent on the status of a particular node. For example: node B,C is dependent on node A. Node D is dependent on node B. I have a post_save signal which is triggered when the status of a particular node is changed. What I want: When I change the status of A, the status of B and C should also change accordingly. And since node D is dependent on node B, the status of D also should change as per the node B's new status. Problem: The post_save signal hits everytime the change of any of these nodes is changed. So for example, an update signal will be fired when status of A is changes. I would then want to change the status of B and C in this trigger. But as soon as the status of B changes, the post_Save signal will again be hit and the code would not even reach to … -
django not geeting ?next=/ without ?next=/ I couldn't get the same page that I want before
Hello everyone please help me to find out this problem I want a URL like http://127.0.0.1:8000/baseaccount/vender_login/?next=/login/ but I am getting http://127.0.0.1:8000/baseaccount/login/ basically, ?next=/ is missing that why after login I couldn't go to the same page that I want before. -
How to load data from multi-level nesting object
``` when i do the School.objects.filter() query , how to load student object in single query using School.objects.filter() ``` class School(models.Model): name = models.CharField(max_length=50) grade = models.ForeignKey(Grade) class Grade(models.Model): name = models.CharField(max_length=10) class Student(models.Model): name = models.CharField(max_length=50) grade = models.ForeignKey(Grade) when i try to load the student object using the school.objects.filter(), its load only school object, when i use select_related('grade'), its load grade object in single sql query how can i use select_related('student'), with school.objects.filter() -
decreasing values with loop in Django
in this code, I tried to decrease the quantity of products from the database when the user places the order, it is working but the problem is just decreasing from the first product in the cart? new_order_items = Cart.objects.filter(user=request.user) for item in new_order_items: OrderItem.objects.create( order=neworder, product=item.product, price=item.product.selling_price, quantity=item.product_quantity ) # decrease the product quantity from table order_product = Product.objects.filter(id=item.product_id).first() order_product.quantity = order_product.quantity - item.product_quantity order_product.save() -
while hitting create api on postman "error": "hashpw() argument 1 must be str, not bytes" is coming
code for create user try: # If it's social login that is from Google, Facebook or Apple if 'social_login_id' in request.data and request.data['social_login_id'] != 0: schema = { "email": {'type': 'string', 'required': False, 'nullable': True}, "device_token": {'type': 'string', 'required': True, 'empty': False}, "device_type": {'type': 'number', 'required': True, 'empty': False}, "social_token": {'type': 'string', 'required': True, 'empty': False}, "social_login_id": {'type': 'number', 'required': True, 'empty': False} } else: # If email id already exist if User.objects(email=request.data.get('email').lower()).first(): return Response({'error': Messages.EMAIL_EXITS}, status=status.HTTP_200_OK) # If username already exist if User.objects(username=request.data.get('username')).first(): return Response({'error': Messages.USERNAME_EXITS}, status=status.HTTP_200_OK) schema = { "first_name": {'type': 'string', 'required': True, 'empty': False}, "last_name": {'type': 'string', 'required': True, 'empty': False}, "username": {'type': 'string', 'required': True, 'empty': False}, "email": {'type': 'string', 'required': True, 'empty': False}, "password": {'type': 'string', 'required': True, 'empty': False}, "device_type": {'type': 'integer', 'required': True, 'empty': False}, "device_token": {'type': 'string', 'required': True, 'empty': False}, "social_token": {'type': 'string', 'required': False, 'nullable': True}, "social_login_id": {'type': 'integer', 'required': True, 'empty': False}, } v = Validator() # validate the request if not v.validate(request.data, schema): return Response({'error': v.errors}, status=status.HTTP_400_BAD_REQUEST) # Create new user utility = hashingUtility() hashed_model = utility.getHashedPassword(request.data["password"]) User.objects.create( first_name=request.data["first_name"], last_name=request.data["last_name"], username=request.data["username"], email=request.data["email"], password=str(hashed_model.Password, 'utf-8'), password_salt=str(hashed_model.Salt, 'utf-8'), device_type=request.data["device_type"], device_token=request.data["device_token"], social_token=request.data["social_token"], social_login_id=request.data["social_login_id"], is_active=1, is_deleted=0 ) # Get inserted user … -
Docker Container not loading static files from Django-React Project
I've been trying to get my main.js file and css static files to load in my container and on google cloud for the past 4 days. Here is my file tree: main/ - frontend/ - node_modules/ - src/ -components/ - index.js - static/ - frontend/ - css/ - main.js - templates/ - frontend/ - index.html - package.json - pack-lock.json - nginx/ - main_project/ - Dockerfile - docker-compose.yml - requirements.txt My docker file has the following: FROM python:3.9-alpine ENV PYTHONUNBUFFERED 1 WORKDIR /pathfinder COPY requirements.txt . RUN pip install -r requirements.txt COPY . . COPY ./entrypoint.sh / ENTRYPOINT ["sh", "entrypoint.sh"] RUN apk update RUN apk add RUN apk add npm COPY ./frontend/package.json /frontend/package.json COPY ./frontend/package-lock.json /frontend/package-lock.json RUN cd frontend/ && npm install my docker-compose.yml folder looks like the following: version: "3.8" services: pathfinder_gunicorn: build: context: . volumes: - static:/static - ./frontend/static/:/pathfinder/frontend/static/ ports: - "8080:8080" image: pathfinder_gunicorn:v1 container_name: pathfinder_gunicorn nginx: build: ./nginx volumes: - static:/static ports: - "80:80" depends_on: - pathfinder_gunicorn volumes: static: Can someone please tell me what is going on and why can't I load my js and css files onto my index.html page?