Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Cookie on the same domain is set, but not being sent to another subdomain
I have a django server running on api.domain.lt and sveltekit server running on dev.domain.lt. Due to the separate servers I have a endpoint /csrf that forces to set a cookie if there's none for the frontend, so I could perform any kind of POST requests later. As I can see in the response headers the cookie is being set: Set-Cookie csrftoken=d8nimJM2fXtyPdhra2h8oF36o7juCJKz; Domain=.domain.lt; expires=Tue, 28 Jan 2025 17:35:19 GMT; Max-Age=31449600; Path=/; SameSite=Lax; Secure But when I perform another request to the server the cookie is not being added to the request,for god damn sakes, whyyyyyy? Even if I open the django server in another tab and view the Cookies in the dev tools, there's nothing. CORS_ALLOWED_ORIGINS = [ "https://domain.lt", "https://dev.domain.lt", "https://api.domain.lt", ] CSRF_TRUSTED_ORIGINS = [ "https://domain.lt", "https://dev.domain.lt", "https://api.domain.lt", ] # This allows us to send requests from dev.domain -> api.domain CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = True # The cookie will be marked as “secure”, which means browsers may ensure that the cookie is only sent under an HTTPS SESSION_COOKIE_SECURE = True # Is this actually doing anything? CSRF_COOKIE_DOMAIN = ".domain.lt" SESSION_COOKIE_DOMAIN = ".domain.lt" This is how I perform a request to the django server: const res = await fetch( "https://api.domain.lt/........", {credentials: … -
Python Django(?) ORM race conditions
The answer to my question may probably be obvious, but I'd like to find out for myself. I love Django ORM and use it in almost all my projects. I'm currently developing a telegram bot using Pyrogram (available in asynchronous mode with async await + asyncio.run), and I want to use Django ORM in it. Let me give a simplified example of my task. There is a button that is bound to an object in the database, each click of which should decrease a field in one object and increase another field in another, conditionally: obj1 = Object1.objects.get(id=X) if obj1.filed1 > 0: obj2 = Object2.objects.get(id=X2) obj1.field1 += N obj2.field2 += N obj1.save() obj2.save() However, I am worried that this may cause a race condition and the result of executing this code with several simultaneous button clicks may differ from what is expected (both in the if condition and when further saving objects). Please tell me what are the best practices for handling such tasks. Is select_for_update method would cover me needs? If Django ORM is not a good solution for this, what ORMs or database libraries should I look at? If Django ORM is suitable, what exactly is the best … -
appication.view is not getting import in django urls using python community edition please help out
i have been making a django project using pycharm community edition i did install application in settings.py it is not getting import in django urls.py from productapp.Views import Home productapp is my app name and this is query ive writen in django.urls file expecting it to get import in my urls file -
Why is my get_token() not the same as my request.META.get("CSRF_COOKIE")?
Does anyone know why I am encountering this issue? I'm starting to test Angular 17 as a FrontEnd with Django as a Backend, and when validating a form, I encounter the issue that when obtaining my token from Django and sending it in the HTTP header, it doesn't match the token expected by Django. I'm not sure if the problem is that the expected token is not updating with get_token() or if get_token() is returning the incorrect token. settings.py: CSRF_TRUSTED_ORIGINS = [ "http://localhost:4200", ] CSRF_COOKIE_NAME = 'XSRF-TOKEN' CSRF_USE_SESSIONS = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True CSRF_COOKIE_DOMAIN = 'localhost' CSRF_COOKIE_PATH = '/' #En esta sección configuro el CORS CORS_ORIGIN_WHITELIST = [ "http://localhost:4200", ] CORS_ALLOWED_ORIGINS = [ "http://localhost:4200", # Angular ] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'X-XSRF-TOKEN', 'x-requested-with', 'Content-Type', '_HttpHeaders', ] csrf-service.service.ts export class CsrfService { private csrfToken: string | null = null; constructor(private http: HttpClient) {} //Obtener el token CSRF getCsrfToken(): string | null { return this.csrfToken; } //Cargar el token CSRF desde el servidor loadCsrfToken(): Observable<any> { const csrfUrl = 'http://localhost:8000/obt_csrf_token/'; return this.http.get<any>(csrfUrl); } //Actualizar el token CSRF en el … -
Django - Cannot Display Elements Based On Field Value
I’m currently building a gaming app where a currently logged in user has access to play different games based on their rank in our application. So if a currently logged in user has a rank of let’s say 100 than all the games with a game rank of 100 and below will be displayed. The rest of the games will be locked. I can’t get this currently fully to work with my code. What do I need to change with my code? If I test using When(game_rank__lte=25, then=Value(True)), that seems to work, I can see both locked and unlocked games based on the value of 25 and less. But when I do When(game_rank__lte=user_profile_rank, then=Value(True)), that doesn’t seem to work. All the games are unlocked and none are locked. The rank of each game is the game_rank field in the Game_Info model. The rank of the currently logged in user is the rank field in the User_Info model. Any help is gladly appreciated. Thanks! models.py class Game_Info(models.Model): id = models.IntegerField(primary_key=True, unique=True, blank=True, editable=False) game_title = models.CharField(max_length=100, null=True) game_rank = models.CharField(max_length=1000, null=True, blank=True) game_image = models.ImageField(default='default.png', upload_to='game_covers', null=True, blank=True) locked_game = models.BooleanField(default=0) unlocked_game = models.BooleanField(default=0) class User_Info(models.Model): id = models.IntegerField(primary_key=True, blank=True) image … -
ImportError: attempted relative import beyond top-level package in Django while importing from different django apps
I am trying to import SignUp model from authentication app into views file of another app named core. Why i am getting this error and how can i solve this? core/views.py from django.http import HttpResponse from django.shortcuts import render from mongoengine import DoesNotExist from ..authentication.models import SignUp def home(request): default_content = { 'title': 'Welcome to College Management System', } # Retrieve the user_id and username from cookies user_id = request.COOKIES.get('user_id') username = request.COOKIES.get('username') if user_id: try: user = SignUp.objects.get(username=username) # Your existing code that uses user_id goes here # For example, you can fetch additional user data using user_id # Update default_content or perform other actions based on user information except DoesNotExist: # Handle the case where the user does not exist return HttpResponse("User does not exist") return render(request, 'core/base.html', {'content': default_content, 'username': username}) authentication/models.py import mongoengine from django.contrib.auth.hashers import check_password class SignUp(mongoengine.Document): email = mongoengine.EmailField() username = mongoengine.StringField(max_length=15) password = mongoengine.StringField() first_name = mongoengine.StringField(max_length=20) last_name = mongoengine.StringField(max_length=20) role = mongoengine.StringField(choices=('admin', 'faculty', 'student')) meta = { 'collection': 'Signup', } def check_password(self, raw_password): return check_password(raw_password, self.password) -
An error occurred (403) when calling the HeadObject operation: Forbidden - Why I'm receiving this error when I try to post an item at AWS S3?
I'm working in an e-commerce Django project and I've made the deployment of the project in an EC2 instance, but now that I'm trying to work again at my Django project I'm receiving this error when I try to create a new item ClientError at /items/new/ An error occurred (403) when calling the HeadObject operation: Forbidden Note that I've tried several different types of bucket policies and no one have work Bucket Policy -> { "Version": "2008-10-17", "Statement": [ { "Sid": "AllowPublicRead", "Effect": "Allow", "Principal": "*", "Action": "s3:*", "Resource": [ "arn:aws:s3:::ecommercesimple", "arn:aws:s3:::ecommercesimple/*" ] } ] } settings.py -> # Amazon S3 settings AWS_ACCESS_KEY_ID = 'xxxxx' AWS_SECRET_ACCESS_KEY = 'xxxx' AWS_STORAGE_BUCKET_NAME = 'ecommercesimple' AWS_S3_SIGNATURE_NAME = 's3v4', AWS_S3_REGION_NAME = 'us-east-2' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_VERITY = True DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I appreciate any help! -
Can't solve problem "Page not found (404)" in Django
I have this problem and can not fix it. project = test_dummy app = database This is the error message that I get: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/templates/htmlcode/homeAntragsteller.html Using the URLconf defined in test_dummy.urls, Django tried these URL patterns, in this order: admin/ [name='login'] [name='index_antragsteller'] The current path, templates/htmlcode/homeAntragsteller.html, didn’t match any of these. database/urls.py urlpatterns = [ path('', views.user_login, name='login'), path('', views.index_antragsteller, name='index_antragsteller'), ] test_dummy/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include("database.urls")), ] my views.py for user_data in example_users: User.objects.get_or_create(email=user_data['email'], password=user_data['password'], telefonnummer=user_data['telefonummer'], vorname=user_data['vorname'], ist_bearbeiter=user_data['ist_bearbeiter'], name=user_data['name'], abteilung=user_data['abteilung']) def user_login(request): create_example_users() if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['email'] password = form.cleaned_data['passwort'] if User.objects.filter(email=username).exists(): user_eintrag = User.objects.get(email=username) if user_eintrag.password == password: print("Passwort correct") if user_eintrag.ist_bearbeiter: return redirect('../templates/htmlcode/homeBearbeiter.html') else: return redirect('templates/htmlcode/homeAntragsteller.html') else: if user_eintrag.password != password: return redirect('../templates/htmlcode/login.html') else: return redirect('../templates/htmlcode/error.html') else: return render(request, '../templates/htmlcode/login.html') @login_required def index_antragsteller(request): return render(request, '../templates/htmlcode/homeAntragsteller.html') in the view, I also tried to remove ../ from ../templates/htmlcode/homeAntragsteller.html but it doesn't look like it's having any effect. my folder structure . ├───database │ ├───migrations │ ├───views.py │ └───urls.py ├───test_dummy │ ├───static │ │ └───filesCSS │ ├───templates │ │ ├───bilder │ │ ├───htmlcode │ | | └───homeAntragsteller.html │ │ └───scripts …