Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Downloading someone's images with an API
Hello i am developing a blog project in django. For each post there are images attached to it I want to share my project with some friends ( by them cloning the github repo ), but don't want them to download all the images. So i have made a new app on my project, an API with django-rest-framework that allow them to get the list of the images from my project Once someone get the list, it create new instances of Post and ImagePost in the DB, based on the json value They get the new instance in their DB, but they don't get the images, they only get the filepath I have no idea how to give them the images using the API, and make the images goes into their project. Thank you So for my models: class Post(models.Model): title = models.CharField(max_length=250) body = models.TextField() author = models.ForeignKey(User, related_name='blog_posts', on_delete=models.CASCADE) images = models.ManyToManyField(ImagePost, related_name='images', blank=True) class ImagePost(models.Model): image = models.ImageField(upload_to='blog_posts/', blank=True) And my API classes : class PostList(ListAPIView): queryset = Post.objects.filter(archived=False) serializer_class = PostSerializer class ImagePostList(ListAPIView): queryset = ImagePost.objects.all() serializer_class = ImagePostSerializer class ImagePostSerializer(ModelSerializer): class Meta: model = ImagePost fields = ["id", "image" ] The urls : path('post/list/', views.PostList.as_view(), … -
Troubleshooting AUTH_USER_MODEL Migration Error in Django App
I am working on a Django application where I've set up **AUTH_USER_MODEL **with the name **User **for authentication purposes. However, when I tried to run migrations, I encountered the following error: django.db.utils.OperationalError: (1005, 'Can't create table myAppDjango.django_admin_log (errno: 150 "Foreign key constraint is incorrectly formed")'). Could someone assist me in properly generating my model and Django migrations to resolve this issue? i used this commande to migrate model: python manage.py makemigrations python manage.py migrate -
How can i optimizate Djnago ORM request?
how can optimize the ORM request, getting the GDD takes a lot of time. I think problem with subquery, but through realation "commune__communemeteo" it takes even longer, (communemeteo about 1 million). communes = communes.filter( communeattribute__date__year=year, communeattribute__date__month=month, communeattribute__date__day__range=( days.get("start_date"), days.get("end_date"), ), ) gdd_subquery = ( CommuneMeteo.objects.filter( date__range=(start_date, end_date), commune_id=OuterRef("id") ) .values("commune_id") .annotate(gdd=Sum((F("temp_min") + F("temp_max")) / Value(2) - Value(TBASE))) .values("gdd")[:1] ) communes = communes.annotate( plant=Value(f"{plant}", output_field=CharField()), size=Sum(F("communeattribute__planted_area"), output_field=FloatField()), gdd=Subquery(gdd_subquery, output_field=FloatField()), ) ``` -
How to return the error in JSON format instead of HTML in REST framework?
I want to make an error handler exception to return the error 404 instead of this html. how can i do this ? i tried the following code but it didn't work for me from rest_framework.views import exception_handler from rest_framework.response import Response from rest_framework import status from django.http import Http404 def custom_exception_handler(exc, context): # Call the default exception handler first, # to get the standard error response. response = exception_handler(exc, context) # Now add the HTTP 404 handling if isinstance(exc, Http404): custom_response_data = { "error": "page not found" } return Response(custom_response_data, status=status.HTTP_404_NOT_FOUND) # Return the default response if the exception handled is not a Http404 return response -
testing nginx in github actions
I'm trying to test the deployment of a django app with github actions and I wanted to test if Nginx accepts request correctly on a certain url path with curl command. the actions yaml file is as follows: name: Test deployment on: push: jobs: automated_deployment: name: Deployment runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - name: Execute auto-deployment run: | bash auto-deployment.bash nginx_test: name: Set up server IP and check Nginx needs: automated_deployment runs-on: ubuntu-latest steps: - name: Generate IP address and Check Nginx run: | # Generate the IP address EXTERNAL_IP=$(curl -s ifconfig.me) echo "External IP from script: $EXTERNAL_IP" # Use the EXTERNAL_IP variable # Check Nginx with curl curl -I "http://$EXTERNAL_IP/conectdb/" exit_code=$? if [ $exit_code -eq 0 ]; then echo "Nginx is running." else echo "Failed to connect to Nginx. Exit code: $exit_code" exit $exit_code fi In fact, the error generated in the run is curl: (28) Failed to connect to 20.57.44.37 port 80 after 134130 ms: Connection timed out Error: Process completed with exit code 28. which means the script generates the correct ip adress but cannot connect to it on port 80. I appreciate any advice about this subject because I'm not even sur … -
Celery and Celery Beat not reading Django Settings
I recently upgraded Django to 4.x from 3.x and all other deps as well. But since the upgrade celery and celery beat do not seem to recognize the settings that begin with CELERY_ and instead I had to provide broker URL as an ENV variable separately for celery to work. But now celery-beat is not picking the right scheduler setting from DJANGO Settings and defaults to a file based scheduler. Would appreciate any thoughts on this as been searching for an answer for a few days now. For Celery I was able to add ENV variable and move forward but still would prefer a way to read the settings from Django -
Django error: IntegrityError: UNIQUE constraint failed: auth_user.username
My views.py file is: from django.shortcuts import redirect, render from django.contrib.auth.models import User from django.contrib import messages def index(request): return render(request, "index.html") def signup(request): if request.method == "POST": username = request.POST['uname'] first_name = request.POST['fname'] last_name = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] myuser = User.objects.create_user(username=username, password=pass1, email=email) myuser.first_name = first_name myuser.last_name = last_name myuser.save() messages.success(request, "Your account has been created successfully...") # function Name = 'login' return redirect('login') return render(request, "signup.html") def login(request): return render(request, "login.html") def signout(request): pass The error is: UNIQUE constraint failed: auth_user.username So whats the cause for it ? And How it can be resolved? -
Django: Adding unique together errors to one of the involved fields
Note: I asked this question on the Django forum, but since I did not receive any answers there, I'm asking here, too. I’m building an application with multi-tenancy, meaning that all data is associated to a tenant model. When creating models, I often want to validate uniqueness of e.g. the name field. However, the uniqueness is only required per tenant, not globally, which is why I’m using unique_together (or UniqueConstraint, found that too late, but will migrate). However, when the uniqueness is violated, a non_field_error is added. I would however prefer to add this error to the name field, as the tenant field is implicit and not visible to the user (the tenant is always the tenant of the logged in user, and can’t be chosen). Any hints on how I could achieve that, preferably in the model or alternatively in a form? I thought about first validating the model, and then moving the error from the non_field_errors to the name field, but that feels kind of wrong. Starting point would be this code: class Company(models.Model): tenant = models.ForeignKey(Tenant, on_delete=models.PROTECT) name = models.CharField(max_length=255) class Meta: unique_together = ('tenant', 'name') -
Django REST Framework: TypeError: 'ManyRelatedManager' object is not iterable for nested M2M serializer
I have two models: Recipe and Ingredient which are connected by ManyToMany through RecipeIngredient: class Recipe(models.Model): ... ingredients = models.ManyToManyField( 'Ingredient', through='RecipeIngredient', ) ... class Ingredient(models.Model): name = models.CharField( max_length=LENGTH_FOR_CHARFIELD ) measurement_unit = models.CharField( max_length=LENGTH_FOR_CHARFIELD ) class RecipeIngredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) amount = models.PositiveIntegerField() I also have a serializer class for Recipe with nested serializer for RecipeIngredient: class IngredientRecipeSerializerForWrite(serializers.ModelSerializer): class Meta: model = RecipeIngredient fields = ('ingredient_id', 'amount') def create(self, validated_data): recipe_ingredient = RecipeIngredient.objects.create(**self.initial_data) return recipe_ingredient class RecipeSerializerForWrite(serializers.ModelSerializer): ingredients = IngredientRecipeSerializerForWrite(many=True) class Meta: model = Recipe fields = ( ... 'ingredients', ... ) def validate(self, attrs): attrs['ingredients'] = self.initial_data['ingredients'] for item in attrs['ingredients']: item['ingredient_id'] = item.pop('id') return attrs def create(self, validated_data): tags = validated_data.pop('tags') ingredients = validated_data.pop('ingredients') recipe = Recipe.objects.create(**validated_data) recipe.tags.set(tags) for item in ingredients: item['recipe'] = recipe ingredients_serializer = IngredientRecipeSerializerForWrite( data=item ) ingredients_serializer.is_valid() ingredients_serializer.save() return recipe Data from request must come in a format: "ingredients": [ { "id": {{firstIndredientId}}, "amount": {{firstIngredientAmount}} }, { "id": {{secondIndredientId}}, "amount": {{secondIngredientAmount}} } I'm trying to pass the data to IngredientRecipeSerializerForWrite and create objects there, but i'm getting error TypeError: 'ManyRelatedManager' object is not iterable I'm using serializer for RecipeIngredient model because i need to pass amount value to … -
How to use different timezone with Django channels?
How to use different timezone with subscriptions? i have middleware class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): user = request.UserOrError.user user_location = user.get_active_location if hasattr(user, "locations") else None if user_location and user_location.time_zone: user_timezone = pytz.timezone(user_location.time_zone) timezone.activate(user_timezone) return self.get_response(request) @strawberry_django.field() def date_created(self, info: Info) -> datetime: return self.date_created but it doesn't work for channels, I get the same time for all countries. How to activate a time zone for each country for subscriptions? -
Get javascript variable's value in Django url template tag, but the following error pops up
In my django app, when i change the car in my car choice in the form, this error pops up: [15/Apr/2024 15:16:49] "GET /unavailable-dates/10/?start_date=2024-01-01&end_date=2024-12-31 HTTP/1.1" 404 2932 urls.py from django.urls import path from . import views urlpatterns = [ # Other URL patterns path('unavailable-dates/<int:car_id>/', views.get_unavailable_dates, name='unavailable_dates'), ] booking_form.html <!-- Inline JavaScript --> <script> $(document).ready(function(){ $('#id_car').change(function(){ var carId = $(this).val(); // Get selected car ID // Make an AJAX request to fetch unavailable dates for the selected car $.ajax({ url: '/unavailable-dates/' + carId + '/', // URL of the get_unavailable_dates view data: { 'start_date': '2024-01-01', // Example start date, replace with actual value 'end_date': '2024-12-31' // Example end date, replace with actual value }, success: function(data) { // Handle the response data here console.log("Unavailable dates:", data); }, error: function(jqXHR, textStatus, errorThrown) { console.error("AJAX error: " + textStatus + ' : ' + errorThrown); } }); }); }); </script> views.py def get_unavailable_dates(request, car_id): try: car = Car.objects.get(id=car_id) except Car.DoesNotExist: return HttpResponse("Car not found.", status=404) start_date_str = request.GET.get('start_date') end_date_str = request.GET.get('end_date') if not start_date_str or not end_date_str: return HttpResponse("Start date and end date must be provided in the request.", status=400) try: start_date = datetime.strptime(start_date_str, '%Y-%m-%d') end_date = datetime.strptime(end_date_str, '%Y-%m-%d') except ValueError: return HttpResponse("Invalid … -
Allauth SocialConnectView django rest framework
can someone help please, the access token retrieved from Facebook is not being stored in the socialaccount_token table after a successful social login. This prevents my application from using the token later for data retrieval. this is my code from dj_rest_auth.registration.views import SocialConnectView from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter import facebook from allauth.socialaccount.providers.oauth2.client import OAuth2Client class FacebookConnect(SocialConnectView): adapter_class = FacebookOAuth2Adapter client_class = OAuth2Client the data is stored in socialaccount_socialaccount table by default , but nothing stored in socialaccount_socialtoken -
Handle multiple clients in a browser terminal that is created by xtermjs
My browser terminal application runs without problem while it is used by a single client but when another client connects to it and tries to use the same terminal is shown to the new client. Also when i open it in another tab it shows the same terminal too. Defining seperate terminals in xtermjs like termA and termB is not viable since number of clients is not certain. The application runs with django in backend. Xtermjs is only used for visualization and getting user input. A pseudo terminal and bash process handles terminal logic in the django. My first approach was to implement multiprocessing in the django but i failed to achieve it. I am open to different approaches to solve this issue. views.py: import os from django.shortcuts import render import socketio import pty import select import subprocess import struct import fcntl import termios import signal import eventlet async_mode = "eventlet" sio = socketio.Server(async_mode=async_mode) fd = None child_pid = None def index(request): return render(request, "index.html") def set_winsize(fd, row, col, xpix=0, ypix=0): winsize = struct.pack("HHHH", row, col, xpix, ypix) fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize) def read_and_forward_pty_output(): global fd max_read_bytes = 1024 * 20 while True: sio.sleep(0.01) if fd: timeout_sec = 0 (data_ready, _, … -
Rounding off decimals in Django not working as expected?
I am using Django version 3.2.16. In Django I am using below code. Here for example income__ownership is 2500 and the value of amount_field is 14826.So when multiplying 14826 by.25 it gives value as 37.715 and I want the rounded result as 35.72 but Django Round gives result as 36. How to achieve desired result? amount_annotation = ExpressionWrapper( # Use Django's Round function to round the base value to 2 decimal places Round( F(amount_field) * (Cast(F('income__ownership'), FloatField()) / 10000), precision=2, # Round to 2 decimal places output_field=FloatField() ) * 100, # Multiply the rounded value by 100 output_field=IntegerField() ) -
What are the best practises to develope a django project with adminLTE frontend admin pannel and DRF as backend
Please stay away who has no experiance to development of real life projects !! i would like to ask that what is best practices to develop a project is admin pannel.I mean that i'm developing a project in python technology and i have little bit knowladge of python technology and Django framework and DRF. what shoud be the folder structure , should i develop both in just single project like following structure or develope saparate projects. i'm following below structure sholud i continue with same or not? . ├── authentication │ ├── admin.py │ ├── api │ │ └── v1 │ │ ├── backend.py │ │ ├── pagination.py │ │ ├── permissions.py │ │ ├── __pycache__ │ │ ├── serializers.py │ │ ├── urls.py │ │ ├── validations.py │ │ └── views.py │ ├── apps.py │ ├── __init__.py │ ├── migrations`your text` │ ├── models.py │ ├── __pycache__ │ ├── services.py │ ├── templates │ │ ├── base.html │ │ ├── change_password.html │ │ ├── edit_role.html │ │ ├── email_message.html │ │ ├── forgot_password.html │ │ ├── login.html │ │ ├── new_role.html │ │ ├── permission.html │ │ ├── role_list.html │ │ └── subadmin_list.html │ ├── tests.py │ ├── urls.py … -
DisallowedHost at / | Invalid HTTP_HOST header
For no apparent reason that I can think of, I am getting the: Invalid HTTP_HOST header: '13.60.32.132:8000'. You may need to add '13.60.32.132' to ALLOWED_HOSTS. The IP address been correctly added to my settings.py file. I am using Ubuntu 22.04.4 LTS (GNU/Linux 6.5.0-1014-aws x86_64) with the latest version of Django, which is Django 5.0.4 As per SO's requirements, these are the fully reproduceable steps I took which brought me to this issue: I created an Amazon EC2 Instance (free tier). The Outbound NSG settings are as follows: Port Range: 8000 Protocol: TCP Source: 0.0.0.0/0 Port Range: 80 Protocol: TCP Source: 0.0.0.0/0 Port Range: 443 Protocol: TCP Source: 0.0.0.0/0 The Inbound NSG Settings are as follows: Port Range: 443 Protocol: TCP Source: 0.0.0.0/0 I connected to my Ubuntu EC2 Server and successfully cloned my GitHub repository via the ssh methodology. I ran the following commands: sudo apt update sudo apt upgrade sudo apt install git sudo apt install python3 python3-pip sudo apt install python3-venv I then continued to ensure that pip was installed to the latest version, before installing my venv and dependencies, by running the following commands: pip install --upgrade pip cd .ssh/<repository-name> python3 -m venv venv source venv/bin/activate pip … -
TinyMCE renders an extra widget
I use django-tinymce to render TinyMCE widgets in my forms. If updated to the latest version 6.8.3 (2024-02-08), I have two widgets on the same form field instead of one. This is the Django template: {% extends "layout.html" %} {% load i18n %}{% load static %} {% block title %} ... {% endblock %} {% block head %}{{ form.media }}{% endblock %} {% block content %} {% if user.is_authenticated %} <div id="create"> <form id="cascade" class="mt-3" method="post" action="." enctype="multipart/form-data"> {% csrf_token %} {{ form.non_field_errors }} {% for field in form %} {% if field.is_hidden %}{{ field }}{% else %} <div class="mb-3"> <label for="{{ field.id_for_label }}" class="form-label">{{ field.label }}:</label> {{ field }} {% if field.help_text %} <div class="form-text">{{ field.help_text|safe }}</div> {% endif %} <div id="{{ field.auto_id }}" class="invalid-feedback">{{ field.errors }}</div> </div> {% endif %}{% endfor %} <button class="btn btn-primary" type="submit" name="action">{% translate "Submit" %}</button> </form> </div> {% endif %} {% endblock %} This is how the form field content using TinyMCE is actually rendered: <div class="mb-3"> <label for="id_content" class="form-label">Содержимое:</label> <textarea class="form-control tinymce" cols="40" data-mce-conf="{&quot;theme&quot;: &quot;silver&quot;, &quot;height&quot;: 500, &quot;menubar&quot;: false, &quot;plugins&quot;: &quot;autolink,lists,link,image,charmap,preview,hr,searchreplace,code,media,table,paste,help,wordcount&quot;, &quot;contextmenu&quot;: &quot;paste | link image table&quot;, &quot;toolbar&quot;: &quot;bold italic underline strikethrough | bullist numlist | blockquote hr charmap | table | … -
Is there a hook to modify field value in Django?
On any type of Django Field, validators is available where I can hook my own custom validator. I understand I cannot change the value in the validator, it must either return None or django.core.exceptions.ValidationError. What I want to do is I want to change the value of the field itself, before it gets saved. For example, I want to store ISO 3166 Numeric Code as a column: def digit_only(value): if not value.isdigit(): raise ValidationError( _("%(value)s contains a non-digit"), params={"value": value}, ) class Country(models.Model): # ... iso3166_numeric = models.CharField(max_length=3, validators=[digit_only]) # ... So far, so good. Now, if the value input is '1', I want to convert it to '001' before the value is stored on the table. Without creating a new Field type and then writing custom Field.to_python(), can I achieve the same, as simply as using validators? I am still learning, and I have not reached as far as Forms yet, but I am trying to achieve the above when seeding from a CSV through Djano command. Yes, I could modify the value immediately on reading from CSV, but I am trying to find out if there is one single place where I can do this so that I … -
Authentication and Security in Django/QT Application
I'm currently working on an application that utilizes Django for the backend and QT/C++/QML for the frontend. One of the key aspects I'm focusing on is authentication and ensuring the security of the application. Here's a brief overview of how it works: When a user logs in, the frontend sends a request to the API, and if the credentials are valid, the user receives a TOKEN, which is then stored in a class variable. Subsequently, this token is sent with each subsequent request to the API. Now, my question is: Is this approach secure? Where should such a token be stored? Is using a class variable acceptable in this scenario? It's worth mentioning that this application doesn't handle sensitive data, but I still want to ensure proper security measures are in place. I'd appreciate any insights or recommendations on best practices for authentication and security in this context. Thank you! I was tried to store the data in variable inside the CPP class. -
I can't use wagtail command after pip install
Firstly, I attempted to install wagtail from source the usual way : pip install -e ."[testing,docs]" -U But it always returned TypeError : excepted string or bytes. I then tried to reinstall python and pip altogether. Through many researches on stackoverflow, I found to try install with sudo. Then It worked. But when I do wagtail command, it returns : Traceback (most recent call last): File "/usr/local/bin/wagtail", line 33, in <module> sys.exit(load_entry_point('wagtail', 'console_scripts', 'wagtail')()) File "/usr/local/bin/wagtail", line 25, in importlib_load_entry_point return next(matches).load() StopIteration I desperate with Wagtail application for more than one month. I'm hoping for your kind help please. Thanks community. -
Make Python async queue based on two dynamic Django ORM requests
I need to make chat offers to the agents. Both are taken from Django ORM dynamically, agents have limits of maximum active chats. One agent must have one offer at a time. Chat should be offered to different agents sequentially. Here is example of try showing the expected logic but it offers only one chat at time. async def offerer(): while True: await asyncio.sleep(0.1) async for chat in Chat.objects.filter(Q(status = 'initiated') | Q(status = 'queued')).order_by('last_init')[:5]: chatid = chat.chatid dobreak = False account = chat.chatacc_id async for agent in Agent.objects.filter(status = 'ready', accounts = account, number_active__lt = maxchats).order_by('number_active'): data = {"type": "chat_initiated", "chatid": chat.chatid} await channel_layer.group_send(f'agent_{agent.agentid}', data) await asyncio.sleep(5) # check if chat was accepted chat_updated = await Chat.objects.aget(chatid = chatid) if 'active' in chat_updated.status: dobreak = True break else: await channel_layer.group_send(f'agent_{agent.agentid}', {"type": "cancel", "value": chat.chatid}) if dobreak: break async def main(): asyncio.create_task(offerer()) loop = asyncio.new_event_loop() loop.create_task(main()) loop.run_forever() What is the correct way to do that? -
Can custome page Admin in Django?
I'm building a clinic system. I'm logged in as an admin as a doctor and this page doesn't have any permissions. How can I customize this page or should create url and overriding admin? Thank you. I have tried creating new URLs, creating a page identical to the admin page and want to override the properties and display of the admin page but still don't know how. -
I am trying to deploy a Django webapp on pythonanywhere but it shows up the error "TemplateDoesNotExist at / generator/signin.html"
TemplateDoesNotExist at / generator/signin.html Request Method: GET Request URL: https://atharvasukale.pythonanywhere.com/ Django Version: 4.0.6 Exception Type: TemplateDoesNotExist Exception Value: generator/signin.html Exception Location: /usr/local/lib/python3.10/site-packages/django/template/loader.py, line 19, in get_template Python Executable: /usr/local/bin/uwsgi Python Version: 3.10.5 Python Path: \['/home/atharvasukale/Django-Certificate_Generator-main', '/var/www', '.', '', '/var/www', '/usr/local/lib/python310.zip', '/usr/local/lib/python3.10', '/usr/local/lib/python3.10/lib-dynload', '/usr/local/lib/python3.10/site-packages'\] Server time: Mon, 15 Apr 2024 08:01:54 +0000 I have made all the necessary changes required, but when deployed using pythonanywhere it shows this error. -
Using UserCreationForm
I am learning django. I would like to understand below code. class RegisterPage(FormView): template_name = 'base/register.html' form_class = UserCreationForm redirect_authenticated_user = True success_url = reverse_lazy('tasks') def form_valid( self, form ): user = form.save() if user is not None: login( self.request, user ) return super( RegisterPage, self ).form_valid( form ) def get( self, *args, **kwargs ): if self.request.user.is_authenticated: return redirect('tasks') return super(RegisterPage, self).get(*args, **kwargs) Can I use def register( self, form ): instead of def form_valid( self, form ): ? How self and form are passing here ? Can I use def save( self, *args, **kwargs ): instead of def get( self, *args, **kwargs ): ? -
Django dropdown menu with logout, change password
` {% csrf_token %} ` I want to make the logout page in a drop down list, but I can't do this. The logout page only works with the above code. The path is: path("logout/", LogoutView.as_view(next_page="login"), name="logout"). How can I solve this?