Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Verifying AzureAD access token with Django-REST-framework
Before anything I would like to warn you about my extremely limited knowledge on the subject. Now that you've been warned, what I need to ask is how can I verify and azureAD access token with Django/django-rest-framework. I have a app that I need to sing in to with azureAD, which means I need to get an access token from azureAD, and thankfully this is will be done on the frontend side with Angular what I need to do is verify that token on the backend side with django/django-rest-framework and I have no idea where to start from, can anyone suggest a way to do this or send me in the right direction ? Thank you very much. -
Django/Flask : Rewritting an Flask Azure B2C authentication in Django, issue with the scope
I want to use and Azure B2C authentication in Django, however there is no tutorial in Django for it but in Flask. However I never coded in Flask. I used the documentation/tutorial of microsoft that share a github with the flask code to do it : https://docs.microsoft.com/en-us/azure/active-directory-b2c/configure-authentication-sample-python-web-app?tabs=windows I try to convert it in Django but I have two issues. One is one line in Flask that I am not sure to understand well its role and how to rewrite it in Django. The second one is the scope of the input variables that do not work. Here is the code how I converted : views.py from django.shortcuts import render, redirect import msal import os from dotenv import load_dotenv load_dotenv() def index(request) : if not request.session.get("user"): return redirect("login") return render('index.html', user=request.session["user"] ) def login(request): print(os.getenv("SCOPE")) # Technically we could use empty list [] as scopes to do just sign in, # here we choose to also collect end user consent upfront request.session["flow"] = _build_auth_code_flow(scopes=os.getenv("SCOPE")) return render("login.html", auth_url=request.session["flow"]["auth_uri"], ) def authorized(request): try: cache = _load_cache(request=request) result = _build_msal_app(cache=cache).acquire_token_by_auth_code_flow( request.session.get("flow", {}), request.args) if "error" in result: return render("auth_error.html", result=result) request.session["user"] = result.get("id_token_claims") _save_cache(cache=cache, request=request) except ValueError: # Usually caused by CSRF pass # … -
How to run single Django project on multiple static IP address in docker
Here, this project works fine. This project is opening only on single static IP address. The problem is I want to open this project on multiple static IP address in docker. Can anyone tell me how to do this? This help will be good for me. Please help. docker-compose.yml: version: '3.9' services: app: build: context: . args: - DEV=true ports: - '8000:8000' volumes: - ./app:/app - dev-static-data:/vol/web command: > sh -c 'python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000' environment: - DB_HOST=db - DB_NAME=devdb - DB_USER=postgres - DB_PASS=m@noj5078 - DEBUG=1 depends_on: - db db: image: postgres:13-alpine volumes: - dev-db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=devdb - POSTGRES_USER=postgres - POSTGRES_PASSWORD=m@noj5078 volumes: dev-db-data: dev-static-data: proxy/default.conf.tpl 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; } } -
user is anonymous despite the user is logged in
I hope you are fine. I have a project using vue and django rest and I have done the authentication by djoser. When a user logs in, a token would be set and the user can login to the website correctly but in views.py when I use self.request.user in get_queryset(self) function it says that the user is anonymous. I will thank if anyone give me a piece of advice. Thanks. -
Why homebrew installs everything in /opt/homebrew/Cellar, while my python project looks for everything in /usr/local
I'm new to macos using Monterey on an M2 macbook Air, and having a hard time satisfying dependencies for a django project. To make it clean and simple, I've build python 3.8 from source, --with-openssl=/also/built/from/source, created a bin/python -m venv django, went source ./django/bin/activate, and installed the project requirements.txt. After running a project, i keep encountering missing library errors, like '/usr/local/lib/libssl.1.1.dylib' (no such file) '/usr/local/lib/libcairo.2.dylib' (no such file) '/usr/local/lib/libffi.8.dylib' (no such file) etc. Even though in the case of libssl for example, i would have expected python to know the location of the custom built openssl, i've went ahead and installed these system dependencies with brew install openssl@1.1 cairo libffi etc. but the errors persisted until i linked (ln -s) each library from /opt/homebrew/Cellar/libffi/3.4.2/lib/libffi.8.dylib to /usr/local/lib/libffi.8.dylib. Why is all this happening? Why is homebrew not populating a static library path? -
execute for loop for a dictionary key
This kind of data i have sent to my template x = [{'id': 668, 'title': 'ME2: Pressurisation Unit Maintenance Record', 'valuess': ['person', 'address', 'asset']} return render(request, 'xyz.html', {'data': x}) want to run a for loop for a key named 'values' in my data set x "x" is a key but it contains list of values as well. So want to run a for loop on a key "values" How to do this. anyone please help....I just started my programming career...i am stucked plz help me -
Run Django's model makemigration from package
I have different package's structure and i want to run makemigration and then migrate but it doesn't work. i have app user_app and models package where is my custom user model's file. when i run makemigration i have this - > No changes detected in app 'user_app' what i can do? it's my project structure user.py from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.core.exceptions import ValidationError from user_app.const import STATUS_CHOICES def validate_length(value): if len(str(value)) != 11: raise ValidationError(('Passport must be 11 digit!')) class MyUserManager(BaseUserManager): def create_user(self, email, last_name, first_name, passport_id, password=None): if not email: raise ValueError('Email is required') elif not last_name: raise ValueError('Last name is required') elif not first_name: raise ValueError('First name is required') elif not passport_id: raise ValueError('Passport is required') user = self.model( email=self.normalize_email(email), last_name=last_name, first_name=first_name, passport_id=passport_id ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractUser): email = models.EmailField(unique=True, verbose_name='Email', error_messages={'unique': 'This email already exists'}) first_name = models.CharField(max_length=20, verbose_name='First name') last_name = models.CharField(max_length=25, verbose_name='Last name') passport_id = models.BigIntegerField(validators=[validate_length], verbose_name='Passport') status = models.CharField(max_length=20, choices=STATUS_CHOICES) object … -
how to use arithmetics in djangos save method?
What is the best appraoch for overriding a save method, which calculates modelfield a trough self.modelfielda= self.modelfieldb / 4 + self.modelfieldc / 2 Currently I get Expected type 'int', got 'DecimalField' instead -
Django ORM query optimisation with multiple joins
In my app, I can describe an Entity using different Protocols, with each Protocol being a collection of various Traits, and each Trait allows two or more Classes. So, a Description is a collection of Expressions. E.g., I want to describe an entity "John" with the Protocol "X" that comprises the following two Traits and Classes: Protocol ABC Trait 1: Height Available Classes: a. Short b. Medium c. Tall Trait 2: Weight Available Classes: a. Light b. Medium c. Heavy John's Description: Expression 1: c. Tall, Expression 2: b. Medium My model specification (barebone essentials for simplicity): class Protocol(models.Model): name = models.CharField() class Trait(models.Model): """ Stores the Traits. Each Trait can have multiple Classes """ name = models.CharField() protocol = models.ForeignKey( Protocol, help_text="The reference protocol of the trait", ) class Class(models.Model): """ Stores the different Classes related to a Trait. """ name = models.CharField() trait = models.ForeignKey(Trait) class Description(models.Model): """ Stores the Descriptions. A description is a collection of Expressions. """ name = models.CharField() protocol = models.ForeignKey( Protocol, help_text="reference to the protocol used to make the description;\ this will define which Traits will be available", ) entity = models.ForeignKey( Entity, help_text="the Entity to which the description refers to", ) class … -
Is there a method to pass a folder path into a File Upload form in Django?
System at present uses no models. Takes user selected multi file input, parses information and generates an output. Currently user needs to navigate to correct share drive location before selecting file(s). Is it possible to pass a folder path (and ideally search string for filename) on windows explorer open using Django form? -
How do I import a Json file into a django database whilst maintaining object references
I have a C# desktop app and a django webapp that share a set of common class/model types. The C# app is exporting json files containing instances of these models, and I am trying to import these into the django database. The complication is that the parent model contained within the json file has properties that may reference the same sub-model in multiple places. For example, the json file looks something like this: { "$id": "1", "SubModels": { "$id": "2", "$values": [ { "$id": "3", "name": "Dave", "value": "123" }, { "$id": "4", "name": "John", "value": "42" } ] }, "PreferredSubModel: { "$ref": "4" } } Which was created using the using System.Text.Json.Serialization C# library with the ReferenceHandler = ReferenceHandler.Preserve serialisation option. In django, I've converted the json file into a dictionary using model_dictionary = JSONParser().parse(json_file). Are there any existing functions (in the django Python environment) that can handle this $id/$ref system to maintain class instances, or do I need to code my own deserializer? If the latter, does anyone have any suggestions for the best way to handle it? I'm new to django and json files, so hopefully I've just been googling the wrong terms and something exists... -
Django auto reloading of code changes not working in Docker on MacM1
Django auto reloading of code changes deployed in docker containers doesn't work on mac m1. -
Display Django Object Values List to jquery datatables
I'm trying to display the data from postgresql using django python to jquery datatables but I'm having some problems. this is my view.py from administrator.models import User def showuser(request): showall = list(User.objects.values_list()) return render(request, '/path.html', {"data": showall}) I want to display it to html template using javascript <script type="text/javascript"> var myDjangoList = "{{ data | safe}}" console.log(myDjangoList) $(document).ready(function () { $("#example").DataTable({ data: [myDjangoList], columns: [ { title: "ID" }, { title: "First Name" }, { title: "Last Name" }, { title: "Email" }, { title: "Roles" }, { title: "Company" }, ], }); }); </script> But unfortunately, I'm having this problem. My table looks like this [table 1] and my data looks like this [(1, 'Test', 'Test', 'Test.@gmail.com', 'Test', 'Test')] -
No data in my postgres DB even though it exists
I have a PostgreSQL DB on a remote ubuntu server. My Python script is able to write to the DB, with the use of these configuration. def get_query(group_name , heb_sale_rent ,heb_street, heb_city , heb_rooms , heb_size , heb_floor , heb_porch , heb_storage , heb_mamad , heb_parking , heb_elevator , heb_phone , heb_price): conn = psycopg2.connect(database='my_db', host='192.168.72.130', port='5432', user='sql_user', password='sql_user') cur = conn.cursor() cur.execute("SELECT * FROM to_excel") query = cur.fetchall() print(query) #Result of print - [('1', 'Karin', 'מכירה, השכרה', 'רחוב, ברובע', 'שכונת, בסמטאות', 'חדרים', 'מ״ר, מ"ר', 'קומה', 'מרפסת', 'מחסן', 'ממד, ממ״ד', 'חניה, חנייה, חניית, חנית', 'מעלית', '054, 052, 053', 'מחיר, מבקשים', '2020-01-01')] I can see that there is data because it prints out the query, but when I connect to the DB on the ubuntu there are no table rows... so weird. Does anybody know what the problem might be? -
Testing CRUD function in Django Restaurant App
I am wondering if someone could help me. I am trying to test some views in a Django restaurant bookings system app I have created. I am doing well with jut testing the views but now I want to test the CRUD functionality of certain pages. In particular the create a booking on the bookings page and then redirect it back to the home page once the booking was successful (as is what happens on the site) I just can't seem to figure out how to do it. Here is my current code. If someone could point me in the right direction that would be great. Thanks setUp: class TestViews(TestCase): """ Testing of the views taken from the views.py file. All HTTP testing includes the base.html template as well as the view being tested to make sure everything is being tested as it would appear for a user """ def setUp(self): testing_user = User.objects.create_user( username='JohnSmith', first_name='John', last_name='Smith', email='johnsmith@email.com', password='RandomWord1' ) Booking.objects.create( user=testing_user, name='John Smith', email_address='johnsmith@email.com', phone='123654789', number_of_people='2', date='2022-10-20', time='19:00', table='Window', occasion='none' ) test: def test_add_booking(self): self.log_in() response = self.client.post('/bookings', {Booking: Booking}) self.assertRedirects(response, '/') -
Django View value not updating in template unless gunicorn.socket is restarted (setup: Django + Gunicorn + Nginx)
I have a little Django website running on Ubuntu 22.04 on Linode. It uses Nginx and Gunicorn to serve the Django page. Now I struggle to understand how to get the latest value for today's date & time from views.py upon a page refresh; it seems to get cached somewhere instead. My view contains the following: import datetime class MonitorView(LoginRequiredMixin, ListView): [...] def get_context_data(self, **kwargs): context_data = super().get_context_data(**kwargs) context_data['todayvalue'] = datetime.datetime.today() return context_data And my template contains: {% extends 'base.html' %} {% block title %} DummyTitle {% endblock title %} {% block content %} {{todayvalue}} {% endblock content %} When loading the template, this {{todayvalue}} prints "Aug. 11, 2022, 8:32 a.m.". And when refreshing the template again 10 minutes later, this {{todayvalue}} still prints "Aug. 11, 2022, 8:32 a.m.". When I restart gunicorn.socket (sudo systemctl restart gunicorn.socket), the values get updated. So it seems gunicorn doing some kind of caching. The thing that confuses me even more, is that other values in the views are updated fine in the template without requiring a gunicorn.socket restart. For example this value in the view: total_monthly_sent_volume = DailyStats.objects.filter(sg_date__gt=last_month).aggregate(Sum('sg_processed')) context_data['total_monthly_sent_volume'] = total_monthly_sent_volume is presented in the template in pretty much the same way, with … -
Django - Annotate with Case/When/Value and related objects
I have the two following models: class Post(models.Model): content = models.TextField() class Vote(models.Model): UP_VOTE = 0 DOWN_VOTE = 1 VOTE_TYPES = ( (UP_VOTE, "Up vote"), (DOWN_VOTE, "Down vote"), ) post = models.ForeignKey(Post, related_name="votes") vote_type = models.PositiveSmallIntegerField(choices=VOTE_TYPES) I would like to have a score property on Post that returns the sum of the values of the votes to that post, counting votes with UP_VOTE type as 1 and those with DOWN_VOTE as -1. This is what I’ve tried: # inside Post @property def score(self): return ( self.votes.all() .annotate( value=Case( When(vote_type=Vote.DOWN_VOTE, then=Value(-1)), When(vote_type=Vote.UP_VOTE, then=Value(1)), default=Value("0"), output_field=models.SmallIntegerField(), ) ) .aggregate(Sum("value"))["value__sum"] ) However, this yields None. More specifically, without dereferencing ["value__sum"], this returns {'value__sum': None}. Is using Case-When-Value the correct approach to my use case? If so, what’s wrong with the code I posted? Thanks in advance. -
Error while changing database engine to PostgreSQL
I got this error after changing the engine, the database is connected however it figured out my id field is a bigint, yet I specifically set it as a UUID field. class Cart(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) created_at = models.DateTimeField(auto_now_add=True) in terminal I get this error: django.db.utils.ProgrammingError: cannot cast type bigint to uuid LINE 1: ...LE "store_cart" ALTER COLUMN "id" TYPE uuid USING "id"::uuid enter image description here -
django restframework object-level-validation
These are my models : Test, Skillarea, question MODELS.PY : class Test(BaseModel): types = models.ManyToManyField( TestType, related_name='tests', ) title = models.CharField(max_length=255) summary = models.TextField() def __str__(self): return self.title class SkillArea(BaseModel): title = models.CharField(max_length=255) test = models.ForeignKey('Test', on_delete=models.PROTECT, related_name='skill_areas') questions = models.ManyToManyField( 'assessment.Question', related_name='skill_areas', ) def __str__(self): return self.title class Question(BaseModel): question_text = models.TextField() def get_absolute_url(self): self.get_type_display() def __str__(self): return truncatewords(self.question_text, 7) class TestType(BaseModel): title = models.CharField(max_length=255) def __str__(self): return self.title I want to have an updateserializer for updating, but the field "type" in the Test model, only can be updated if there is no question in Skillarea model which related to Test model( has the same id as updating test, in its test field) I wrote these serializer and view but it doesnt know data['id'] which i used in validator and sends KeyError: 'id' serializer.py : class TestUpdateAPIViewSerializer(serializers.ModelSerializer): def validate(self, data): questions = SkillArea.objects.filter(test=data['id'], questions=None) if questions.exists(): raise serializers.ValidationError("You may not edit type") return data class Meta: model = Test fields = ( 'id', 'types', 'title', 'summary', ) Views.py : class TestUpdateAPIView(APIView): def patch(self, request, pk): test = Test.active_objects.get(pk=pk) serializer = TestUpdateAPIViewSerializer(instance=test, partial=True, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) -
Django Model custom User creates auth_user table in my app database when using multiple databases
I've created a new project from scratch. By default it uses the auth package for user and permission management. I am wanting to override the default User - using AbstractBaseUser. Having created migrations and executed them on my databases, the auth_user table resides in my application database - not the auth database. Is this expected behaviour? I was expecting - and I want the auth_user table to reside in the auth database. Is there a way to make the auth_user reside in the auth database? Create Project py -m venv venv venv\scripts\activate pip install django django-admin startproject core . py manage.py startapp acmeapp acmeapp/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class Foo(models.Model): foo_id = models.BigAutoField(primary_key=True) name = models.TextField() class Meta: db_table = 'foos' class AccountManager(BaseUserManager): """ The management class to handle user creation. """ def create_user(self, username, password=None): if not username: raise ValueError(_('The Username must be set')) user = self.model(username=username) user.set_password(password) user.save() return user def create_superuser(self, username, password=None): return self.create_user(username, password) class Account(AbstractBaseUser): """ The custom user model. """ username = models.CharField(max_length=40, unique=True) email = None USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['access_platforms', 'access_missions', 'access_rule_sets', 'access_mdsr'] objects = AccountManager() def __str__(self): return ''.join(c for c in self.username if … -
Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details
remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 remote: remote: https://devcenter.heroku.com/articles/django-assets remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed This is the error i am getting when i am deploying my application on Heroku. I used a postgres database to store my data and when i am trying to deploy its giving me an error code DEBUG = False ALLOWED_HOSTS = ['127.0.0.1','mca-blog-n.herokuapp.com'] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR,'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 = 'CrabbyCoder.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static') ] -
ModuleNotFoundError: No module named 'django_rest_passwordreset'
I have tried to Create a Django Superuser Account for my Project by using: 'python manage.py createsuperuser' on the command Prompt error occurred - ModuleNotFoundError: No module named 'django_rest_passwordreset' -
Nepali language written in html template of python not supporting
i was trying to display sales invoice in nepali language but it displays as enter image description here -
Raised Error when I run python manage.py in Django in linux vps
I've recently cloned my django project into a linux vps. I used python3.10 in my system but in vps I have python3.8 . Actually I installed all necessary packages for it and also created database. I have this error whenever I run commands start with python manage.py. Can any body help me to solve it? Maybe this error is for different python version? It also raised the error ModuleNotFoundError: No module named 'mysite' but I have no idea where I defined 'mysite' module. Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/commands/runserver.py", line 74, in execute super().execute(*args, **options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/commands/runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 92, in __getattr__ self._setup(name) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line … -
How to display the data that available in database using exist() query
I have this Code. But I need to display the values that exists in the database, Not like "It's Exists in the Database", I need to display the values of that given email_id. def post(request): if request.method == 'GET': value = example.objects.all() email_id = request.GET.get('email_id', None) if example.objects.filter(email_id = email_id).exists(): tutorials_serializer = exampleSerializer(value, many=True) return JsonResponse(tutorials_serializer.data, safe=False) Pls help me through it.