Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django static files 404 errors just for one folder and all images
I'm integrating a theme into my project. Some of the static files are found, but I get two types 404 errors. I'd appreciate any help. The first type (all images): For the line <img class="rounded-circle" src="{% static 'sleek-bootstrap/source/assets/img/user/u6.jpg" alt="Image' %}"> I get the error "GET /static/sleek-bootstrap/source/assets/img/user/u6.jpg%22%20alt%3D%22Image 404 1958 The file /static/sleek-bootstrap/source/assets/img/user/u6.jpg does exist, but somehow Django adds %22%20alt%3D%22Image to the name, so of course it can't find it. It does this for all the image files in the template The second type (one folder): for the line <script src="{% static 'sleek-bootstrap/source/assets/plugins/daterangepicker/moment.min.js' %}"> ></script> I get the error "GET /static/sleek-bootstrap/source/assets/plugins/daterangepicker/moment.min.js HTTP/1.1" HTTP/1.1" 404 1958 Django finds all the files in the path /static/sleek-bootstrap/source/assets/plugins/, except those in the daterangepicker plugin folder. -
Practices for Using Virtual Environments in Python Development
Could someone please explain the following: What are some best practices for using virtual environments effectively in Python projects? Are there any common pitfalls or misconceptions to watch out for when working with virtual environments? Does python devlopers use virtual environment in their works ? And how does this help them? -
how to check that the bot is running in telethon
i tried Redis before it, still not working i want to get informations from bot and send them to web page. i want check the bot its running or not, checking that in another file. this is my simple code, help me to complete it from telethon.sync import TelegramClient, events import cfg api_id = cfg.API_ID api_hash = cfg.API_HASH bot = TelegramClient('bot', api_id, api_hash) bot.start() @bot.on(events.NewMessage) async def my_event_handler(event): if 'hello' in event.raw_text: await event.reply('hi!') bot.run_until_disconnected() -
Django crispy-form, data from the form is not saved in the database
I'm just starting my adventure with Django. I wrote a small application in which, of course, there is a form that collects data from the user. This form in the standard version of Django doesn't look nice. I found information about crispy-form on the Internet and added it to my project. I managed to create a form that I like, but there is a problem. I cannot save the data retrieved from the form to the database. Previously, when I had a Django form, in the views.py file, the function handling this form saved the retrieved data to the database. Now that it's crispy-form I don't want to save. My knowledge is too little to be able to do it, hence my request to you for help. Can you take a look at the codes below and tell me what I'm doing wrong? forms.py from django.forms import ModelForm from crispy_forms.helper import FormHelper from .models import Firma, DaneKsiegowe from django import forms from django.urls import reverse from crispy_forms.bootstrap import Field, TabHolder, Tab from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset class FormNowaFirma(forms.Form): nazwa = forms.CharField(required=True, max_length=120) typ_ksiegowosc = forms.ChoiceField( choices=(("ryczałt ewidencjonowany","ryczałt ewidencjonowany"),("ryczałt ewidencjonowany bez VAT","ryczałt ewidencjonowany bez VAT"), ("KPiR … -
RoutablePageMixin working locally but not on Heroku
I'm in the process of gradually upgrading an old Wagtail CMS website. I've just upgraded from Wagtail V2.13.5 to 2.15.6, including upgrading from Django 3.1 to 3.2, and Python from 3.8 to 3.10. The website is working 100% fine on my local dev copy (Win10), and 95% fine on my Heroku staging environment. However, the parts of the site that uses RoutablePageMixin are not working on my Heroku staging environment (Heroku-22 stack). The website is a fairly basic blog, with an index page ('/explore/') below the homepage, and I'm using RoutablePageMixin to create a 'latest' page ('/explore/latest/') to display the 5 most recent posts below that. This '/explore/' and '/explore/latest/' pages work fine locally, but on my Heroku staging environment '/explore/' is fine but '/explore/latest/' just displays a 404 error ('rasied by wagtail.core.views.serve)'. There's nothing in the Heroku logs to explain why this is, it's just not recognising the @route(r'^latest/$') at all. from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.db import models from django.shortcuts import render, redirect from modelcluster.fields import ParentalKey, ParentalManyToManyField from modelcluster.contrib.taggit import ClusterTaggableManager from taggit.models import TaggedItemBase from wagtail.api import APIField from wagtail.core.models import Page, Orderable from wagtail.contrib.routable_page.models import RoutablePageMixin, route # Location Index Page class LocationIndexPage(RoutablePageMixin,Page): … -
How to have multiple versions of website (with different type of content)?
I need a little bit of help. I'm working on a Django project, it's like a blog. I have implemented localization and added couple languages. Now I would like to develop a customized content for specific regions. Current set up it like this: http://127.0.0.1:8000/en/ I have one content and 3 languages: content - en (English) - http://127.0.0.1:8000/en/ - de (German) - http://127.0.0.1:8000/de/ - ar (Arabic) - http://127.0.0.1:8000/ar/ I used django-parler so every article can be provided in all 3 languages. Now I'd like to have more content - let's say content specific to specific region, it would look like this: Global content - en (English) - http://127.0.0.1:8000/en/glo/ (content on English for global readers) - de (German) - http://127.0.0.1:8000/de/glo/ (content German for global readers) - ar (Arabic) - http://127.0.0.1:8000/ar/glo/ (content on Arabic for global readers) German content - en (English) - http://127.0.0.1:8000/en/de/ (content on English for German region) - de (German) - http://127.0.0.1:8000/de/de/ (content German for German region) - ar (Arabic) - http://127.0.0.1:8000/ar/de/ (content on Arabic for German region) Middle East content - en (English) - http://127.0.0.1:8000/en/me/ (content on English for Middle East readers) - de (German) - http://127.0.0.1:8000/de/me/ (content German for Middle East readers) - ar (Arabic) - http://127.0.0.1:8000/ar/me/ (content … -
How to override the internal read query of class or method in django
I wan't to override the internal read query present inside my class or method. I wan't to write generalised solution so that it should work on the class or method where I wan't to modify the read queries. I am trying to do using decorators, middleware and metaclasses but I am unable to access the internal read query of function. I just wan't to modify it to take it from read replica. but I can't do this to all read query. I can only modify read query to take it from read replica for few class or method. master_models.CarTransmission.objects.filter( # pylint: disable=E1101 variant_id__in=self.variant_ids ).values_list(*self.specifications, named=True) modify this to- master_models.CarTransmission.objects.using('replica').filter( # pylint: disable=E1101 variant_id__in=self.variant_ids ).values_list(*self.specifications, named=True) original- model = get_object_or_404(master_models.Model,slug=slug) modify this to - model = get_object_or_404(master_models.Model.objects.using('replica'),slug=slug) The logic that I am expecting should be specific to class and method. I f i apply that on class all the method present should modify all the internal read query. Is it possible or I should go to all query and write .using('replica') pleaser don't provide solution which work for some specific app like using routing to move it to redirect to replica as they will be going to work on whole project … -
AssertionError when the serializer does not find an object in Django Login
I'm creating an app in django with custom registration and login that behave like forms, but when I log in with wrong credentials, the program returns an AssertionError. . views.py ... def post(self, request): serializer = LoginSerializer(data=request.data) if serializer.is_valid(): email = serializer.validated_data['email'] password = serializer.validated_data['password'] user = authenticate(email=email, password=password) if user: login(request, user) return redirect('/') else: return Response({'erro': 'user nao encontrado'}) serializers.py class LoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) password = serializers.CharField(write_only=True, style={'input_type': 'password'}) class Meta: model = Profile fields = ['email', 'password'] def validate(self, attrs): email = attrs.get('email') password = attrs.get('password') if email and password: user = authenticate(email=email, password=password) if not user: raise serializers.ValidationError('O usuário não existe') attrs['user'] = user return attrs I've already tried a try and except, as well as adding a Response if the user doesn't exist, but still, nothing works. -
Adding the django-parler to django admin pages?
I'm workin on my django project and I added django-parler to my django project. I have added parler in my models.py and that looks like this: class Category(TranslatableModel): translations = TranslatedFields( category_name=models.CharField(max_length=255, verbose_name="Category name"), ) parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) slug = models.SlugField(max_length=200, unique=True, editable=False, default='') def clean(self): if self.parent: if self.parent.parent: raise ValidationError("A category that already has a parent cannot be set as the parent of another category.") def save(self, *args, **kwargs): if not self.slug: base_slug = slugify(self.safe_translation_getter('category_name', self.category_name)) # Ensure uniqueness of the slug slug = base_slug counter = 1 while Category.objects.filter(slug=slug).exists(): slug = f"{base_slug}-{counter}" counter += 1 self.slug = slug super(Category, self).save(*args, **kwargs) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['category_name'] def __str__(self): return self.safe_translation_getter('category_name', self.category_name) Tricky part is that I want slug to be translated not just category name. Also, in admin.py I did it like this: admin.site.register(Category, TranslatableAdmin) And I got it like on images below. I'm happy with the result. What you see on first image, is when you click on categories on admin side, and if I have multiple translations it makes entry for every language. On second image you see how it looks like when you are adding … -
Django 404 when connecting to websocket router wh
I'm trying to write my first Django project using websockets. I use django channels. And everything worked fine until the time to integrate react, nginx and django came. Now i get: Could not connect to wss://our.web.site/ws/notifications/id/?token={my_token} Request URL: https://our.web.site/ws/notifications/id/?token={my_token} Request Method: GET Status Code: 404 Not Found my asgi.py: import os from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application from apps.notifications.middlewares import JwtAuthMiddlewareStack from apps.notifications.routing import websocket_urlpatterns os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") # application = get_asgi_application() application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( JwtAuthMiddlewareStack(URLRouter(websocket_urlpatterns)) ), } ) my routing.py: from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r"ws/notifications/(?P<user_id>\w+)/$", consumers.NotificationConsumer.as_asgi()), ] my consumers.py: import json from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer from apps.notifications.models import Notification, OnlineUser class NotificationConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.user = None self.pool_name = None async def connect(self): self.user = self.scope["user"] self.pool_name = f"user_id_{self.user.id}" await self.accept() await self.channel_layer.group_add( self.pool_name, self.channel_name, ) await self.add_online_user() async def disconnect(self, close_code): await self.remove_online_user() await self.channel_layer.group_discard(self.pool_name, self.channel_name) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] await self.channel_layer.group_send(self.pool_name, {"type": "read_message", "message": message}) async def read_message(self, event): message = event["message"] await self.mark_notifications_as_read(message) await self.send(text_data=json.dumps({"message": message, "message_type": "read_message"}, ensure_ascii=False)) async def notification_message(self, event): message … -
How to change model field names among themselves in Django?
I have created a model in my Django project. By mistake, I set the date_created and date_updated fields wrong as follows: class Article(models.Model): date_created = models.DateTimeField(auto_now=True) date_updated = models.DateTimeField(auto_now_add=True) I should have set date_created as auto_now_add=True, and date_updated as auto_now=True. Now, when I want to change the model names by each other as class Article(models.Model): date_updated = models.DateTimeField(auto_now=True) date_created = models.DateTimeField(auto_now_add=True) Django detects that I just changed the definition of the fields and creates a migration as operations = [ migrations.AlterField( model_name='article', name='date_created', field=models.DateTimeField(auto_now_add=True), ), migrations.AlterField( model_name='article', name='date_updated', field=models.DateTimeField(auto_now=True), ), ] But I actually renamed them. When I manually set the migrations as RenameField, it simply does not work because Django detects that I have not created a migration for the changes that I made. Renaming with a different name could be solution, but I need to keep the field names. What can I do in this situation? -
In Django I have been getting this error can anyone help me to solve this
while learning Django created static folder and templates folder and imported code from bootstrap and while running the server I have been getting this errorThis image with Debug = True in settings.py fileAnd this image with Debug = False in settings.py file I need this to solve my error -
Russian set default language when user opened website in Chrome browser
In base.html there is a dropdown to change the language. I think get_current_language comes in Russian Even if en is the default language, when entering kedi.uz, the default language is Russian. How can I set the default language for the user when he first logs in? repo link: https://github.com/bahrom04/ekologiya/blob/master/templates/base.html#L56 # base.py LANGUAGE_CODE = "en-us" this is the dropdown to change language and it stores django_language into session. <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go"> </form> For new users the session will be empty but language of website is on russian language in Chrome browser but if i open it on FireFox, default language of website will be english. My both Chrome and Firefox on english -
execution error in javascript post event $.post when in dev everything is ok
My javascript code raise an error in my production server (nginx+gunicorn) when all is ok in dev. here is my js many thanks for your help <script> const findLoc = () => { const success = (position) => { const latitude = position.coords.latitude; const longitude = position.coords.longitude; var data = {'latitude': latitude, 'longitude': longitude }; data.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val(); console.log('Location is on'); console.log(data); document.getElementById("LocationLat").innerHTML = latitude; document.getElementById("LocationLon").innerHTML = longitude; ----->$.post("gps/", data,function(response) { // La réponse est maintenant disponible dans la variable 'response' console.log('Réponse reçue:', response); document.getElementById("postdata").innerHTML = response; $('.spinner-border').hide(); // Faites quelque chose avec les données, par exemple mettre à jour le contenu de la page }).fail(function(xhr, status, error) { // En cas d'échec de la requête, affichez l'erreur console.log('Erreur lors de la requête:', status, error); }); } const error = () => { console.log('Location gathering Not allowed') $('.spinner-border').hide(); document.getElementById("postdata").innerHTML ="Activate position in your browser !" } navigator.geolocation.getCurrentPosition(success,error); } </script> the error is raised by this instruction ---->$.post here the console in the browser : enter image description here urls.py urlpatterns = [ path('admin/', admin.site.urls), path('gps/',views.home_view), views.py def home_view(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') if request.method == 'POST': Latitude = float(request.POST.get('latitude')) Longitude = float(request.POST.get('longitude')) … -
WSL(Ubuntu 22.04 LTS) djnago project unable to connect to Mysql Workbench, but mysql -u root -p working
I'm running my django project in WSL(ubuntu 22.04 LTS), recently moved from windows, when i create a db in windows and migrate the db tables are created but in linux the db itself when created in mysql terminal, not shown in mysql workbench? The problem is that the project in windows was running fine with mysql but since i shifted to linux and using mysql workbench, the database isnt created in mysql wrorkbench from mysql terminal, seems like my project and mysql isnt connected. can anyone help? When i create a database in mysql terminal in my vscode with mysql -u root -p create database "xyz"; the database is created and i migrate the tables in db but this database is just not visible in mysql workbench I tried creating a db in mysql workbench and then adding that db name to settings.py but the db that is created in workbench isnt connected to django project -
Can someone explain to me what "data = validated_data.copy()" means?
I wonder why the create method does not process the data directly but has to copy it into data and then process it indirectly, while the returned result is also the processed user. class UserSerializer(serializers.ModelSerializer): alumni = AlumniSerializer() def to_representation(self, instance): req = super().to_representation(instance) if instance.avatar: req['avatar'] = instance.avatar.url if instance.cover: req['cover'] = instance.cover.url return req def create(self, validated_data): data = validated_data.copy() user = User(**data) user.set_password(user.password) user.save() return user class Meta: model = User fields = ['id', 'first_name', 'last_name', 'username', 'password', 'email', 'avatar', 'cover', 'alumni'] extra_kwargs = { 'password': { 'write_only': True } } -
Profile Picture Not Showing
I am able to upload a profile picture and it goes to the database. I have a "print(profile.profile_picture)" in my views.py that will correctly print the current profile picture in the console when I save. For some reason the profile picture will not show though, my "{% if profile.profile_picture %}" in my profile.html isn't even picking anything up. [] VIEWS.PY= @login_required def profile(request): profile, created = Profile.objects.get_or_create(user=request.user) print(profile.profile_picture) if request.method == 'POST': form = ProfileForm(request.POST, request.FILES, instance=profile) if form.is_valid(): form.instance.user = request.user form.save() return redirect('base:profile') # Redirect to the home page after form submission else: form = ProfileForm(instance=profile) return render(request, 'profile.html', {'form': form}) PROFILE.HTML= <div class="ProfilePage"> <form method="POST" enctype="multipart/form-data" class="profile-form"> {% csrf_token %} <div class="form-group"> <label for="id_username">Username:</label> <input type="text" id="id_username" value="{{ request.user.username }}" readonly> </div> <div class="form-group"> <label for="id_bio">Bio:</label> <textarea id="id_bio" name="bio" rows="4" cols="50" required>{{ form.bio.value }} </textarea> </div> <div class="form-group"> <label for="id_profile_picture">Profile Picture:</label> <input type="file" id="id_profile_picture" name="profile_picture" accept="image/*"> </div> {% if profile.profile_picture %} <div class="form-group"> <label>Profile Picture Preview:</label><br> <img src="{{ profile.profile_picture.url }}" alt="Profile Picture" style="max-width: 500px;"> </div> {% endif %} <button type="submit" class="btn-submit">Save</button> </form> </div> FORMS.PY= from django import forms from .models import Profile class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['bio', 'profile_picture'] I can give more … -
Adding the django-parler to admin pages?
I added django-parler to my django project. I have added parler in my models.py and that looks like this: class Category(TranslatableModel): translations = TranslatedFields( category_name=models.CharField(max_length=255, verbose_name="Category name"), ) parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) slug = models.SlugField(max_length=200, unique=True, editable=False, default='') def clean(self): if self.parent: if self.parent.parent: raise ValidationError("A category that already has a parent cannot be set as the parent of another category.") def save(self, *args, **kwargs): if not self.slug: base_slug = slugify(self.safe_translation_getter('category_name', self.category_name)) # Ensure uniqueness of the slug slug = base_slug counter = 1 while Category.objects.filter(slug=slug).exists(): slug = f"{base_slug}-{counter}" counter += 1 self.slug = slug super(Category, self).save(*args, **kwargs) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['category_name'] def __str__(self): return self.safe_translation_getter('category_name', self.category_name) Tricky part is that I want slug to be translated not just category name. Also, in admin.py I did it like this: admin.site.register(Category, TranslatableAdmin) And I got it like on images below. I'm happy with the result. What you see on first image, is when you click on categories on admin side, and if I have multiple translations it makes entry for every language. On second image you see how it looks like when you are adding categry. Now the question, is it possible … -
ModuleNotFoundError: No module named 'django.db.backends.postgresql' on Ubuntu 24.04
Yesterday I switched to Ubuntu 24.04 LTS from windows and having an issue with my django project and tried every suggestion on the web but no luck. I'm getting below issue: django.core.exceptions.ImproperlyConfigured: 'django.db.backends.postgresql' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'sqlite3' Most of the suggesion on the web telling update django but I'm already using the latest version 5.0.4 Also postgresql is working fine. I'm able to connect it. -
Django/Heroku - Handling ObjectDoesNotExist Exception When Pushing Data from API to Django Database
My django application receives data from an API. It's very unlikely the API will send incorrect information, but I am trying to cover the possibility the API may send data that would return ObjectDoesNotExist from malicious attempts. Below is my try at how I could handle the exception, by leaving the data 2 tries. After that, I want it to stop pushing the data. I left a few print statement to track the tries are being executed. But none of them are getting printed. This makes me think that the data received from the API is considered as valid (because it exists) and its only when the data is pushed to the database that the application realises it does not exist. Any suggestion on how I could handle this? (I am hoping I am clear) the function: def API_data(request): userprofile_id = request.GET.get('userprofile_id', '') venue_id = request.GET.get('venue_id', '') user = UserProfile.objects.get(id=userprofile_id) venue = Venue.objects.get(id=venue_id) venue_loyalty_point_rule = VenueLoyaltyPointRule.objects.get(venue=venue) scans = ItemisedLoyaltyCard.objects.filter( user_id=user.id, venue=venue) is_point_valid = loyalty_card_validation_rule( scans, user, venue, venue_loyalty_point_rule) if is_point_valid: try_count = 0 max_retries = 2 # Define the maximum number of retries while try_count < max_retries: try: ItemisedLoyaltyCard.objects.create( user_id=user.id, venue=venue, add_points=venue_loyalty_point_rule.points) # If creation succeeds, set data and break … -
Cannot get response for more than first or several first requests with Django and Apache?
I have started to learn Python, then Django in practice by way of executing tutorial codes in Python IDLE. Indeed as maybe the code is of old versions the code running not always works well. Especially I am stacked upon running Django with Apache 2.4 through mod_wsgi. I have done it at first two-three weeks ago, and then main issue was that Django requests on apache (on localhost, not on built-in localhost:8000) completed normally just the two-three times, then I should wait almost indefinitely to see the response from request, or without it. This week I returned to this example Django plus Apache, but it detiorated to the level that just first request is done, the second one almost not executed in a moment as it should be, or even not at all, the next ones - not at all untill Apache server restart in Apache24\bin httpd command. I have extracted Apache lounge (on Windows 10) in C:\Apache24 folder as it should be. Indeed when extracting I deleted two files (readme.txt..)as evidently not neccesarily files over nested Apache24 folder, so maybe I should extract to C:\Apache24\Apache24. When I extracted to the nested folder --- and run from C:\Apache24\Apache24\bin -- the … -
Django celery media folder backup issue
I create a library to get backup to Google Drive using with Google Drive api in python. Actually its work well but when I use with celery my library, celery do not wait for compress my media folder(I guess). Its every time get backup zipped and encrypted backup to Google Drive but its empty. If I go to my django app container and I write my custom command to get media backup, its work well. I have been dealing with 2 week. Is someone can help me about celery or my library. Tried: asycn compress process. my library -> https://github.com/ylrmali/py-googledrive (README.md is not updated) # gcapi/dbhandler/management/commands/pymedia_backup.py import asyncio from django.core.management.base import BaseCommand, CommandParser from django.conf import settings from gcapi.cryption import Cryption from gcapi.drive import GCDrive from gcapi.compress import compress_folder import os import tarfile import datetime class Command(BaseCommand): help = "Restore database" def add_arguments(self, parser: CommandParser): parser.add_argument( '--encrypt', action='store_true', help='Encrypt media folder' ) parser.add_argument( '--compress', action='store_true', help="Compress media folder" ) def __success_output(self, text): """ Success output """ return self.stdout.write(self.style.SUCCESS(str(text))) def __error_output(self, text): """ Success output """ return self.stdout.write(self.style.ERROR(str(text))) def __remove_temp(self, temp_list: list): """ Remove temprary used files """ for file in temp_list: os.remove(file) async def _create_media_tar_async(self, media_folder: str): """ Asynchronously create … -
Django update m2m objects on save
I have a m-2-m rel and i want to update the rel B after any rel A is added via the admin page. Here the details: I have 2 models, Match (rel A) and Player (rel B). I want to update Player.matches_played eveytime a new Match with that player in Match.team1 or Match.team2 is added. How can i achieve this??? the models class Match(models.Model): data=models.DateField(auto_now_add=False,auto_now=False) team1=models.ManyToManyField('players.Player',related_name='team_1') team2=models.ManyToManyField('players.Player',related_name='team_2') score_team1=models.IntegerField(validators=[MinValueValidator(0)]) score_team2=models.IntegerField(validators=[MinValueValidator(0)]) class Player(models.Model): matches_played= models.IntegerField(validators=[MinValueValidator(0)], default=0) I tried signals but in post_save signal {instance.team1} or instance.team1.all() return an empty QuerySet which i believe is correct as the M2M rel is saved later. Then i tried m2m_changed but that signal is not fired with a save via the admin page. What am i missing? @receiver(post_save, sender=Match, dispatch_uid="update_player_game_count") def update_player_games(sender, instance, created, **kwargs): print(f'created {instance.pk}') print(f'created {instance.team1}') print(f'created {instance.team2}') print(f'created {instance.score_team1}') print(instance.team1.all()) @receiver(m2m_changed, sender=Match, dispatch_uid="update_player_game_count") def update_player_game(sender, instance, created, action, **kwargs): print(action) if action == 'post_add': print(action) Thank you very much for you help an alternative which i thought about is to retrieve the data via a property in Player for instance like this, but i think, from a performance point of view, is better to update rows every time a match is added … -
Media not shown on django nginx host
I am currently working on a django project which I deployed to a digitalocean droplet with nginx. The website works, including the staticfiles. After looking at my error.log i saw that it was a permission problem: 2024/04/27 18:58:19 [error] 130139#130139: *194 open() "/home/project/project/media/gallery/IMG_9510.jpeg" failed (13: Permission denied) And when excecuting the namei command, this is the response: root@host:~# namei -l /home/project/project/media/gallery/IMG_9510.jpeg f: /home/refugium/refugium/media/gallery/IMG_9510.jpeg drwxr-xr-x root root / drwxr-xr-x root root home drwxr-x--- project_user project_user project drwxrwxr-x project_user project_user project drwxr-xr-x www-data www-data media drwxr-xr-x www-data www-data gallery -rwxr-xr-x www-data www-data IMG_9510.jpeg So the permissions seem to be fine. For the last check I shortly changed the user in my nginx.conf to root. After that it worked. Did I miss anything? This is my file in sites-available: server { listen 80; server_name refugium-romontberg.ch; location = /favicon.ico { access_log off; log_not_found off; } location /media/ { alias /home/refugium/refugium/media/; } location /static/ { alias /home/refugium/refugium/staticfiles/; } location / { client_max_body_size 200M; include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Thanks -
Django unit test fixing database row id
from django.test import TestCase class DefTests(TestCase): def setUp(self): # first made the label UserType(label="mylabel").save() ## UserType is model object, and I made the first row , the id is supposed to be 1 def test_my(self): u = UserType.objects.get(id=1) # UserType.DoesNotExis error I guess in test mode real insert is not executed, so id is not fixed. Am I correct? Then, Is there any way to fix the id in advance before doing test_****?