Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter for ManyToMany items which exist only in a specified list
I have the following: class Category(): category_group = models.ManyToManyField("CategoryGroup", blank=True, related_name="category_group") class CategoryGroup(): label = models.TextField(null=True, blank=True) categories = Category.objects.exclude(category_group__label__in=["keywords_1", "keywords_2"] I wish to exclude the categories whose group label exists in either keywords_1 or keywords_2 only. If a category group label exists in keywords_1 and keywords_3 I do not want to exclude it. What changes are needed for this query? -
Unique value in django model field
I have the following code: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Employee(models.Model): employee = models.OneToOneField(User, on_delete=models.CASCADE) executive_head = models.BooleanField( default=False, help_text=_("e.g. Chief Executive Officer or Managing Director."), ) job_title = models.CharField(max_length=100) def __str__(self): return f"{ self.employee }" What I would like to see is that only one value should be true in the executive_head field. It should not be possible to have more than one executive head. Using unique_together in the class Meta does not work (in hindsight it should not) because the false values would then not be unique. Any ideas? -
Django ForeignKey prevent creation when parent is a child
I have the following model: class PostModel(models.Model): post = models.ForeignKey('self', on_delete=models.CASCADE, related_name='posts') I can create new posts like this: post_1 = PostModel.objects.create() Or new posts with a parent post: post_2 = PostModel.objects.create(post=post_1) I want to know if it's possible for a post to have only a parent which itself doesn't have a parent. So the following wouldn't be allowed: post_3 = PostModel.objects.create(post=post_2) # post_2 has a parent, prevent creation -
Django FileDescriptor in settings
In my Django project, I want to use the MaxMind db file to acquire information about IP-addresses. The file takes up to 90 megabytes. I expect about 50 requests per second and also the application will be hosted on the Gunicorn with 3 workers. So, Will I meet the limits if I open a file every request? with maxminddb.open_database('GeoLite2-City.mmdb') as mmdb: info = mmdb.get('152.216.7.110') return Response({'city': info.city, 'other': 'some_other_information_about_ip'}) or should I open the file in settings.py once: mmdb = maxminddb.open_database('GeoLite2-City.mmdb') and use this descriptor in my views.py ? from django.conf import settings .... info = settings.mmdb.get('152.216.7.110') return Response({'city': info.city, 'other': 'some_other_information_about_ip'}) I am concerned about several problems: If 2 workers will try to read the file simultaneously, where might be conflicts. The File descriptor will not be properly closed if the application fails. What is best practice for Django apps to keep files in memory. -
Access the files that are being sent via a PATCH request inside of Django middleware
I have written a Django middelware class that I used to access the files that are being uploaded and do some stuff. I have used rest_framework package to enable some API enpoints. When I try to do a POST request with an uploaded file, I can access that file by calling request.FILES. However, if I do a PATCH request with a file, request.FILES is empty. Instead the file is inside of the request.body as a byte stream. What do I have to do to access the file using request.FILES in a patch request? Middleware: class MyMiddleware: def __init__(self, get_response): # noqa: D107 self.get_response = get_response def __call__(self, request): if request.FILES: for key, file in request.FILES.dict().items(): # Do some stuff pass response = self.get_response(request) return response I tried to parse the request with rest_framework's MultiPartParser but no luck. Thanks in advance! -
I want to make password field in my model by the inheriting AbstractBaseUser, but it shows me the error about non-nullable iid field
It is impossible to add a non-nullable field 'id' to client without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit and manually define a default value in models.py. models.py from django.contrib.auth.models import AbstractBaseUser from django.db import models class Client(AbstractBaseUser): username = models.CharField(max_length=200) password = models.CharField(max_length=200, default="") def __str__(self): return self.username -
Django custom database field - psycopg2.errors.SyntaxError: syntax error at or near "None"
I've created a custom fields called RelativeURLField that inherits the CharField from django.db.models.CharField. from django.db import models from django.core.validators import RegexValidator class RelativeURLField(models.CharField): default_validators = [RegexValidator( regex=r'^(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)', message='Enter a valid URL.', code='invalid_url' )] When replacing the URLField in the model with this custom field. I get this error psycopg2.errors.SyntaxError: syntax error at or near "None" LINE 1: ...onal_investor" ALTER COLUMN "website_url" TYPE varchar(None) This is the part that is causing the error in the migration script migrations.AlterField( model_name='institutionalinvestor', name='website_url', field=accounts.fields.RelativeURLField(blank=True, default='', null=True), ), I've tried giving the field a default value by editing the AlterField part. However, the same issue persists. -
If .env file is not included in git then how the prod deployment works in ec2 , how the prod code gets access to variables?
.env is included in gitignore ,then how do the prod code know the values. I think that the jenkins handle this in order to maintain security , but please someone let me know how this works .Since i dont have much knowledge on devops side. -
list index out of range IndexError at /en/dashboard/edit-server-request/2/
So i'm trting to edit a form and while submission it shows: IndexError at /en/dashboard/edit-server-request/2/ list index out of range this is the views.py def edit_server_request(request, pk): server_request = get_object_or_404(ServerRequest, pk=pk) mediator = server_request.mediator teachers = server_request.teachers.all() if server_request.teachers.exists() else None TeacherFormSet = formset_factory(TeacherForm, extra=1, formset=BaseTeacherFormSet) if request.method == "POST": server_request_form = ServerRequestForm(request.POST, instance=server_request) mediator_form = MediatorForm(request.POST, instance=mediator) teacher_formset = TeacherFormSet(request.POST, prefix='form') if all([server_request_form.is_valid(), mediator_form.is_valid(), teacher_formset.is_valid()]): print('All forms are valid') server_request = server_request_form.save(commit=False) mediator = mediator_form.save() server_request.mediator = mediator server_request.user = request.user server_request.save() # Delete any existing teachers that were removed from the form existing_teachers = set(teachers) new_teachers = set() for form in teacher_formset.forms: teacher = form.save(commit=False) if teacher.name: teacher.server = server_request new_teachers.add(teacher) for teacher in existing_teachers - new_teachers: teacher.delete() # Save the new teachers for form in teacher_formset.forms: teacher = form.save(commit=False) if teacher.name: teacher.server = server_request teacher.save() else: print('One or more forms are invalid') else: server_request_form = ServerRequestForm(instance=server_request) mediator_form = MediatorForm(instance=mediator) initial_data = [{'name': teacher.name, 'contact': teacher.contact} for teacher in teachers] if teachers else None teacher_formset = TeacherFormSet(prefix='form', initial=initial_data) context = { 'server_request_form': server_request_form, 'mediator_form': mediator_form, 'teacher_formset': teacher_formset, } forms.py class ServerRequestForm(forms.ModelForm): """ Server request form for schools This uses a three way chained dependent dropdown for province, district … -
Using related_name in Django Template
I have two models: Usecase and Usecase_progress. I'm creating a page where I can see a list of all the use cases with their information + the usecase progress for each use case. Usecase model: class Usecase(models.Model): usecase_id = models.CharField(primary_key=True, max_length=20) usecase_name = models.CharField(max_length=256) user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email') usecase_type = models.ForeignKey('UsecaseType', models.DO_NOTHING) kpi = models.ForeignKey(Kpi, models.DO_NOTHING) business_owner = models.ForeignKey(BusinessOwner, models.DO_NOTHING) usecase_description = models.CharField(max_length=5000) usecase_creation_date = models.DateField() estimated_date = models.DateField() usecase_priority = models.CharField(max_length=100) usecase_git = models.CharField(max_length=512, blank=True, null=True) current_phase = models.ForeignKey(Phase, models.DO_NOTHING) delivery_date = models.DateField() class Meta: managed = False db_table = 'usecase' usecase progress model: class UsecaseProgress(models.Model): usecase_progress_date = models.DateTimeField(primary_key=True) usecase = models.ForeignKey(Usecase, models.DO_NOTHING, related_name='usecaseids') phase = models.ForeignKey(Phase, models.DO_NOTHING) pipeline = models.ForeignKey(Pipeline, models.DO_NOTHING) usecase_progress_value = models.IntegerField() estimated_date_delivery = models.DateField(db_column='Estimated_Date_Delivery') My views.py: @user_login_required def view_usecase(request): usecase_details = Usecase.objects.all() context = {'usecase_details': usecase_details} return render(request, 'ViewUsecase.html', context) My template: {% extends 'EmpDashboard.html' %} {% block body %} {% if usecase_details is not none and usecase_details %} <div class="col-12 mb-4"> {% for result in usecase_details %} <div class="card border-light shadow-sm components-section d-flex "> <div class="card-body d-flex "> <div class="row mb-4"> <div class="card-body"> <div class="row col-12"> <form> <div class="mb-4"> <h6 class="fs-5 fw-bold mb-0 border-bottom pb-3">{{result.usecase_id}} - {{result.usecase_name}}</h6> <div class="mb-0 mt-2">{{result.usecase_description}}</div> </div> <div class="form-row … -
Why can't I access start_utc? All I want to do is print it once the serializer is initialized
See code Here PROBLEM: def start_utc() -> datetime: return timezone.make_aware( datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0), timezone.utc ) def get_serializer_context(self): print(self.start_utc()) # start_utc() takes 0 positional arguments but 1 was given The error I'm getting when I run this is: start_utc() takes 0 positional arguments but 1 was given I tried: def start_utc(self) print(self.start_utc(self) Nothing worked so far -
Can't see my tables in Google Cloud SQL (PGSQL) but connection is ok
I am developing an application. Everything was going well locally, I now want to create a first postgre SQL database and connect it to django. I established the connection in the Django settings and perform the migrations, it's ok. But I don't see anything on the google cloud SQL console (I have the correct permissions). However, the tables were created, I see it thanks to the VSCODE extension. here's some informations settings.py [...] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PWD'), 'HOST': 'config('DB_HOST')', 'PORT': '5432', 'OPTIONS': { 'sslmode': 'verify-ca', #leave this line intact 'sslrootcert': os.path.join(BASE_DIR, config('CERT_SERVEUR')), "sslcert": os.path.join(BASE_DIR, config('CERT_CLIENT')), "sslkey": os.path.join(BASE_DIR, config('CERT_KEY')), } } } [...] I can see my tables, in my database, in my instance staging-01 But in my Google console, I don't see anything and I can only "delete" my database I configured my IP address in Public IP to test and I embed the certificates. Migrations and table creation seem to be ok. I don't know much about networking. and for example, when I try to create a user with Djoser, I have an error: net::ERR_CONNECTION_REFUSED. Everything was going well locally. I continue to launch with manage.py runserver but I would … -
Primary Key varchar - no detection of model changes
PostgreSql database, Django 4. I have a problem with detecting data model changes to a migration file. I am trying to add my primary key of type varchar which has format dddddd-ddd in the model. The field definition itself looks like this : mid = models.CharField(max_length=10, primary_key=True, verbose_name='custom ID'), Unfortunately, after creating the migration file, you can't see the mid field, but there is an id. To test the correctness of the makemigrations itself, I added the phone1 field, which is already detected and has coverage in the migration. Here is my model class Report(ModelBaseClass): mid = models.CharField(max_length=10, primary_key=True, verbose_name='custom ID'), created_user = models.ForeignKey(User, on_delete=models.PROTECT, editable=False, verbose_name='Przyjmując') client = models.ForeignKey(Client, on_delete=models.PROTECT, verbose_name='Klient') email = models.EmailField(null=True, blank=True, verbose_name='E-mail') phone = models.CharField(max_length=20, null=True, blank=True, verbose_name='Telefon') phone1 = models.CharField(max_length=20, null=True, blank=True, verbose_name='Telefon') comment = models.TextField(max_length=1000, blank=True, verbose_name='Uwagi do zgłoszenia') registration_date = models.DateField(auto_now_add=True, verbose_name='Data przyjęcia') ending_date = models.DateTimeField('Data zakończenia', null=True, blank=True) And an excerpt from the migration file. migrations.CreateModel( name='Report', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_date', models.DateTimeField(auto_now_add=True)), ('modified_date', models.DateTimeField(auto_now=True)), ('email', models.EmailField(blank=True, max_length=254, null=True, verbose_name='E-mail')), ('phone', models.CharField(blank=True, max_length=20, null=True, verbose_name='Telefon')), ('phone1', models.CharField(blank=True, max_length=20, null=True, verbose_name='Telefon')), ('comment', models.TextField(blank=True, max_length=1000, verbose_name='Uwagi do zgłoszenia')), ('registration_date', models.DateField(auto_now_add=True, verbose_name='Data przyjęcia')), ('ending_date', models.DateTimeField(blank=True, null=True, verbose_name='Data zakończenia')), ('client', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='organize.client', verbose_ … -
Passing two arguments in reverse
return HttpResponseRedirect(reverse("listing", args=[auction_id, commentForm])) The path in urls.py is: path("<int:auction_id>/listing", views.listingPage, name="listing"), The listingPage definition function: def listingPage(request, auction_id, commentForm = None): My experience throws this error: NoReverseMatch at... Reverse for 'listing' with arguments '(3, )' not found. 1 pattern(s) tried: ['(?P<auction_id>[0-9]+)/listing\Z'] I have no problem passing 1 arg: return HttpResponseRedirect(reverse("listing", args=[auction_id,])) -
python/ Django values_list is not returning all values
I have this bit of ugly code that is producing what I want. It's working but only necessary because what I would like to do with values_list is not working. member_channels = Channel.objects.filter(Q(members=request.user) | Q(owner=request.user)).prefetch_related('members').prefetch_related('owner') members_nested = list(map(lambda channel: channel.members.all(), member_channels)) members = list(dict.fromkeys(itertools.chain(*members_nested))) owners = list(map(lambda channel: channel.owner, member_channels)) # this is all the user's who's comment's the request.user should be able to see. valid_comment_users = list(dict.fromkeys(members + owners)) What I would like to do and should work is: member_channels = Channel.objects.filter(Q(members=request.user) | Q(owner=request.user)).prefetch_related('members').prefetch_related('owner') member_ids = member_channels.values_list('members', 'owner', flat=True) valid_comment_users = AppUser.objects.filter(id__in=member_ids).distinct() The issue is that with values_list I'm not getting all the members for each Channel in the members_channels it seems like it's only returning the members that are the same in all channels, or maybe just the first member I can't tell. Any insight into why values_list isn't working for this? -
How to remove all duplicates and similiar quieries from Django admin
I have a lot different models in my project and in every of them there`s a duplicated sql quieries I want to know how to remove them but the main problem is that in one model when im trying to take a look on single object of this model i have like 5k sql queries I also tried to for loop all of information from this model in my template and still got ~5k queires how does it work? models.py class PresenceSectionList(models.Model): presence_detail = models.ForeignKey(PresenceDetailInfo, on_delete=models.CASCADE) presence_sections = models.ForeignKey(CleanSections, blank=True, on_delete=models.CASCADE, null=True) class Meta: verbose_name = 'Раздел с информацией' verbose_name_plural = 'Разделы с информацией' ordering = ['presence_detail', ] def __str__(self): return f'{self.presence_detail}' admin.py class PresenceSectionListAdmin(admin.ModelAdmin): list_display = ('presence_detail', 'presence_sections') ordering = ['presence_detail__presence_info', 'presence_detail__work_date'] admin.site.register(PresenceSectionList, PresenceSectionListAdmin) Amount of sql queries -
error: Pandas requires version '1.4.16' or newer of 'sqlalchemy' (version '0.9.8' currently installed)
I am using sqlalchemy to access my sql database and making changes in sql database, the code for the requirement is: output_db_engine=create_engine( "mssql+pymssql://{user}:{pw}@{ip}/{db}".format( user=PORTAL_DB_USERNAME, pw=urllib.parse.quote_plus(PORTAL_DB_PASSWORD), db=smartsearch_db_name, ip=smartsearch_db_ip ) ) final_df.insert(loc=0, column='Id', value=np.arange(1, len(final_df) + 1)) final_df.to_sql('Smart_Search_Table', con=output_db_engine, chunksize=900, method='multi', if_exists='replace', index=False) # Making Id column as Primary Key in table with output_db_engine.connect() as con: con.execute('ALTER TABLE ' + 'Smart_Search_Table' + ' ALTER COLUMN Id INT NOT NULL') con.execute('ALTER TABLE ' + 'Smart_Search_Table' + ' ADD PRIMARY KEY (Id);') print( f"SUCCESS : Table with name Smart_Search_Table is created and loaded with new data " ) return final_df if __name__ == "__main__": i = making_table() i.making_final_df() But i am getting an error: ImportError: Unable to find a usable engine; tried using: 'sqlalchemy'. A suitable version of sqlalchemy is required for sql I/O support. Trying to import the above resulted in these errors: Pandas requires version '1.4.16' or newer of 'sqlalchemy' (version '0.9.8' currently installed). Can anyone help me to resolve this error? I am also getting a warning: A NumPy version >=1.16.5 and <1.23.0 is required for this version of SciPy (detected version 1.24.1 warnings.warn(f"A NumPy version >={np_minversion} and <{np_maxversion}". I am new to python, can anyone help me how to resolve … -
NoReverseMatch at /en/dashboard/server-request/
Reverse for 'edit_server_request' with arguments '(2,)' not found. 1 pattern(s) tried: ['en/dashboard/edit-server-request/int:pk'] the edit and delete button on the template below raises the error: <td> <a class="edit-button" href="{% url 'dashboard:edit_server_request' user.server_user.pk %}">{% trans 'Edit' %}</a> <a class="delete-button" href="{% url 'dashboard:delete_server_request' user.server_user.pk %}">{% trans 'Delete' %}</a> </td> views.py def edit_server_request(request, pk): server_request = get_object_or_404(ServerRequest, pk=pk) if request.method == "POST": form = ServerRequestForm(request.POST, instance=server_request) if form.is_valid(): form.save() return redirect('server_request_list') else: form = ServerRequestForm(instance=server_request) context = {'form': form} return render(request, 'dashboard/school/edit_server_request.html', context) def delete_server_request(request, pk): server_request = get_object_or_404(ServerRequest, pk=pk) server_request.delete() return redirect('server_request_list') urls.py url(r'edit-server-request/<int:pk>', school_views.edit_server_request, name='edit_server_request'), url(r'delete-server-request/<int:pk>', school_views.delete_server_request, name='delete_server_request') edit and delete url raises the error -
Getting user name in the access token response in Django
I have integrated google social auth in my django + react.js project. I am using the access token that I am getting from google to call this url 'http://localhost:8000/auth/convert-token'. This is giving me a json response which contains the access-token and the refresh-token. However I want to add the user name in that json response as well. I tried using request.user.username. But it is not giving me anything. I guess it is because by the time the call is made the for aforementioned URL, the request doesn't have any value for the currently logged in user. Can you suggest me any way to get the username. Following is my code. @api_view(["POST"]) def googleSignIn (request): print(request.headers.get("token")) resposnePayload = {} # token obtained from google token = request.headers.get("token") clientId = "<client-id for django app>" clientSecret = "<client-secret for django app>" url = 'http://localhost:8000/auth/convert-token' header = { "Content-Type": "application/x-www-form-urlencoded" } payload = { "grant_type": 'convert_token', "client_id" : clientId, "client_secret" :clientSecret, "backend":"google-oauth2", "token":token } result = requests.post(url,data=payload,headers = header) resopnsePayload=result.json() print("currently logged in user is ",request.user.username) return Response(resopnsePayload,status=result.status_code) -
Django admin: Geometry Widget not showing up for view permission on the model
The GEO MAP for the geometry field doesn't show up for the user having only View Permission on the model. Instead the geometry field value gets displayed in a text format, something like this: SRID=4326;POLYGON ((82.071... Is there any way workaround for this problem? -
Adding Role option in django.contrib.auth.models.User
As of now, I am storing username, password in User object which I import from "django.contrib.auth.models". Now, I am also sending 'role' attribute in POST request and it should add 'role' in User as well. I have seen multiple posts, but not able to understand role part. Some posts says, use some Groups, not clear how to use them. I just have to store role attribute in User of django.contrib.auth.models. POST body will be something like this: {"username":"name22","password":"$pwd1234","password2":"$pwd1234", "role": "admin" } Using below code: serializers.py: from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password class RegisterSerializer(serializers.ModelSerializer): username = serializers.CharField(required=True) password = serializers.CharField(write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('username', 'password', 'password2') def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError({"password": "Password fields didn't match."}) return attrs def validate_username(self, value): if User.objects.filter(username__iexact=value).exists(): raise serializers.ValidationError("A user with this username already exists.") return value def create(self, validated_data): user = User.objects.create( username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user` Want to understand , if "role" = "Customer" also comes in POST request, then how to store this role in above User object. I checked multiple posts, but all seems to handle complex cases. In my case, … -
Django could not build wheels for backports.zoneinfo error
ModuleNotFoundError: No module named 'backports.zoneinfo not install pip3 install backports.zoneinfo==0.2.1 error Building wheels for collected packages: backports.zoneinfo Building wheel for backports.zoneinfo (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for backports.zoneinfo (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [43 lines of output] /tmp/pip-build-env-mlqbnavt/overlay/lib/python3.10/site-packages/setuptools/config/setupcfg.py:520: SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use license_files instead. warnings.warn(msg, warning_class) running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-310 creating build/lib.linux-x86_64-cpython-310/backports copying src/backports/init.py -> build/lib.linux-x86_64-cpython-310/backports creating build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/_zoneinfo.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/init.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/_common.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/_version.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/_tzpath.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo running egg_info writing src/backports.zoneinfo.egg-info/PKG-INFO writing dependency_links to src/backports.zoneinfo.egg-info/dependency_links.txt writing requirements to src/backports.zoneinfo.egg-info/requires.txt writing top-level names to src/backports.zoneinfo.egg-info/top_level.txt reading manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no files found matching '.png' under directory 'docs' warning: no files found matching '.svg' under directory 'docs' no previously-included directories found matching 'docs/_build' no previously-included directories found matching 'docs/_output' adding license file 'LICENSE' adding license file 'licenses/LICENSE_APACHE' writing manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' copying src/backports/zoneinfo/init.pyi -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/py.typed -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo running build_ext building 'backports.zoneinfo._czoneinfo' extension creating build/temp.linux-x86_64-cpython-310 creating build/temp.linux-x86_64-cpython-310/lib x86_64-linux-gnu-gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -fPIC -I/var/www/vhosts/arbitrage/myvenv/include -I/usr/include/python3.10 -c lib/zoneinfo_module.c -o … -
Django: how to filter with exact same count?
Let's say I have a group of id's : [1, 2, 87] I want to get all the User who have those exact addresses, not the User that might have those addresses and more. So if I do a request like this, I might have User that have those addresses and more: User.objects.filter(addresses__in=[1, 2, 87]) With this code, I might get a User who has those addresses, for example [1, 2, 87, 724, 725]. This is not what I want! Is there a way to get only those who have exactly the those 3 addresses, no more? -
How to implement PDF file upload feature using django rest framework and MySQL?
I'm making Website using Next.Js(v13.1.6) as frontend and Django REST Framework(v3.14.0, django:v4.1.6) as backend, AWS RDS MySQL as Database. I want to make user upload and download pdf in client. How to implement this feature in backend? I heard that when saving static file(like image file) in django, usally use S3 as storage to be efficient. Is it the same when saving a pdf file? I want to know is it okay saving pdf file just in mysql without s3. I want to make user upload and download pdf in client. How to implement this feature in backend? I want to know is it okay saving pdf file just in mysql without s3 in django. -
Facing error in django-microsoft-authentication
I am facing key error, access_key no found This is the error which I am facing Refering this documentation https://pypi.org/project/django-microsoft-authentication/ These are my configuration: Settings.py DEBUG = True INSTALLED_APPS = [ ... 'microsoft_authentication', ] LOGIN_URL = 'login' LOGIN_REDIRECT_URL = 'home' MICROSOFT = { "app_id": "...", "app_secret": "...", "redirect": "http://localhost:8000/microsoft_authentication/callback/", "scopes": ["user.read"], "authority": "https://login.microsoftonline.com/common", "valid_email_domains": ["<list_of_valid_domains>"], "logout_uri": "http://localhost:8000/logout" } MICROSOFT_CREATE_NEW_DJANGO_USER = False urls.py urlpatterns = [ path('admin/', admin.site.urls), ... path('microsoft_authentication/', include('microsoft_authentication.urls')), ] In Azure portal, I created an app, and client secret. and gave correct credentials in settings.py I have sepcified redirect uri's as: http://localhost:8000/microsoft_authentication/callback/ In my login page, I gave correct Url <a href="{% url 'microsoft_authentication:microsoft_authentication_login' %}">Login With Microsoft</a> It is asking to enter email, password. After entering, I am facing the error. Someone help with it.