Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What are good practices when using Vault to secure a containerized Django application?
I need help with a school project; I have a Django app and a Vault server in separate containers (database and other things too, but they are not important here). I am struggling to understand what should and should not be done when using Vault to ensure my app's security. It's also worth mentioning that the entire project needs to be compiled and ready to use with a single 'make' command, so Vault's initialization, key storage, unsealing, etc., must be handled in scripts. Where should I store Vault's token and root key once initialized? Storing them in plain text files doesn't seem secure, but I'm not sure of other options. Same with the TLS certificates and keys. When is Vault supposed to be sealed? Should Vault be unsealed and then sealed again with each request? Or should Vault remain unsealed as long as the app is running? But in that case, sealing it seems pointless. Is storing keys on the host machine and passing them to containers via environment variables a secure approach? Sorry if these questions seem basic, but this project is a big deal, and I want it to be secure. Thanks! -
Getting :- Error exchanging code for token: invalid_request
So I have been trying to make an extension using MyAnimeList API to fetch user data and upon callback after authorization of the user. It seems there seem to be some problem with my access token def mal_callback(request): code = request.GET.get('code') # Exchange the code for an access token token_response = post( 'https://myanimelist.net/v1/oauth2/token', data={ 'client_id': settings.MAL_CLIENT_ID, 'client_secret': settings.MAL_CLIENT_SECRET, 'code': code, 'grant_type': 'authorization_code', 'redirect_uri': settings.REDIRECT_URI, } ).json() if 'access_token' not in token_response: error_message = token_response.get('error', 'Unknown error') logger.error("Error exchanging code for token: %s", error_message) return redirect('/error/') logger.error("Token response: %s", token_response) access_token = token_response['access_token'] # Retrieve user information user_info_response = get( 'https://api.myanimelist.net/v2/users/@me', headers={'Authorization': f'Bearer {access_token}'} ).json() # Log the user info response # Make sure user_info_response is valid if 'name' not in user_info_response: # Handle error error_message = user_info_response.get('error', 'Unknown error') logger.error("Error retrieving user info: %s", error_message) return redirect('/error/') # Redirect to an error page or handle as needed username = user_info_response['name'] # Create or get the user user, created = User.objects.get_or_create(username=username) # Create or update the ExternalUser model external_user, _ = ExternalUser.objects.update_or_create( user=user, defaults={ 'provider': 'MAL', 'access_token': access_token, 'refresh_token': token_response.get('refresh_token'), 'token_expires_at': token_response.get('expires_at'), } ) # Log the user in login(request, user) return redirect('/') I rechecked all variable and constant values and … -
Recover Custom Field when Editing Django Admin Form
Given the current models in models.py: from django import forms from django.db import models from decimal import Decimal from datetime import datetime, date class Order (models.Model): assignment = models.ForeignKey("Assignment", on_delete=models.RESTRICT) qty = models.PositiveIntegerField(default=1) order_date = models.DateField() price = models.DecimalField(max_digits=10, decimal_places=2) class Assignment (models.Model): assig_year = models.PositiveSmallIntegerField() customer = models.ForeignKey("Customer", on_delete=models.CASCADE) agent = models.ForeignKey("Agent", on_delete=models.CASCADE) class Agent (models.Model): name = models.CharField(max_length=32) surname = models.CharField(max_length=32) class Customer (models.Model): name = models.CharField(max_length=64) I need to provide users with an admin custom form which allows to create and update orders in a more intuitive way. In order to do that, I exclude the assignment field (which bounds a Customer with a Sales Agent for a given year, but may not be so obvious to fill in for a user) and include a custom field for the user to select just a Customer instead. Based on this input and the order date, I internally look for the specific assignment that fulfills this criteria and assign it to the order to be stored in the Database. It looks like this: admin.py from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.contrib import admin from django.db.models import CharField from django import forms from django.db import models from .models import Customer, … -
My login and register page doesnt work when i click the button and my url config is good
i am building a django project and i keep getting this error:- django.db.utils.IntegrityError: null value in column "id" of relation "validation" violates not-null constraint DETAIL: Failing row contains (null, 7, 839510, 0, 2024-10-29 19:51:34.057435+00, f, null). I think it is something to do with my datbase,i use pgadmin views.py from django.shortcuts import redirect, render from django.contrib.auth import login, authenticate from django.core.mail import send_mail from django.utils import timezone from .forms import UserRegistrationForm, UserLoginForm, VerificationForm from .models import Validation # User Registration View def register_view(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) token = random.randint(100000, 999999) Validation.objects.create(user=user, token=token, expired=timezone.now() + timezone.timedelta(hours=1)) send_mail( 'Your Verification Code', f'Use this code to verify your account: {token}', settings.DEFAULT_FROM_EMAIL, [user.email], ) return redirect('verification') else: form = UserRegistrationForm() return render(request, 'registration/register.html', {'form': form}) # Verification View def verify_view(request): if request.method == 'POST': form = VerificationForm(request.POST) if form.is_valid(): token = form.cleaned_data['token'] try: validation = Validation.objects.get(user=request.user) if validation.token == int(token) and validation.expired >= timezone.now(): validation.validation_status = True validation.save() return redirect('profile') else: # Handle case where verification fails except Validation.DoesNotExist: pass else: form = VerificationForm() return render(request, 'registration/verify_email.html', {'form': form})models.py # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) status = models.CharField(max_length=50, … -
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 …