Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Determine languages per user in Django Admin using django-modeltranslation
I'm considering to use django-modeltranslation for my project. So far, seems very suitable. One question about it, I'd like to create a custom method to determine what languages should be displayed and editable in the Admin based on the logged in user. Simple example of the method below: def get_languages(user: User) -> list[str]: if user == Bert: return ['en'] elif user == Ernie: return ['en', 'nl'] return ['de'] Is this supported? -
Email test does not work in Django if django-allauth sends the email
I use the Django 5.0.1 with django-allauth. With real smtp email backend, email confirmation works. Django's email testing features are also working if django-allauth is not involved, like in the [example of the Django testing docs' email service][1]. As soon as I want to test the third party django-allauth confirmation email sending function, the mail.outbox does not have any item. My partial test code: class SignupProcessTest(TestCase): def setUp(self): # We setup base form data and we overwrite only test method specific ones self.data = {"email": "roland.szucs@booknwalk.com", "password1": "ajtoablak1", "newsletter": 1} def test_confirmEmailSent(self): self.client.post(reverse("account_signup"), self.data, secure=True, follow=True) # check email self.assertEqual(len(mail.outbox), 1, f"Email was not sent for confirmation:{len(mail.outbox)}") Based on the docs Django just replaces transparently the email backend settings and collects all emails to the mail.outbox array. Even Django-allauth should not be aware wich email backend serves its email sending request. When I try this in my local server, after signup I am redirected to another page and I get an email within seconds. Why does not it happen in test environment? Any idea? [1]: https://docs.djangoproject.com/en/5.0/topics/testing/tools/#email-services -
how to fix "TypeError: requires_system_checks must be a list or tuple." caused by "py manage.py grpcrunserver" command?
it's my first time aksing a question here so please take easy on me if I do it bad (or whatever) and help! Thanks. I have a project in which I need to use djangogrpcframework, and I've implemented the code but when I try to run the grpc server using "py manage.py grpcrunserver" I get the following error log: (.venv) D:\Programming-stuff\PythonProjects\notification>py manage.py grpcrunserver Traceback (most recent call last): File "D:\Programming-stuff\PythonProjects\notification\manage.py", line 22, in <module> main() File "D:\Programming-stuff\PythonProjects\notification\manage.py", line 18, in main execute_from_command_line(sys.argv) File "d:\Programming-stuff\PythonProjects\notification\.venv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "d:\Programming-stuff\PythonProjects\notification\.venv\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "d:\Programming-stuff\PythonProjects\notification\.venv\Lib\site-packages\django\core\management\__init__.py", line 275, in fetch_command klass = load_command_class(app_name, subcommand) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "d:\Programming-stuff\PythonProjects\notification\.venv\Lib\site-packages\django\core\management\__init__.py", line 49, in load_command_class return module.Command() ^^^^^^^^^^^^^^^^ File "d:\Programming-stuff\PythonProjects\notification\.venv\Lib\site-packages\django\core\management\base.py", line 284, in __init__ raise TypeError("requires_system_checks must be a list or tuple.") TypeError: requires_system_checks must be a list or tuple. (versions:Python 3.12.0, Django 5.0.1, djangogrpcframework 0.2.1, grpcio-tools 1.60.0, grpcio 1.60.0) I've already tried to update django-extensions, but didn't resolve the issue. I also tried to use alternative ways like using "py services.py" to run my grpc server directly but it came up with troubles as well (like not loading apps, and it's not the only one for sure!). any help will … -
Making a field both foreign and primary key in Django
I have a database and in one of the tables, a field should both be a primary and a foreign key. I am new to Django, and I couldn't find an example implementation. I appreciate all the help, Didem I tried looking the documentation or some example repos but didn't see anything -
How to compare integer type and string type variable in Django using if template tag
I am trying to compare two variables using if template tag. If condition is not working as stock.id is integer and form.product_in_stock.value is string. {% if form.product_in_stock.value == stock.id %}selected{% endif %} Is there any way to type cast and then compare using if in django template. -
Django-Ninja CSRF Token & OpenAPI
I am using Django-Ninja and want to use authentication in it. Here is my authentication process : from ninja_extra import NinjaExtraAPI from ninja.security import django_auth api = NinjaExtraAPI(csrf=True) # AUTHENTICATION #////////////////////////////////////////////////////////////////////////////// @api.post("/login") def login_user(request, username: str, password: str): # Authentification de l'utilisateur user = authenticate(request, username=username, password=password) if user is not None: # Connexion de l'utilisateur login(request, user) return {"message": "Login successful"} else: return {"message": "Login failed"} @api.post("/logout", auth=django_auth) def logout_user(request): # Déconnexion de l'utilisateur logout(request) return {"message": "Logout successful"} #////////////////////////////////////////////////////////////////////////////// When I go to http://127.0.0.1:8000/api/docs, I can try the login route and it works. And the other hand, the logout route fails with a CSRF verification failed. Request aborted.. I then tried to look closer to the queries and here is what I found : 1. GET http://127.0.0.1:8000/api/docs ------------------------------------------------------------------- HTTP/1.1 200 OK Date: Thu, 18 Jan 2024 13:16:07 GMT Server: WSGIServer/0.2 CPython/3.10.9 Content-Type: text/html; charset=utf-8 X-Frame-Options: DENY Vary: Cookie Content-Length: 974 X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin Set-Cookie: csrftoken=ZMn7RxrJl3fdnrMHGKNmlgB0GiB0Eyeq; expires=Thu, 16 Jan 2025 13:16:07 GMT; Max-Age=31449600; Path=/; SameSite=Lax <!DOCTYPE html> <html> <head> <link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@4.15.5/swagger-ui.css"> <link rel="shortcut icon" href="https://django-ninja.rest-framework.com/img/favicon.png"> <title>NinjaExtraAPI</title> </head> <body> <div id="swagger-ui"> </div> <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@4.15.5/swagger-ui-bundle.js"></script> <script> const ui = SwaggerUIBundle({ url: '/api/openapi.json', dom_id: '#swagger-ui', presets: [ … -
AttributeError: 'ManyRelatedManager' object has no attribute 'title'
I was trying to make some tests in an API Django with pytest, but find this error: Attribute error image Here's the code's test that failed: import pytest from core.orders.factories import * @pytest.fixture def order_created(): user1 = UserFactory(username='Lucas') category = CategoryFactory(title='teste') product1 = ProductFactory(title='teste_product') return OrderFactory(customer=user1) @pytest.mark.django_db def test_order_customer_name(order_created): assert order_created.customer.username == 'Lucas' @pytest.mark.django_db def test_order_product_name(order_created): assert order_created.product.title == 'teste_product' Searching into web I found this error is related to method ManyToManyField() from models. If helps, I'll also put my model's code here: from django.db import models from django.db import models from django.contrib.auth.models import User class Category(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) description = models.TextField(max_length=200, blank=True, null=True) active = models.BooleanField(default=True) def __str__(self): return self.title class Product(models.Model): title = models.CharField(max_length=200) description = models.TextField(max_length=500, blank=True, null=True) price = models.PositiveIntegerField(null=True) active = models.BooleanField(default=True) category = models.ManyToManyField(Category, blank=True) def __str__(self): return self.title class Order(models.Model): product = models.ManyToManyField(Product, blank=False) customer = models.ForeignKey(User, on_delete=models.CASCADE, null=False) def __str__(self): return self.customer.name I try to remove the lines of category1 and product1 delcaration from test code, but I really need find a way to verify the instances of a Order in terms of Product (that needs a category) and Customer(no problem whit that since I was trying to … -
Getting warnings while using django in vscode wsl
I'm using django in vscode in wsl. I'm getting continously warnings in importing packages like from django.contrib import admin, from django.db import models etc. I tried to import python extension and set interpreter to version 3.10.12 -
Architecture of basket in django
I want to create several baskets for ordering items. When i click on "add button" on item's page, i want it was added to my last basket. Baskets amount are several. I don't want select "basket" each time, when i want to add. I want it was selected and changed once somewhere (other page). How should it work? I click basket#1 and then i go add items to this basket. Then i go to basket#2 and add. And i cannot make a selection from the list. I need adding from the page of item. I'm a bit stuck in architecture. Please help. -
Celery ignores Django settings
I'm using Celery for managing async tasks in Django. I set up it using the official instruction. However, when I output app.conf on my worker instance - it outputs default settings. celery.py: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") app = Celery("myapp") app.config_from_object("django.conf:settings", namespace="CELERY") @setup_logging.connect def config_loggers(*args: Any, **kwags: Any) -> None: from logging.config import dictConfig from django.conf import settings dictConfig(settings.LOGGING) app.autodiscover_tasks() @celery_bound_logged_task def debug_task(self: Any) -> None: logger = logging.getLogger(__name__) logger.debug(f"Heartbeat: {self.request.id}") logger.debug("Config: %s", app.conf) <------- Here I get default config, with broker_heartbeat: 120 and etc. settings.py # Celery # From https://www.cloudamqp.com/docs/celery.html CELERY_BROKER_URL = RABBITMQ_URL CELERY_BROKER_POOL_LIMIT = 1 CELERY_BROKER_HEARTBEAT = None CELERY_BROKER_CONNECTION_TIMEOUT = 30 CELERY_RESULT_BACKEND = None CELERY_EVENT_QUEUE_EXPIRES = 60 CELERY_WORKER_PREFETCH_MULTIPLIER = 1 CELERY_WORKER_CONCURRENCY = 1 # Never give up set up CELERY_TASK_ACKS_LATE = True CELERY_TASK_TIME_LIMIT = 30 * 60 # 30 minutes CELERY_TASK_REJECT_ON_WORKER_LOST = False CELERY_TASK_ACKS_ON_FAILURE_OR_TIMEOUT = False -
Slicing an unevaluated Django Queryset, has different results if not ordered
I'm trying to handle in memory data with slicing a unevaluated queryset 500 at a time and then processing it accordingly. What I can't seem to understand is that if I don't apply an order_by to my queryset filter queryset.objects.filter(id_in=[something]) the slicing will not give me all the rows but sometimes repeated rows compared to when I order the queryset queryset.objects.filter(id_in=[something]).order_by("id"). -
DJANGO cors origin not allowed when LOGIN_URL set to localhost:3000 (frontend)
I am using django as backend and react as frontend. Also using google-oauth and the url it redirects to is a callback url in backend and it redirects to the frontend dashboard. Also using django-auth But, as my login page is on React and not the default template, I set the settings.LOGIN_URL = 'http://localhost:3000' So, when frontend accesses a url eg localhost:8000/authorised_url it should redirect to my frontend login page if user is not authenticated. But the browser gives the error: Access to XMLHttpRequest at 'http://localhost:3000/?next=http%3A//localhost%3A8000/auth/check' (redirected from 'http://localhost:8000/auth/check') from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. Should I some another way of acheiving the above as I beleive the default django auth model might not set the headers properly. Django Settings: LOGIN_URL = 'http://localhost:3000' CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000'] CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = [ 'http://localhost:3000' ] Initially was handling the flow in frontend and had a special endpoint to check if user is logged in or not and perform the request, … -
Django, Redis and channels: Using websockets to pass message to browser page via GET request for notifications
I am trying to set up some async notifications in my django app using redis and channels, and new to websockets! I'm confused why my consumer methods are being called in a specific order (below). My setup is essentially a proof of principle one, where in a get request of a view i send a message to my websocket and i'm trying to retrieve this in the console of browser when i access the page. The end goal being to do this in some post requests instances, such as account activation or data upload - to notify specific users about these events. So when i access my view via get request the consumer methods are called in this order: receive disconnect connect I thought they would be called in this order: connect receive disconnect What happens in my browser as well, is the first time i access the get request page, websocket opens (with a print to console saying open) Then if i were to refresh that page, just before the page reloads, the message is printed to console in this case: HELLO YES THIS IS DOG - but when the page actually refreshes, it disappears. I guess i'm trying … -
Django-import-export does not work with 'delete' field
When importing with 'delete' field, it gives error: BaseBoqItem has no field named 'delete' I am also aware that this model doesn't have that field. That model should not have that field for sure, that is not a mistake. I need to add 'delete' field so that user can mark rows those he/she wants to delete, then when importing django-import-export deletes those rows. I followed documentation of django-import-export, and did exactly same. At the end all I get is this error. BaseBoqItem has no field named 'delete' What am I missing here? Here is my model: ``` class BaseBoqItem(models.Model): lot = models.ForeignKey(BaseLot, on_delete=models.PROTECT, related_name='boq_items') code = models.CharField(max_length=20, null=True) name_tm = models.CharField(max_length=255) name_ru = models.CharField(max_length=255, null=True) name_en = models.CharField(max_length=255, null=True) name_original = models.CharField(max_length=255, null=True) quantity = models.DecimalField(max_digits=12, decimal_places=2) unit = models.ForeignKey(BaseUnit, on_delete=models.PROTECT) material_unit_price = models.DecimalField(max_digits=12, decimal_places=2) labor_unit_price = models.DecimalField(max_digits=12, decimal_places=2) transport_unit_price = models.DecimalField(max_digits=12, decimal_places=2, null=True) def __str__(self) -> str: return f'{self.code} - {self.name_tm}' Here is my resource: class BaseBoqItemResource(resources.ModelResource): lot = fields.Field( column_name='lot', attribute='lot', widget=ForeignKeyWidget(BaseLot, field='code')) unit = fields.Field( column_name='unit', attribute='unit', widget=ForeignKeyWidget(BaseUnit, field='code_tm')) delete = fields.Field(readonly=True) def for_delete(self, row, instance): return self.fields['delete'].clean(row) class Meta: model = BaseBoqItem skip_unchanged = True use_bulk = True fields = ( 'id', 'lot', 'code', 'name_tm', 'name_ru', … -
Objects field is set with wrong default value in Django
I modified a default value in an objects' field but it has not been taken in account. I have deleted the database, migrations files and pycaches. In the current configuration shouldn't plateforme.name be set with 'Plateforme_Test_1' ? Because instead, I have the old default value 'default_plateforme'. I am talking about plateforme objects, not environnement objects. Thank you for your help. PS: Here is the snippet: class Plateforme(models.Model): name = models.CharField(max_length=50, default = 'Plateforme_Test_1') def __str__(self): return self.name class Environnement(models.Model): name = models.CharField(max_length=100, default = 'default_module') plateforme = models.ForeignKey('homepage.Plateforme', on_delete=models.CASCADE, related_name='Environnement', null = True) plateforme_name = models.CharField(max_length=100, default = 'default_plateforme') def save(self, *args, **kwargs): if self.name == 'M42048': self.name = 'Env' super().save(*args, **kwargs) def __str__(self): return self.name -
Google API Calendar mismatching_state
Google API Calendar mismatching state error: (mismatching_state) CSRF Warning! State not equal in request and response. erorr occcurs at flow.fetch_token(authorization_response=authorization_response): class GoogleCalendarInitView(View): """ Initiate the OAuth2 authorization flow. """ def get(self, request, *args, **kwargs): # Create a flow instance to manage the OAuth 2.0 Authorization Grant Flow steps. flow = InstalledAppFlow.from_client_secrets_file( 'client_secret.json', scopes=['https://www.googleapis.com/auth/calendar.events'] ) # The URI created here must exactly match one of the authorized redirect URIs # for the OAuth 2.0 client, which you configured in the API Console. If this # value doesn't match an authorized URI, you will get a 'redirect_uri_mismatch' # error. flow.redirect_uri = redirect_uri authorization_url, state = flow.authorization_url( # Enable offline access so that you can refresh an access token without # re-prompting the user for permission. Recommended for web server apps. access_type='offline', # Enable incremental authorization. Recommended as a best practice. include_granted_scopes='true', ) # Store the state so the callback can verify the auth server response. request.session['state'] = state print(f"Stored State in Session: {request.session.get('state')}") # Redirect the user to the authorization URL. return redirect(redirect_uri+"redirect/") class GoogleCalendarRedirectView(View): """ Callback view to handle the response from Google OAuth2 authorization server. This view is registered as the redirect_uri in the Google OAuth2 client configuration. The authorization … -
Reducing Database Queries per Row in Django Admin for Non-ForeignKey Fields
I'm working with Django Admin and facing a challenge related to database queries. In my ModelAdmin, I have multiple functions that fetch data from another model (App). However, this model is not directly related through a ForeignKey. Each function makes an individual query to the App model for each row in the admin list, which seems inefficient. Here's an example to illustrate my current setup: class MyModelAdmin(admin.ModelAdmin): list_display = ('data_from_app_a', 'data_from_app_b', ...) def data_from_app_a(self, obj): # Fetches and returns specific data from App model data_a = App.objects.get(app_no=obj.app_no).field_a return data_a def data_from_app_b(self, obj): # Fetches and returns different data from App model data_b = App.objects.get(app_no=obj.app_no).field_b return data_b In this example, data_from_app_a and data_from_app_b are functions that query the App model separately for each row. I'm looking to reduce the number of these per-row queries. Is there a way to aggregate or prefetch this data more efficiently in Django Admin when dealing with non-ForeignKey relationships? -
Django device tags
I am trying to have functionality on my edit_project page where, when the page loads the current device tag is pre selected from the options menu so that a user 1 knows what the current tag is for that device but also so that if the click save/update the tag will remain as whatever is was. at the moment when the page loads the initial state of the tag menu is "None" or blank if i remove the initial state from the forms function.enter image description here i am able to display the current tag on my dashboard page no problem,enter image description here here are my current files: Views.py from django.urls import reverse from django.contrib import messages from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.db import models, transaction from .models import DeviceInformation, Projects, ApiTokens from .forms import ProjectForm from django.db.models import Count, ExpressionWrapper, F, FloatField @login_required(login_url="/accounts/login") def dashboard(request): devices = get_devices_without_project() projects = get_queryset('Projects') tokens = get_queryset('ApiTokens') context = {'devices': devices, 'projects': projects, 'tokens': tokens} return render(request, 'dashboard/index.html', context) def get_devices_without_project(): return DeviceInformation.objects.filter(projects__isnull=True) def get_queryset(model): if model == 'Projects': return Projects.objects.all() elif model == 'ApiTokens': return ApiTokens.objects.all() @login_required(login_url="/accounts/login") def create_project(request): if request.method == 'POST': form … -
From Django 1.11 onwards, context passed in render method should be a dictionary rather than a Context object. Then how context.render_context works?
render() in django.shortcuts calls render_to_string method of loader module, which calls render method of Template class by creating a Template object. Till now, context is a dictionary. Inside render method in Template class, context.render_context.push_state(self): How does this works? Because render_context is an attribute of Context class which gets assigned a RenderContext object. So, how context being not an instance of Context class can access its attribute? -
Field expected a number but got <django.db.models.fields.IntegerField>
from django.db import models from django.contrib.auth.models import User from django.utils.text import slugify class Quiz_Model(models.Model): quiz_name = models.CharField(max_length = 30) slug = models.SlugField(max_length = 30, default = '', blank = True) test_number = models.IntegerField(default = 0) max_test_number = models.IntegerField(default = 0) first_boundary = models.IntegerField(default = 0) last_boundary = models.IntegerField(default = 1) show_number = models.BooleanField(default = False) tests = models.TextField() user = models.ForeignKey(User, on_delete = models.CASCADE, default = '') def save(self, *args, **kwargs): if not self.last_boundary: self.last_boundary = self.max_test_number self.slug = slugify(self.quiz_name) super(Quiz_Model, self).save(*args, **kwargs) def __str__ (self): return self.quiz_name I keep gettings this error :TypeError: Field 'last_boundary' expected a number but got <django.db.models.fields.IntegerField>. -
Grouping data when you’ve unique together on foreign keys
Model student=models.FK(Student) grades=models.FK(Grades) unique together is true And i want to query data like [ …student, grades:[…gradeobjects] ] All grades objects related to student should come under the student details -
Mpeg Dash in Django
I was researching ways to stream videos served from the server when I came across MPEG-DASH. I also learned that both Netflix and YouTube use MPEG-DASH for video streaming. Since I'm using Django in the backend of my project, I searched for information on implementing MPEG-DASH in Django, but I couldn't find any relevant details. Could you please provide a comprehensive guide on how to use MPEG-DASH in Django? -
How do I display new posts in bootstrap cards?
I made this website and I wanted to use bootstrap cards in it to display the post I managed to put them in the position I wanted but the cards have same information I want each card to have the info of the new posts that the user update but when I delete one of the cards then the grid gets messed up how should I display new posts in each cards? if I need to post more codes please let me know Thanks in advance user_posts.html {% extends "online_shop/base.html" %} {% block content %} <div style="margin-top: 20px"></div> <h1 class="text-left" class="mb-3" style="font-family: Georgia, serif;">{{ view.kwargs.username }} ({{ page_obj.paginator.count }})</h1> <div style="margin-top: 20px"></div> {% for post in posts %} <div class="card-deck"> <div class="card" style="margin-top: 15px;"> <img class="card-img-top" src="{{ post.image.url }}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ post.title }}</h5> <p class="card-text">{{ post.content|truncatewords_html:16 }}</p> <p class="text-muted" style="margin-top: 10px;">Price: <i class="fa fa-usd" aria-hidden="true"></i> {{ post.price }}</p> </div> <div style="margin-left: 10px; margin-top: -30px; padding: 10px;"> {% if user.is_authenticated %} {% if user == post.author%} <a href="{% url 'update' post.id %}" class="btn btn-outline-primary btn-small" >Edit</a> <a href="{% url 'delete' post.id %}" class="btn btn-outline-danger btn-small" >Delete <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash" viewBox="0 0 16 … -
How to redirect next page after successfully login with flutter?
I create a simple login app with flutter. Backend is simple Jwt. After successfully login, Can not redirect to other page please help This is login page code //login buttom SizedBox( width: 360, child: Padding( padding: const EdgeInsets.only(top: 48.0), child: ElevatedButton( onPressed: () { authController.loginUser(); }, style: ElevatedButton.styleFrom( backgroundColor: const Color.fromARGB(255, 40, 41, 131), padding: const EdgeInsets.only( top: 16, bottom: 16, )), child: const Text( 'ログイン ', style: TextStyle( color: Colors.white, fontSize: 16, fontWeight: FontWeight.w700), ), ), ), ), //end login buttom const SizedBox( height: 60, ), ], ), ), ); } } This is auth controller code class AuthController { TextEditingController emailController = TextEditingController(); TextEditingController passwordController = TextEditingController(); Future loginUser() async { const url = 'http://127.0.0.1:8000/api/v1/login/'; var response = await http.post(Uri.parse(url), headers: { "content-type": "application/json", "accept": "application/json", "access": "Access-Control-Allow-Origin: *", "allow": "POST, OPTIONS", }, body: jsonEncode({ "email": emailController.text, "password": passwordController.text, })); if (response.statusCode == 200) { var loginArr = json.decode(response.body); print('Home'); // save this token in shared prefrences and make user logged in and navigate print(loginArr['token']); } else {} } } I try to fix this error please help me.how to navigate to other page after successfully login -
Django firebase phone auth
is there module for Django which working with Firebase and can use Firebase to send sms to phone, I use django-phone-auth , but its not working with Firebase. Thanks you.