Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
after changing a user password then the session got flushed
when i changed user password the user becomes anonymous means the session get flushed after.How to solve this issue. Why this happens when the password changed. the url has given below path('psswdReset/',psswdReset, name = 'psswd_reset') def psswdReset(request): if request.method == 'POST': new_psswd = request.POST.get('new_psswd') psswd = request.POST.get('psswd') password_is_correct = check_password(psswd, request.user.password) if password_is_correct: user = CustomUser.objects.get(id=request.user.id) user.password = make_password(new_psswd) user.save() messages.success(request, 'Password changed successfully!') return render(request,'User/userPsswdReset.html',{}) print('anonymouse', request.user.is_anonymous) return render(request,'User/userPsswdReset.html',{}) -
request.user always returns Anonymous user, even though request.META gives proper token when decoded in JWT it gives user_id
settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', "allauth.account.auth_backends.AuthenticationBackend", ] views.py def google_login_view(request): if not request.user.email: return HttpResponse("An email is required to login.", status=400) email_from_google = request.user.email try: user = User.objects.get(email=email_from_google, is_active=True) user_details = UserDetails.objects.get(email=email_from_google, is_active=True) except (User.DoesNotExist, UserDetails.DoesNotExist): return HttpResponse("User not found. Please register.", status=404) # generate_token_pair is defined in tokens.py access_token, refresh_token, access_token_exp, refresh_token_exp = generate_token_pair(user) current_time = datetime.now() access_token_expiration_timestamp = access_token_exp.timestamp() access_token_expiration_datetime = datetime.fromtimestamp(access_token_expiration_timestamp) # Check if the access token has expired if access_token_expiration_datetime < current_time: # Check if the refresh token is still valid if refresh_token_exp >= current_time: with transaction.atomic(): new_access_token, _, new_access_token_exp, _ = generate_token_pair(user) user.access_token = new_access_token user.save() # Log the user back in with the new access token login(request, user, backend='allauth.socialaccount.providers.google.backends.GoogleOAuth2') redirect_url = f"{settings.FRONTEND_REDIRECT_URL}?access_token={new_access_token}" return redirect(redirect_url) else: logout(request) # Ensure the user is logged out return redirect(settings.LOGIN_URL) else: login(request, user, backend='allauth.socialaccount.providers.google.backends.GoogleOAuth2') redirect_url = f"{settings.FRONTEND_REDIRECT_URL}?access_token={access_token}" return redirect(redirect_url) @authentication_classes([JSONWebTokenAuthentication]) @api_view(['POST']) def send_client_feedback_email(request, project_id): try: pass I have above setup Now when I Add PDB set trace in google login view I get a request.user of current logged in user. Now when I try to use my POST METHOD and when I add request.user It returns Anonymous … -
Plotting a bargraph in django using matplotlib
so here is my code. The bargraph is not showing in the dashboard page. This is my views.py code. expenses = Expense.objects.filter(user=user) incomes = Income.objects.filter(user=user) expense_date_list=[] amount_list=[] for expense in expenses: expense_date=expense.date.strftime("%Y-%m-%d") amount=expense.amount expense_date_list.append(expense_date) amount_list.append(amount) data=plt.bar(expense_date_list, amount_list) fig=plt.gcf() buf=io.BytesIO() fig.savefig(buf, format='png') buf.seek(0) data=urllib.parse.quote(base64.b64decode(buf.read())) context = { 'expenses': expenses, 'incomes': incomes, 'user':user, 'data':data`} return render(request, 'dashboard.html', context) -
Django:TemplateDoesNotExist at /accounts/login/
accounts/models.py from django.db import models from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms # Create your models here. class UserCreateForm(UserCreationForm): email = forms.EmailField(required=True,label='email',error_messages={'exists':'This already exists'}) firstname = forms.CharField(required=True,label='firstname') lastname = forms.CharField(required=True,label='lastname') class Meta: model = User fields = ('firstname','lastname','username','email','password1','password2') def __init__(self, *args, **kwargs): super(UserCreateForm, self).__init__(*args, **kwargs) self.fields['firstname'].widget.attrs['placeholder'] = 'First Name' self.fields['lastname'].widget.attrs['placeholder'] = 'Last Name' self.fields['username'].widget.attrs['placeholder'] = 'Username' self.fields['email'].widget.attrs['placeholder'] = 'Email' self.fields['password1'].widget.attrs['placeholder'] = 'Password' self.fields['password2'].widget.attrs['placeholder'] = 'Confirm Password' def save(self, commit=True): user = super(UserCreateForm,self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user def clean_email(self): if User.objects.filter(email=self.cleaned_data['email']).exists(): raise forms.ValidationError(self.fields['email'].error_messages['exists']) return self.cleaned_data['email'] accounts/views.py from django.shortcuts import render # Create your views here. from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User, auth from accounts.models import UserCreateForm from django.http import JsonResponse import random from django.core.mail import send_mail from django.conf import settings def registerpage(request): if request.method == 'POST': #login form = UserCreateForm(request.POST) if form.is_valid(): new_user = form.save() new_user = authenticate( username = form.cleaned_data['username'], password = form.cleaned_data['password1'], ) login(request, new_user) return redirect('home') else: #registration form = UserCreateForm() context = {'form':form} return render(request, 'store/auth/register.html', context) accounts/urls.py from django.urls import path,include from . import views urlpatterns = [ path('register', views.registerpage, name='register'), path('', … -
Need Help {{ Can't install mysql client }}
I'm just beginner for codeing and i try to connect Django with Mysql. But When i pip install myslqclient it error code below : ERROR: Command errored out with exit status 1: command: 'c:\users\admin\envs\envdjango\scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-ktopnk4j\\mysqlclient_9607a86bf5aa4a55ac82c8bd2f6752ec\\setup.py'"'"'; __file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-ktopnk4j\\mysqlclient_9607a86bf5aa4a55ac82c8bd2f6752ec\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Admin\AppData\Local\Temp\pip-wheel-e994nvxe' cwd: C:\Users\Admin\AppData\Local\Temp\pip-install-ktopnk4j\mysqlclient_9607a86bf5aa4a55ac82c8bd2f6752ec\ Complete output (23 lines): running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.6 creating build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.6\MySQLdb creating build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.6\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ ERROR: Failed building wheel for mysqlclient Running setup.py clean for mysqlclient Failed to build mysqlclient Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'c:\users\admin\envs\envdjango\scripts\python.exe' -u -c 'import io, … -
List Data from Multiple Models in Single HTML Table
I am trying to render data from 3 models in single html table. I have tried an error few times but failed. Below is my code. The workstation, printer and laptop have foreign of site ID. I want to list all the workstation, laptop and printer filter by a site. Below is my code: Models: class Site(models.Model): site_name = models.CharField(max_length=30, blank=True, null=True, verbose_name="Site Name") site_address = models.CharField(max_length=30, blank=True, null=True, verbose_name="Site Address") def __str__(self): return self.site_name class Workstation(models.Model): name = models.CharField(max_length=30, blank=True, null=True, verbose_name="Workstation Name") serial = models.CharField(max_length=30, blank=True, null=True, verbose_name="Serial") workstation_model = models.CharField(max_length=30, blank=True, null=True, verbose_name="Workstation Model") sitename = models.ForeignKey(Site, on_delete=models.SET_NULL, blank=True, null=True, verbose_name="Site") def __str__(self): return self.name class Laptop(models.Model): name = models.CharField(max_length=30, blank=True, null=True, verbose_name="Laptop Name") serial = models.CharField(max_length=30, blank=True, null=True, verbose_name="Serial") laptop_model = models.CharField(max_length=30, blank=True, null=True, verbose_name="Laptop Model") sitename = models.ForeignKey(Site, on_delete=models.SET_NULL, blank=True, null=True, verbose_name="Site") def __str__(self): return self.name class Printer(models.Model): name = models.CharField(max_length=30, blank=True, null=True, verbose_name="Printer Name") serial = models.CharField(max_length=30, blank=True, null=True, verbose_name="Serial") printer_model = models.CharField(max_length=30, blank=True, null=True, verbose_name="Printer Model") sitename = models.ForeignKey(Site, on_delete=models.SET_NULL, blank=True, null=True, verbose_name="Site") def __str__(self): return self.name URL: urlpatterns = [ path('', views.SiteView.as_view(), name='site'), path('report/<sitename>', views.ReportView.as_view(), name='reportview'), ] Template 1: Site List <table> <tr> <th>Site</th> <th>Address</th> </tr> {% for site in site_list %} … -
Django join two or three models class into get request
models.py class CMDBInstanceProduct(models.Model): name = models.CharField(primary_key=True, max_length=50) def __str__(self): return self.name class CMDBStatus(models.Model): name = models.CharField(primary_key=True, max_length=50) def __str__(self): return self.name class Instance(models.Model): cmdbid = models.CharField(primary_key=True, max_length=15]) name = models.CharField(max_length=100) product = models.ForeignKey(CMDBInstanceProduct, on_delete=models.CASCADE) status = models.ForeignKey(CMDBStatus, on_delete=models.CASCADE) def __str__(self): return self.cmdbid class Instance_account(models.Model): fk_instance = models.ForeignKey(Instance, on_delete=models.CASCADE) name = models.CharField(max_length=200) views.py @api_view(('GET',)) def accountlist(request): accountlists = Instance_account.objects.all().prefetch_related('fk_instance') dict = {} records=[] for account_list in accountlists: list = {"name":account_list.name,"ci_name": account_list.fk_instance.ci_name ,"product": account_list.fk_instance.product} print (list) records.append(list) dict["pickup"]=records return JsonResponse(dict) my print(list) {'name': 'accountnameinstance', 'ci_name': 'MKZSQLT99_PROD1', 'product': <CMDBInstanceProduct: MS-SQL Instance>} {'name': 'accountname', 'ci_name': 'MKZSQLT99_PROD1', 'product': <CMDBInstanceProduct: MS-SQL Instance>} {'name': 'shareacc', 'ci_name': 'MKZSQLT99_PROD1', 'product': <CMDBInstanceProduct: MS-SQL Instance>} i get an error TypeError: Object of type CMDBInstanceProduct is not JSON serializable Anyone could help on this to solve JSON serializable? -
Django - is there a way to shuffle and run only a subset of tests?
We are using Django with tests. We have in total about 6,000 tests which take about 40 minutes to run. Is there a way to shuffle the tests and run only 200 (randomly chosen) tests? This should be done with a command line parameter with the number 200 (which may change), since usually we run all the tests. -
Passing image to email in Django
I am attempting to send an email with a image embedded in the html code. I have verified that the image is being accessed but, I'm not able to see the image when I get the email. Trigger In Views: try: logo = base64.b64encode(open("dashboard/static/assets/abc.png", "rb").read()).decode() current_site = get_current_site(request) mail_subject = 'Welcome to AV Support' message = render_to_string('activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), 'logo':logo }) plain_message = strip_html(message) email = send_mail( mail_subject, message=plain_message,html_message=message, recipient_list=[ user.email], from_email=settings.EMAIL_HOST_USER ) email print('EMAIL SENT') except Exception as e: print('NO EMAIL SENT') print(e) Passing Logo To Email: <img src="data:dashboard/static/assets/abc.png;base64,{{logo}}" width="250" height="50" /> I have verified that the "logo" has data and the file is in the directory, the email comes up with a blank space. Could someone tell me what needs to be done? -
D5RF - Display something in HTML format before processing API requests
Django 5 - Rest Framework I am building a Django REST API project. I am currently dealing with a request that takes so long to process. I want to know if I could display something like an HTML Response before the request is processed, or just like a text saying: Loading... Please wait. Here is my code: from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView class SomeView(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def get(self, request): # I wanted to display it here. # ----------------- # Some process here # ----------------- # And then the actual response of the process. return Response(response, status=status.HTTP_200_OK) Any help would be appreciated, thank you. -
Usage of 'DIRS' attributes of TEMPLATES and static files in Django
I am new to Django and back-end development in a general. I am currently trying to build a very simple app. I saw some tutorials and am a little bit confused about 2 things: 1. What is the use of the attributes DIRS below in the picture. I knew that it was somehow used for "registering" templates but in my own apps, I didn't register it and somehow it still worked normally. Here is the picture of my settings.py and overall structure of my project: Project screenshot 2. What does it mean to "deploy" static files and why is it a better way than let Django automatically "deploy" the files by itself? (see picture below) Django docmumentation - https://docs.djangoproject.com/en/5.0/howto/static-files/ I really appreciate any thorough explanation on how things work since I am a beginner. I would be grateful if you guys provide any resources for Django practice as well! -
creating Event Loop scoped object (singleton) shared between coroutines Python
I want to create and store a singleton object such that, the variable necessarily has different object for different event loops (running concurrently) and for a single event loop, all coroutines executing inside the eventloop shares the same object. (what i want is contextVars which operate at the event loop scope. cannot use contextVars as coroutines have different contexts and hence different objects.) I do not control creation of event loops. I only have access to a coroutine (async def func()) executing inside an eventloop. Usecase: I am running a django server on gunicorn with uvicorn worker (afaik, different requests can run concurrently on the same worker at any time, but with differnet event loops). I want to share a connection pool, and the connection pool implementation binds itself to an eventloop (usage of asyncio lock, condition and queue) ), making global-variable like singleton erroneous. There are some other hacky solutions, like attaching the singleton to the request object, or attaching the singleton to the current event loop object, but the requirement seems like a fundamental usecase, and hopefully python has thought about it and solved the same. -
I can't get DRF-Spectactular to generate OpenApiParameter values for functions, only classes
Currently I'm working on a django project and I have an api_views.py file with the following view function: @api_view(["GET"]) @extend_schema( parameters=[ OpenApiParameter( name="jurisdiction", description="City for the query", required=True, type=str, default="Boston" ), ], description='More descriptive text', responses={200: OpenApiTypes.OBJECT}, # Define your response schema ) def distinct_address_autocomplete(request: Request): jurisdiction = request.GET.get("jurisdiction", "Boston") # Get distinct addresses for the city addresses = get_distinct_addresses(jurisdiction) # Filter addresses based on user's query filtered_addresses = addresses # Implement your filtering logic return Response(filtered_addresses) I've got it all set up correctly in all the settings.py and urls.py because it shows up in swagger, but incorrectly. The OpenApiParameter doesn't show up at all, it looks like this: But when I refactor this as a class like so: class DistinctAddressAutocompleteView(APIView): @extend_schema( parameters=[ OpenApiParameter( name="jurisdiction", description="City for the query", required=True, type=str, default="Boston" ), ], description='More descriptive text', responses={200: OpenApiTypes.OBJECT}, # Define your response schema ) def get(self, request: Request): jurisdiction = request.GET.get("jurisdiction", "Boston") # Get distinct addresses for the city addresses = get_distinct_addresses(jurisdiction) # Filter addresses based on user's query filtered_addresses = addresses # Implement your filtering logic return Response(filtered_addresses) The parameter shows up! What am I doing wrong on the function view? As best I can tell, I've set … -
Aggregate of OuterRef in Django Subquery
I have the following two models in Django 4.2: class Team(Model): members = ManyToManyField(...) ... class Size(Model): max_members = PositiveSmallIntegerField(blank=True, null=True) class Meta: ordering = [F('max_members').asc(nulls_last=True)] The idea is that each Team has a Size but I can't (as far as I know) model this as a SQL relation. But that's OK, we can get the size of a team as follows: Size.objects.filter(Q(max_members=None) | Q(max__gte=team.members.count())).first() However if I want to get the size associated with an entire queryset of teams at once, I am stuck. It seems like the following should work: teams.annotate( size=Subquery( Size.objects.filter( Q(max_members=None) | Q(max_members__gte=Count(OuterRef('members'))) ).values('pk')[:1] ) ) But this produces invalid SQL (we are using PostGres): SELECT "teams_team".* (SELECT U0."id" FROM "teams_size" U0 HAVING (U0."max_members" IS NULL OR U0."max_members" >= (COUNT("teams_teammembers"."user_id"))) ORDER BY U0."max" ASC NULLS LAST LIMIT 1) AS "size" FROM "teams_team" LEFT OUTER JOIN "teams_teammembers" ON ("teams_team"."id" = "teams_teammembers"."team_id") This is missing a GROUP BY teams_team.id and the HAVING clause should be WHERE. I can get some of the way there with some hacking: if I swap Count for Func(..., function='COUNT') then Django doesn't realise there is any aggregation and keeps the WHERE clause as it should do. But adding the grouping by hand, … -
pytest-django access to db when using pytest_generate_tests
Is there a way to be able to indirectly generate parameters via a database query when using pytest-django. For example if I have the following: Some code from here. pytestmark = pytest.mark.django_db def pytest_generate_tests(metafunc): if "foo" in metafunc.fixturenames: metafunc.parametrize("db", Foo.objects.filter(bar=1), indirect=True) def test_foo(load_all_foo, foo): # do things with all foo and test I am not sure what the deferred parametrization means here. Looking at code, pytest as well as pytest-django was not quite helpful. In the link above the example is still using an initial static list of params which then get converted to an actual db object. Where it would be useful to me is when I have a test that has a large setup and teardown time, plus the list of Foos can change and ocassionally fail. However rather than stopping and exiting when a test with one specific Foo fails I would like to continue and see the failed one in the report. I could sort of call metafunc.parametrize with an array of Nones and then yield a Foo in another fixture but that's not really a test. Any help would be greatly appreciated. -
Django BMI calculator not showing results
I'm trying to create a simple BMI calculator in django and for the life of me I cannot figure out why the app doesn't show the result after I press the "calculate" button. Does anyone have any insights on why this may be? views.py def calculate(response): if response.method == "POST": form = BMIform(response.POST) if form.is_valid(): weight = form.cleaned_data["weight"] height = form.cleaned_data["height"] bmi = weight / height ** 2 return render(request, "main/calculate.html", {"form": form, "bmi": bmi}) else: form = BMIform return render(response, "main/calculate.html", {"form": form}) models.py class BMImodel(models.Model): weight = models.FloatField() height = models.FloatField() def bmi(self): return weight / height ** 2 forms.py class BMIform(ModelForm): weight = forms.FloatField() height = forms.FloatField() class Meta: model = BMImodel fields = "__all__" html file for the calculations {% extends 'main/base.html' %} {% block content %} <h1><center>Calculate your BMI</center></h1> <style> .btn-primary { background-color: rgb(82, 200, 216); color: black; border: none; } .btn-primary:hover { background-color: rgb(0, 128, 145); color: white); } </style> {% csrf_token %} {{ form }} <div class="form-group col-md-4"> <button type="submit" name="calculate" class="btn btn-primary">Calculate</button> </div> {% if bmi %} <div class="form-group col-md-4"> <h5>BMI: {{bmi}}</h4> </div> {% endif %} </form> {% endblock %} I tried following several different tutorials but got lost somewhere along the … -
Filter blog posts using Category name with space in django
I have a website project in django with a blog app in it, I have category model for posts for filtering posts by category, the problem is when category name has space in it like "web development" my code works fine in development on my system, but after I deploy it on host nothing shows for category names which has white space in it. Here my urls.py for blog app: from django.urls import path from blog.views import * app_name ='blog' urlpatterns = [ path('', blog_view, name='index'), path('category/<str:cat_name>', blog_view, name='category'), path('author/<str:username>', blog_view, name='author'), path('search/', blog_search, name='search'), path('tag/<str:tag_name>', blog_view, name='tag'), path('<int:pid>', blog_single, name='single'), ] And here my view.py: def blog_view(request, **kwargs): posts = Post.objects.filter(status=1, published_date__lte=timezone.now()) if kwargs.get('cat_name'): posts = posts.filter(category__name= kwargs.get('cat_name')) if kwargs.get('username'): posts = posts.filter(author__username= kwargs.get('username')) if kwargs.get('tag_name'): posts = posts.filter(tags__name__in= [kwargs.get('tag_name')]) posts = Paginator(posts, 3) try: page_number = request.GET.get('page') posts = posts.page(page_number) except PageNotAnInteger: posts = posts.get_page(1) except EmptyPage: posts = posts.get_page(1) context = {'posts': posts} return render(request, 'blog/blog-home.html', context) I don't know what's happening on host but on localhost this request works fine and shows posts in that category: http://127.0.0.1:8000/blog/category/Web%20Development but on host the query doesn't work. Thanks -
Django on CPanel, can't install requirements.txt
I am trying to publish a Django web-application using CPanel. I created the python application but when I tried to install requirements.txt (using python version 3.8.18), I get tput: No value for $TERM and no -T specified error: subprocess-exited-with-error × Preparing metadata (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata.╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. This is my requirements.txt asgiref==3.5.1 attrs==20.3.0 cachetools==5.3.0 certifi==2021.10.8 cffi==1.15.0 charset-normalizer==2.0.12 cryptography==37.0.2 defusedxml==0.7.1 device-detector==5.0.1 distlib==0.3.4 Django==4.0.4 django-allauth==0.52.0 django-cors-headers==3.13.0 django-filter==22.1 django-user-agents==0.4.0 djangorestframework==3.13.1 filelock==3.7.1 geonamescache==1.5.0 google-auth==2.16.0 google-auth-httplib2==0.1.0 google-auth-oauthlib==0.8.0 httplib2==0.21.0 idna==3.3 jellyfish==0.9.0 joblib==1.2.0 lib50==3.0.4 Markdown==3.3.7 markdown2==2.4.3 networkx==3.0 numpy==1.24.2 oauthlib==3.2.2 pbr==5.9.0 pexpect==4.8.0 Pillow==9.1.0 pipenv==2022.7.4 platformdirs==2.5.2 pomegranate==0.14.8 ptyprocess==0.7.0 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.21 pygame==2.2.0 PyJWT==2.6.0 pyparsing==3.0.9 python3-openid==3.2.0 pytz==2022.1 PyYAML==5.4.1 regex==2022.10.31 requests==2.27.1 requests-oauthlib==1.3.1 rsa==4.9 scipy==1.10.1 six==1.16.0 sqlparse==0.4.2 stevedore==4.0.0 submit50==3.1.1 termcolor==1.1.0 ua-parser==0.16.1 urllib3==1.26.9 user-agents==2.2.0 virtualenv==20.15.1 virtualenv-clone==0.5.7 virtualenvwrapper==4.8.4 whitenoise==6.4.0 I have previously published web apps using Django and CPanel. For some reason, it will not install this time. How can I make the packages install properly? -
MSAL - Multi-Tenant Web APP - aad.config.json
We have successfully gotten our Django + Nginx + MySQL web app hosted and auth working through Azure with O365 for mailing using graph & O365 EWS. We have two different redirect URI's 1 for a dev environment and the other for prod. Both seem to work fine with both being up at the same time. The issue we are running into is the AAD.config.json, I authorized and got all the way through MFA with the external tenant account. On the APP Registration in hosted tenant Azure/Entra it shows supported account types: multiple organizations and verified the Publisher with the MPN ID. Whenever I try logging in with External Tenant (user's added to User & groups with default access role assigned) AuthCanceled at /social-auth/complete/azuread-oauth2/ Authentication process canceled During handling of the above exception (400 Client Error: Bad Request for url: https://login.microsoftonline.com/common/oauth2/token), another exception occurred: Below is the aad.config.json taken from https://github.com/Azure-Samples/ms-identity-python-samples-common/blob/main/aad.django.config.json { "type": { "client_type": "CONFIDENTIAL", "authority_type": "MULTI_TENANT", "framework": "DJANGO" }, "client": { "authority": "https://login.microsoftonline.com/common/oauth2/token" }, "auth_request": { "redirect_uri": null, "scopes": [], "response_type": "code" }, "flask": null, "django": { "id_web_configs": "MS_ID_WEB_CONFIGS", "auth_endpoints": { "prefix": "auth", "sign_in": "sign_in", "edit_profile": "edit_profile", "redirect": "redirect", "sign_out": "sign_out", "post_sign_out": "post_sign_out" } } } -
When I run python manage.py test... only some of my tables / fields are created in the test db
In django, I am trying to run tests on a test db, but I can't seem to get the test db stood up properly... I have 226 models on my real db, but when I run python manage.py test (test location) it breaks pretty quickly referencing that a field is not present in the test db. psycopg2.errors.UndefinedColumn: column core_division.display_name does not exist A quick look at the test db (since it crashes, it doesn't teardown the db, so I can view it) shows only 47 tables created, and sure enough that particular field is not there. Below is my database settings in my config.settings.test file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myscore', 'USER': env('DEFAULT_DATABASE_USER'), 'PASSWORD': env('DEFAULT_DATABASE_PASSWORD'), 'HOST': 'localhost', 'PORT': '', 'TEST': { # 'MIRROR': 'default', 'SERIALIZE': False, # 'MIGRATE': False, } }, } What I tried to do as a workaround was apply the 'MIGRATE': False option. When I do this (with --keepdb applied), I see that the test db has 195 tables (and does have the field that wasn't created before). So this is better. No failures / crashes. However...I can't seem to write / read anything from the db and I'm not sure why... So...what I've … -
How to serialize request.user for ModelSerializer to auto fill the user field in Model?
This question is not good question but, I spent 6 hours to solve this problem, searching in stackoverflow and still problem is bother me. I have a model as below : class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=144, primary_key=True, unique=True) description = models.CharField(max_length=144) def __str__(self) -> str: return self.title and its serializer : class ProductSerailizer(serializers.ModelSerializer): class Meta: model = Product fields = "__all__" exclude = ["user"] and my view is like below : class CreateProduct(generics.GenericAPIView): """""" serializer_class = [ProductSerailizer] permission_classes = [permissions.IsAuthenticated] def perform_create(self, serializer): return self.serializer(user=self.request.user) def post(self, request, *args, **kwargs): user_serializer = UserSerializer(data=request.data) if user_serializer.is_valid(): user_serializer.save() return response.Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST) I wanna auto fill the user by the request, but when I send the request with postman it says : "username": [ "A user with that username already exists." ] and it doesn't save my instance. I don't know how to handle this. I wanna type this with generics. Can anyone help me out ? -
How do I display non field errors and field errors after I hit the submit form button for user sign up?
I would like to display Form.non_field_errors() and Form.errors upon submitting my form. It has email, password and confirm password fields. The thing is, I want all errors to show up if the inputs for these fields are wrong. (e.g. invalid email, passwords don't match). However, I am facing the issue that upon submission of my form when all fields are wrong, only the non_field_errors() show up first. Once that has been resolved and I clicked enter again, the field errors then show up. I don't want them to show up 1 by 1 and prefer that they show up altogether. Issue on my form (Only Enter a valid email address is showing up, no password errors when there should be upon submitting) Here's my code. forms.py class UserRegistrationForm(forms.ModelForm): password2 = forms.CharField( label="New password confirmation", widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), ) class Meta: model = User fields = [ "email", "password", ] def _validate_passwords(self, password1, password2): password_errors = [] try: validate_password(password1, self.instance) except ValidationError as e: password_errors.append( ValidationError(_("Weak password provided"), code="weak-password"), ) if password1 and password2 and password1 != password2: password_errors.append( ValidationError(_("Passwords mismatch"), code="password-mismatch"), ) if len(password_errors) > 0: raise ValidationError(password_errors) def clean(self): cleaned_data = super().clean() email = cleaned_data.get("email") password1 = cleaned_data.get("password") password2 = … -
My Python Django button is not appearing when someone logs in(it should be)
I am working on a Python Django project. I'm currently working on a way for myself to log in and create a product card for this project store. The create button should only appear when I am logged in. It's just not appearing. I go to Inspect the web page and I don't even see the code for my button. I have no idea what is happening and some help would be awesome! This is the block of code that should be producing said button. If the user is authenticated, it'll create this create button under each one of my categories. I originally had the for statement over the if statement and I switched it to see if that would change anything and nothing happened. HTML {% if user.is_authenticated %} {% for category in categories %} <p>User is authenticated: {{ user.username }}</p> <!--LINE FOR DEBUGGING--> <p>Category: {{ category.name }}</p> <!--LINE FOR DEBUGGING--> <a class="create_button" href="{% url 'create_product' category.id %}">Create {{ category.name }}</a> {% endfor %} {% endif %} One of the first things I did I was add some debugging lines to see if it actually understood I was logged in. HTML <div> {% if user.is_authenticated %} <p>User is authenticated: … -
Why does my django-project work when I change my secret_key?
I change my SECRET_KEY in django project, and i start it again using manage.py runserver, but project is still working. How is it possible,? I think the project should not work. I try replace SECRET_KEY from .env back to settings.py. But it doesn`t help. -
I need to run migrations as a part of an MS Azure app service release pipeline for a Django web app
I need to execute the migration command on the container hosted on azure webapp python3 manage.py migrate I have tried using POST_BUILD_SCRIPT_PATH which points to the shell script file which has the command I tried passing the command using startup command from both cd pipeline as well as configuration but both of the approaches didn't help Did anyone succeeded with this? As I'm stuck from a day on the same.. I'm expecting a working solution for this issue who has done recently or who is familiar with this stuff