Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't Load URL Error on Facebook Login Integration: Missing 'Facebook Login' Product in Developer Console
Question: I'm integrating Facebook Login into my Django web application hosted at https://weddingcloset.store. In the Facebook Developer Console, I set up an app and added weddingcloset.store and www.weddingcloset.store to the App Domains in the Basic settings. I also added the Privacy Policy URL and Site URL.Dashboard error message. Additionally, in my Facebook Developer Console, the "Add Product" option, which includes Facebook Login, does not appear in the sidebar. I cannot find the OAuth Redirect URI field either, making it impossible to specify the redirect path. This is code of my setting.py , I am using django # settings.py from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-x(m$y#9=ko8*q(z8@=0ct%8v6sppw(+9!^mt$tt^926%!0%shf' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'login_via_facebook', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'social_logins.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', # Fixed typo here ], }, }, ] WSGI_APPLICATION = 'social_logins.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { … -
How to add additional fields in model serializer in django ModelViewSet?
Cart Serializer classs class CartSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) menuitem = MenuItemSerializer(read_only=True) price = serializers.SerializerMethodField(method_name='calculate_price') menuitem_id = serializers.IntegerField(write_only=True) user_id = serializers.IntegerField(write_only=True) class Meta: model = Cart fields = ['id', 'user', 'menuitem', 'quantity', 'unit_price', 'price', 'menuitem_id', 'user_id'] validators = [ validators.UniqueTogetherValidator( queryset=MenuItem.objects.all(), fields=('id',), message="Menuitem should be unique in this curt" ), validators.UniqueTogetherValidator( queryset=User.objects.all(), fields=('id'), message="User should be unique") ] def calculate_price(self, item: Cart): print(item.unit_price * item.quantity) return item.unit_price * item.quantity add_cart method in CartItemsViewSet class @action(detail=True, methods=['post']) def add_cart(self, request, pk=None): if request.user.is_authenticated: user = request.user else: return Response('User is not authenticated', 403) # print(request.data) # print(request.user.id) # user_id = user.id # menuitem_id = request.data['menuitem_id'] # quantity = request.data['quantity'] # unit_price = request.data['unit_price'] # id = request.data['id'] # pack_data = {'user_id': user_id, 'menuitem_id': menuitem_id, # 'quantity': quantity, 'unit_price': unit_price, 'id': id} serializer = serializers.CartSerializer( data=request.data) if serializer.is_valid(raise_exception=True): print(serializer.validated_data) serializer.save(user_id=user.id) return Response('Item is added successfully.', 201) Cart Model class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) menuitem = models.ForeignKey(MenuItem, on_delete=models.CASCADE) quantity = models.SmallIntegerField(), unit_price = models.DecimalField(max_digits=6, decimal_places=2) price = models.DecimalField(max_digits=6, decimal_places=2) class Meta: unique_together = ('menuitem', 'user') I want to implement a login user add a menu item to their cart. But the problem is that I do not add additional field 'user_id' when save … -
Latency to be addressed in django for M2M relationship in ModelAdmin dropdown
I have a group of mailboxes which needs to be populated based on customer login and the domains he owns. Customer:User is 1:1 relationship. Tried: views.py: class MailboxAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return Mailbox.objects.none() qs = Mailbox.objects.all() # Check if the user is in the 'customers' group if self.request.user.groups.filter(name='customers').exists(): print('customer login in mailbox autocomplete view.......') # Filter based on the customer's email qs = qs.filter(domain__customer__email=self.request.user.email).only('email') elif self.request.user.groups.filter(name__in=['resellers']).exists(): # Filter based on the reseller's email qs = qs.filter(domain__customer__reseller__email=self.request.user.email).only('email') if self.q: # Further filter based on user input (e.g., email matching) qs = qs.filter(email__icontains=self.q) print(qs.values('email')) return qs in the apps urls.py: path('mailbox-autocomplete/', views.MailboxAutocomplete.as_view(), name='mailbox-autocomplete'), ] in models.py: class GroupMailIdsForm(forms.ModelForm): class Meta: model = GroupMailIds fields = "__all__" mailboxes = forms.ModelMultipleChoiceField( queryset=Mailbox.objects.none(), widget=autocomplete.ModelSelect2Multiple(url='mailmanager:mailbox-autocomplete') ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance.pk: # Check if the instance is being updated if self.request.user.groups.filter(name='customers').exists(): self.fields['mailboxes'].queryset = Mailbox.objects.filter(domain__customer__email=self.request.user.email) elif self.request.user.groups.filter(name='resellers').exists(): self.fields['mailboxes'].queryset = Mailbox.objects.filter(domain__customer__reseller__email=self.request.user.email) in admin.py: class GroupMailIdsAdmin(ImportExportModelAdmin): resource_class = GroupMailIdsResource ordering = ('address',) filter_horizontal = ('mailboxes',) and in settings.py: INSTALLED_APPS = [ 'mailmanager.apps.MailmanagerConfig', 'admin_confirm', 'dal', 'dal_select2', 'django.contrib.admin', 'jquery', ] with other required django apps. The autocomplete is not working. Django version 4.2 used django-autocomplete-light==3.11.0 IS there something I am missing. I am trying to solve … -
Can Django make this multiple tables query in a single statement?
Let simplify the problem. Say I have two models: class Man(models.Model): # some fields class Job(models.Model): man = models.ForeignKey(Man) # other fields Here, my logic is that, some man may have a job, some may not. Now I want to make a query to select men with the info if the man have a job. If I write the query in SQL, then something like: select m.*, j.id from man m left join job j on m.id=j.id where m.some_condition So that if j.id is null, then the man has no job. How to make this query in Django ORM? -
limit the number of inserts for a user in a date range
I would like to limit the number of posts or articles to a user, for example 12 or 15 publications over a year I would like to limit the number of posts or articles to a user, for example 12 or 15 publications over a year, the logged user will take one or more subscriptions for posts after reaching the default number of posts -
TemplateSyntaxError: expected token '=', got '['
This is my source code (sorry for sending almost everything, i rly idk where's the error): <p class="font-bold">Apresentar a avaliação detalhada processo de negócio, trazendo todos os questionários, suas perguntas e respostas.</p> {% for item in data['quiz'] %} {% if forloop.first or item['Questionario__QuestionarioDescricao'] != previous_questionario %} {% if not forloop.first %} </div> {% endif %} <h3 class="quiz-title">Questionário: {{ item['Questionario__QuestionarioDescricao'] }}</h3> {% endif %} <p class="font-bold">Pergunta: {{ item['QuestionarioItem__QuestionarioItemDescricao'] }}</p> <p>Resposta: {{ item['QuestionarioRespostaTexto'] }} </p> {% if item['QuestionarioRespostaSimNao'] == "S" %} <p>Resposta (Sim/Não): Sim</p> {% elif item['QuestionarioRespostaSimNao'] == "N" %} <p>Resposta (Sim/Não): Não</p> {% else %} <p>Resposta (Sim/Não): {{ item['QuestionarioRespostaSimNao'] }}</p> <!-- Caso não seja S ou N --> {% endif %} {% with item['Questionario__QuestionarioDescricao'] as previous_questionario %} <!-- Isso vai ajudar a saber se a próxima iteração é de um novo questionário --> {% endwith %} {% endfor %} the error occurs in this section code: try: jinja_template = Template(template) rendered_html = jinja_template.render( data=data, generation_date=datetime.now().strftime('%d/%m/%Y') ) except TemplateError as te: print(f"Erro ao processar o template Jinja2: {te}") return the error: Erro ao processar o template Jinja2: expected token '=', got '[' I'm trying to generate a pdf report using the weasyprint lib from an html template. -
Django Ninja multiple APIs documentation
Django Ninja allows to autogenerate OpenApi endpoint documentation. However, the documentation is available for single API object only, meaning that in order to view another API's documentation I need to change the URL. My project uses multiple API versions. I would like to host the docs under single, unified URL instead of having to remember what api version specific feature used. Django Ninja's documentation allows API versioning as stated here. However, this leads to the problem described above. Is there any way to include API version switcher as if I was using standalone OpenAPI docs? Obviously, I could get and host raw docs myself, but I hope that there's an easy configure-and-forget solution I am missing, since Django Ninja hosts it already. I tried combining different api versions using Router objects instead of API objects. This, however, only is a workaround and prevents some features from working properly. On top of that, wrong API version displays in the UI -
Django DetailView pagination no navigation numbers
(Yes, I know that the first suggestion will be to convert my DetailView into ListView; I've tried that, and it wasn't helpful) I have a Django forum app, its structure is "forum -> subforum -> topic -> comments". Comments are displayed on their related topic's page, so a topic's view handles Topic together with its comments. Topic itself includes its subject and the initial comment (first_comment). I've looked through some tutorials and questions here in SOF, so somehow I've made my pagination work in the sense that it cuts the amount of displayed comments by the number in the parameter in Paginator (in the example it's 5). But, unfortunately, I cannot reproduce any links, numbers of pages to navigate through the pagination. And I don't even know, where is the cause of this problem hidden - either in html code, either in the view's code. Please help me. View: class ShowTopic(DetailView): model = Topic template_name = "forum/topic.html" slug_url_kwarg = 'topic_slug' context_object_name = 'topic' def get_context_data(self, **kwargs): topic = get_object_or_404(Topic, slug=self.kwargs['topic_slug']) comments = self.get_comments(topic) comments_number = len(Comment.objects.filter(topic__id=topic.id)) context = {'menu': menu, 'topic': topic, #'comments': comments, 'page_obj': comments, 'comm_num': comments_number} return context def get_comments(self, topic): qs = Comment.objects.filter(topic=topic) paginator = Paginator(qs, 5) … -
Which python virtual environment tool should I use? [closed]
I want to build a backend application in Django (4.2) framework. The reason is mostly educational. I feel like I lack experience for choosing the right technology. I was wondering if any of you, who work on real life Django applications, and have a history of problems/success stories with a certain tool. I would really appreciate the help for me to decide which to use. When I was previously developing python applications I used 'virtualenvironment' and 'Pipenv'. Where I used to work we also use 'Poetry'. I never encountered any problems with any of them, so I cant make an educated decision. What python virtual environment and deployment solution should I use? This is a similar issue, but its 14 years old and a lot changes in 14 years :D -
How do I display foreignkey as a search option in Django cms Plugin
I want to be able to use the autocomplete_fields interface from Django admin in a Django CMS plugin I've created a plugin which has a foreignkey field : class ProductBlock(CMSPlugin): text = models.TextField() product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True) When I go to add the plugin to the page the option is shown as a dropdown. I've created an admin.py as follows: class ProductBlockAdmin(admin.ModelAdmin): autocomplete_fields = ['product'] admin.site.register(ProductBlock, ProductBlockAdmin) In the admin section the field appears with the search option but this isn't displayed in the editor for the plugin. I'm using django cms 4.1.3 -
Tying data to a user's account
I am writing a signup form for my django site. And basically I want them to hit submit and create the account. I have written code that creates a license key when they hit it but I don't know how to tie it to their account. Any ideas? from django.shortcuts import render, redirect from django.contrib.auth import login from .forms import SignupForm from Functions.average_getter_shortened import baseline from Functions.today_checker import today_getter from Functions.license_key import license_getter def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): user = form.save() try: license_key = license_getter(access_key='access_key') except: license_key = 'Key' login(request, user) return render(request, r'registration\license_key.html', {'license_key' : license_key}) else: form = SignupForm() return render(request, r'registration\signup.html', {'form': form}) I tried to implement user.save() after the except statement but then the website wouldnt redirect to the license_key page -
Disable CORS in Django running in Dokku
When building websites I use the following logic: If my frontend domain is domain.com then my backend domain is always api.domain.com (subdomain via Cloudflare) I hit an errors caused by CORS WildcardOriginNotAllowed, MultipleAllowOriginValues when I tried to apply response CORS header via nginx, Access to XMLHttpRequest has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header In my Django config I have added: CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] CORS_ALLOW_ALL_HEADERS = True SECURE_CROSS_ORIGIN_OPENER_POLICY = None In my Cloudflare config I disabled all the advanced security settings. In my Dokku config I don't have any settings related to CORS. The problem remains after all the fixes -
Using celery-beat as a timer
In my application, I want to run some function once after a certain time interval since the object is created. Is django-celery-beat the right tool for doing this? -
Issue with FORCE_SCRIPT_NAME Configuration in Django
I have to use FORCE_SCRIPT_NAME to set the app name. The problem is when I go from one page to another it set the script name behind de url. Below is the code #setting.py FORCE_SCRIPT_NAME = "/myapp/" #urls.py(myapp) urlpatterns = [ path('', views.index, name='index'), path('another-page/', views.another_page, name='another_page'), ] #urls.py(project urlpatterns = [ path("admin/", admin.site.urls), path('myapp/', include('myapp.urls')), ] #views.py def index(request): return render(request, 'home.html') def another_page(request): return render(request, 'another_page.html') As a result when I go from home to another_page the url is: http://127.0.0.1:8000/myapp/myapp/another-page/ How do I fix this? This is the code for the home page <body> <h1>Welcome to the Home Page!</h1> <a href="{% url 'another_page' %}"> <button type="button">Go to Another Page</button> </a> </body> -
Geonode project: deploy at subfolder
I trying to deploy geonode-project at subfolder. By now, I succesfully done the following: changed static and upload urls in settings added prefix to all urls, like re_path(r"^my_prefix", include("geonode.urls")) But, problem is, all links on pages still point to /original_url, not to /my_prefix/original_url, although I've rebuild everything with docker compose build --no-cache. Script paths, api endpoints, and static paths are all correct now. What do I missing? -
CI CD PIpeline downline
I am working on a Django project with a CI/CD pipeline implemented using Jenkins. When I add a new library to my code and update requirements.txt, pulling these changes through the CI/CD pipeline and running requirements.txt causes downtime while the new libraries are being installed. -
Django - Warning "Accessing the database during app initialization is discouraged" in AppConfig.ready() after update
Recently, I’ve updated Django to the latest version, 5.1.2, and since then, every time I start the server, I get this warning: RuntimeWarning: Accessing the database during app initialization is discouraged. To fix this warning, avoid executing queries in AppConfig.ready() or when your app modules are imported. From what I’ve searched so far, my apps.py file is causing this due to the operation it’s executing on the database: from django.apps import AppConfig class TenantsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'tenants' def ready(self): self.load_additional_databases() def load_additional_databases(self): from django.conf import settings from .models import DatabaseConfig for config in DatabaseConfig.objects.all(): if config.name not in settings.DATABASES: db_settings = settings.DATABASES['default'].copy() db_settings.update({ 'ENGINE': config.engine, 'NAME': config.database_name, 'USER': config.user, 'PASSWORD': config.password, 'HOST': config.host, 'PORT': config.port, }) settings.DATABASES[config.name] = db_settings My settings.py has two main databases (default and tenants) hard-coded and the other configurations should be updated with data from the model DatabaseConfig when I start the server. The problem is that I need this exact behavior, but the solution I’ve found so far, is to use connection_created which makes this run for every database query. This is the implementation using the signal: def db_config(**kwargs): from django.conf import settings from .models import DatabaseConfig for config in DatabaseConfig.objects.all(): if … -
How do you make gunicorn forward SIGINT to uvicorn when running inside Docker?
I have a script running inside Docker (using wsl2), started with CMD, that is behaving strangely w.r.t. SIGINT signals. This is the script: #!/usr/bin/env bash python manage.py init_db exec gunicorn foobar.asgi:application \ --worker-class uvicorn.workers.UvicornWorker \ --bind 0.0.0.0:8000 \ --graceful-timeout 5 \ --log-level debug \ -w 4 The problem is that when I press Ctrl+C, gunicorn ends up having to forcefully kill the running uvicorn workers. I see the following errors after 5 seconds: ^C[2024-10-29 21:15:35 +0000] [1] [INFO] Handling signal: int [2024-10-29 21:15:40 +0000] [1] [ERROR] Worker (pid:8) was sent SIGKILL! Perhaps out of memory? [2024-10-29 21:15:40 +0000] [1] [ERROR] Worker (pid:9) was sent SIGKILL! Perhaps out of memory? [2024-10-29 21:15:40 +0000] [1] [ERROR] Worker (pid:10) was sent SIGKILL! Perhaps out of memory? [2024-10-29 21:15:40 +0000] [1] [ERROR] Worker (pid:7) was sent SIGKILL! Perhaps out of memory? I have found three workarounds of sorts, which may be useful to help understand what is going on. Bash into the container and start the script from inside. Now Ctrl+C seems to work better, because now the uvicorn workers quit on time, but gunicorn still prints some errors: ^C[2024-10-29 21:21:56 +0000] [1] [INFO] Handling signal: int ... worker shutdown cleanup output omitted [2024-10-29 … -
How to properly implement login and token handling from REST endpoint in ASP.NET Core/MAUI Blazor
I'm developing a MAUI Blazor application that communicates with a Django REST Framework backend. I'm trying to implement user authentication, but I'm encountering a "Bad Request" error when trying to log in. I'm successfully hitting the /api/login/ endpoint, but I'm getting a "Bad Request" error. What could be causing this? How should I format the request to ensure successful authentication? Here's the relevant part of my Blazor code: @page "/" @inject HttpClient HttpClient @using System.Text @using mysocial.Models @using Newtonsoft.Json <h3>Login</h3> <div> <label>Username:</label> <input type="text" @bind="username" /> </div> <div> <label>Password:</label> <input type="password" @bind="password" /> </div> <button @onclick="Logins">Login</button> @if (authToken != null) { <p>Login successful! Token: @authToken.Token</p> } @code { private string? username; private string? password; private AuthToken? authToken; private async Task Logins() { var loginData = new { Username = username, Password = password }; var json = JsonConvert.SerializeObject(loginData); var response = await HttpClient.PostAsync("http://127.0.0.1:8000/api/login/", new StringContent(json, Encoding.UTF8, "application/json")); if (response.IsSuccessStatusCode) { authToken = await response.Content.ReadFromJsonAsync<AuthToken>(); } else { var errorContent = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Error: {errorContent}"); } } } -
I can't create tests that involve authorization groups
Salutations, I've been creating tests for testing web I've been looking all over the internet to find the solution. I've been building a fixture for a group that allows users to create blog posts. It's a series of test I've been building for the sake of authorization purposes. I've using both Pytest fixtures and factories with similar results. Here's the Test Class: import pytest import factory from django.contrib.auth import get_user_model from posts.models import Post from members.models import Member from factories import MemberFactory, PostFactory from faker import Faker from django.contrib.auth.models import Group # Create your tests here. User = get_user_model() fake = Faker() #Fixture @pytest.fixture(scope="session") def contributor_group(db): return Group.objects.create("Contributor") @pytest.fixture(scope="session") def authorized_user(db): authorized_user = MemberFactory() return authorized_user # Post Tests class TestPosts: #Disallows user to create a post if they're not a contributor @pytest.mark.django_db def test_is_not_contributor(db): reg = MemberFactory() assert reg.has_post_permissions() is False #Allows a user to create a post if they're a contributor. @pytest.mark.django_db def test_can_post(db): contributor_group. print(authorized_user) print(contributor_group) print(authorized_user.has_post_permissions()) assert authorized_user.has_post_permissions() is True I've also created Factories for both of them. import factory from faker import Faker from django.contrib.auth.models import PermissionsMixin from django.contrib.auth import get_user_model from posts.models import Post from members.models import Member fake = Faker() User = get_user_model() … -
Filters and Pagination with Django Function-Based Views
I'm working on my first Django program and would like to create a template including filtering and pagination functions that could be used simultaneously. This is what I have so far: models.py class Player (models.Model): name = models.CharField(max_length=32) surname = models.CharField(max_length=32) def __str__(self): return f"{self.name} {self.surname}" class Meta: verbose_name_plural = "Players" views.py def GetPlayers(request): players = Player.objects.all().values() pn = request.GET.get('name') if pn != '' and pn is not None: players = players.filter(name__icontains=pn) page_num = request.GET.get('page', 1) paginator = Paginator(players, 2) page_obj = paginator.get_page(page_num) template = loader.get_template('players.html') context = { 'players' : players, 'page_obj' : page_obj, } return HttpResponse(template.render(context, request)) players.html {% block content %} <div class="mycard"> <h1>Players</h1> <div class="filters"> <form action="" method="GET"> <div class="row"> <div class="col-xl-3"> <label>Name:</label> <input type="text" class="form-control" placeholder="name" name="name" {% if name %} value = "{{ name }}" {% endif %}> </div> <div class="col-xl-2" style="padding-top: 2%;"> <button type="submit" class="btn custom-btn">Filter</button> </div> </div> </form> </div> <p/> <div style="overflow-x:auto;"> <table> <thead> <th>Name</th> <th>Surname</th> </thead> <tbody> {% for x in page_obj %} <td>{{ x.name }}</td> <td>{{ x.surname }}</td> </tr> {% endfor %} </tbody> </table> {% include "pagination.html" %} </div> </div> {% endblock %} Let's imagine I have 6 players called "John", "Mark", "Phil", "Jason", "Jane" and "Juliet". If I don't … -
Problems uploading django static files to S3 using zappa
Good afternoon! I'm deploying a Django project with Django Rest Framework (DRF) on AWS Lambda using Zappa. Everything is working so far, except for the Django admin, which appears unstyled and missing static files. Following the documentation, I attempted to configure my static files to be served from S3 by running zappa manage dev "collectstatic --noinput". This command completes successfully, but when I check the S3 bucket, there are no static files related to my project (specifically for Django admin). Here’s my configuration: Settings.py java Copiar código from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = '' DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'notification', 'storages' ] S3_BUCKET = "Name-bucket-s3" STATICFILES_STORAGE = "django_s3_storage.storage.StaticS3Storage" AWS_S3_BUCKET_NAME_STATIC = S3_BUCKET STATIC_URL = f"https://{S3_BUCKET}.s3.amazonaws.com/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') AWS_S3_CUSTOM_DOMAIN = f"{S3_BUCKET}.s3.amazonaws.com" AWS_ACCESS_KEY_ID = "" AWS_SECRET_ACCESS_KEY = "" AWS_STORAGE_BUCKET_NAME = S3_BUCKET AWS_S3_REGION_NAME = '' Zappa settings (zappa_settings.json) json Copiar código { "dev": { "aws_region": "", "django_settings": "core.settings", "profile_name": "default", "project_name": "djangotea", "runtime": "python3.12", "s3_bucket": "Name-bucket-s3" } } Problem: When I run the collectstatic command, it completes without errors, but no files are actually uploaded to S3. After enabling logging, I see an "Access Denied" error. … -
how to add {%for item%} in django
{% block content %} <div class="mt-6 px-6 py-12 bg-gray-100 rounded-xl"> <h2 class="mb-12 text-2xl textt-center">Shop Smart, Live Better.</h2> <div class="grid grid-cols-3 gap-3"> {% for item in items %} <div> <a href="#"> <div> <img src="{{ item.image.url }}" class="rounded-t-xl"> </div> <div class="p-6 bg-white rounded-b-xl"> <h2 class="text-2xl">{{ item.name }}</h2> <p class="text-gray-500">Price: {{ item.price }}</p> </div> </a> </div> {% endfor %} </div> </div> {% endblock %} i tried to add for item in to the block content and iam getting Error during template rendering k your text -
Is there a way to have multiple users on the same device without anyone being the same person with Webauthn in Django?
I am currently working on a project in Django. The application in question consists of allowing agents to register their presence at guard posts (guarding) and to make the rounds. Per post, we can have 2 or 3 agents and who will have to share the same device (Smartphone or tablet) To ensure that each agent is actually present, I wanted to use Webauthn (fingerprints) in the application. So after connecting using the identifiers of the Django connection form, they will have to authenticate using Webauthn to be able to register their arrival at the post. Naturally, each agent would have been registered by their fingerprints at the very level of the security parameters of the device upstream My question is whether this is possible with a shared device. Agents may want to help each other by passing their Django login credentials, so if authentication by Webauthn can cause Agent B to fail to login pretending to be Agent A. Thanks to the kind souls who will do me the honor of answering me. My codes already allow registration and authentication with webauthn. -
Can dependency injection be used with django?
I am very popular with using the technique of dependency injection to decouple my code. This would typically involve providing an object with functionality, into the constructor of it's dependent. For the first time, I am using django to make a web api (with a database of objects attached). I intended to inject an elaborate dependency into the otherwise simple method. (in my case it was functionality to interpret messages coming from RabbitMQ exchanges, but my minimal example is just interpreting a generic message as a site-dependent dictionary). However in django everything seems to be autogenerated from either static methods or the definition of classes, I couldn't find where anything was actually instantiated or customisable to push the dependency in. Is the technique and the django framework just incompatible or am I missing something? Code so far (minimal example recreation, not actual code) in urs.py: urlpatterns = [ path("run/", views.run), ] in views.py def run(request): interpreter = AbstractDataInterpreter() #This is the object I want to inject data = interpreter.interpret(request) return JsonResponse(data, safe=False) I have a test class TestDataInterpreter to use for testing. I have a class CustomDataInterpreter custom for my domain/ecosystem. I plan for for other interpreters on different deployments …