Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reducing the number of queries in a Django TabularInline Admin
I have an admin with 1 row in the tabular inline. I have a custom queryset in class ExtensionTabularInlineFormSet(BaseInlineFormSet): def get_queryset(self) -> QuerySet[Extension]: qs = super().get_queryset() This gets called 20 times to display that one row. When you have more rows, it gets called 20 times/row (I think, but I lose count). The culprit is calls to this method: def initial_form_count(self): """Return the number of forms that are required in this FormSet.""" if not self.is_bound: return len(self.get_queryset()) return super().initial_form_count() The solution would be to cache this value, but admin views seem like singletons way too often for this to work. How do I solve this? -
Django model choices and jQuery DataTables sort
I am struggling to get a sorting to work in jQuery DataTables when I want to sort objects based on choices in the django model. With the snippets included I can sort it based on the values 1..n in choices, but as it considers those as strings, sorting is not working properly. It considers 10, 11 and 12 to be lower that everything between 2 to 9. How would I fix this issue? I have this model in my django app: class Action(models.Model): STATUS_CHOICES = ( ('1', 'Status 1'), ('2', 'Status 2'), ('3', 'Status 3'), ('4', 'Status 4'), ('5', 'Status 5'), ('6', 'Status 6'), ('7', 'Status 7'), ('8', 'Status 8'), ('9', 'Status 9'), ('10', 'Status 10'), ('11', 'Status 11'), ('12', 'Status 12'), ) status = models.CharField(max_length=100, choices=STATUS_CHOICES, default=1, verbose_name='Status') From views I will render everything to my template: def actions_view(request, *args, **kwargs): actions = Action.objects.all() context = { 'actions':actions, } return render(request, "actions.html", context) And in the template everything will be displayed in jQuery datatables: <table id="actionTable" class="table table-striped"> <thead> <tr> <th>Action</th> </tr> </thead> <tbody> {% for action in actions %} <tr> <td><span style="display:none;">{{ action.status }}</span>{{ action.get_status_display }}</td> </tr> {% endfor %} </tbody> </table> <script> $(document).ready(function () { $('#actionTable').DataTable({ fixedHeader: … -
How to listen a django web api from celery task?
I created a project using Django, Celery, and celery beat for scheduling tasks. I created a task using celery. @shared_task(bind=True) def my_task(self): # How can I listen if a post API is requested from here? return "Task Successful" I want this task to listen to a web API if it is requested. Is it possible? -
Where to run Celery on AWS
In my django web app I am running a calculation which takes 2-10 minutes, and the AWS server times out with a 504 server error. It seems that the best way to fix this problem is to implement a worker, and offload the calculations. Through some research, it seems that Celery with a Redis server (maybe AWS SQS instead?) are best for Django. However, I only see tutorials for instances that are run locally. The Redis server is hosted by Railway and Celery is run in a separate terminal than Django. I'm curious if/where Celery and Redis should be running on AWS. This answer says you should try to run celery as a deamon in the background. AWS Elastic Beanstalk uses supervisord already to run some deamon processes. So you can leverage that to run celeryd and avoid creating a custom AMI for this. It works nicely for me. but don't the Celery and Redis servers still need to run somehow? Where does the Celery server run? How do I start it? How can I leverage supervisord to run daemon processes? The documentation isn't helping me very much with AWS integration -
Django Rest Framework - How do I get the count and average of a related field in a serializer
I have a post model that can have ratings: Here is the post model: class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=1, related_name="posts") body = models.TextField("content", blank=True, null=True, max_length=5000) slug = AutoSlugField(populate_from=["category", "created_at"]) video = models.FileField(upload_to=video_directory_path, null=True, blank=True) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="posts" ) published = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = "post" verbose_name_plural = "posts" db_table = "posts" ordering = ["created_at"] get_latest_by = "created_at" def __str__(self): return self.body[0:30] def get_absolute_url(self): return self.slug def one_image(self): return PostImage.objects.all().filter(post=self)[:1] and here is the post rating model: class PostRating(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="ratings") score = models.IntegerField(choices=list(zip(range(1, 6), range(1, 6)))) user = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name="user rating" ) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "post rating" verbose_name_plural = "post ratings" db_table = "post_ratings" def __str__(self): return str(self.score) Here is the serializer: class PostSerializer(serializers.ModelSerializer): images = PostImageSerializer(many=True, read_only=True, required=False) class Meta: model = Post fields = [ "id", "category", "body", "images", "video", "ratings", "published", "created_at", "updated_at", ] depth = 1 def create(self, validated_data): user = User.objects.get(id=self.context['request'].data.get('user')) category = Category.objects.get(id=self.context['request'].data.get('category')) new_post = Post.objects.create(**validated_data, category=category, user=user) images = dict((self.context['request'].FILES).lists()).get('images', None) if images: for image in images: PostImage.objects.create( image=image, post=new_post ) return new_post QUESTION: … -
django rest framework returning incorrect format for response
I'm having issues with serializing a list. so my models.py looks like this: class Show(models.Model): name = models.CharField(max_length = 500) rating = models.FloatField() network = models.CharField(max_length = 500) description = models.CharField(max_length = 500) episodes = models.IntegerField() cast = models.CharField(max_length=200) rating = models.FloatField() def __str__(self):return self.name and my serializers.py looks like this: class show_serializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only = True) name = serializers.CharField() network = serializers.CharField() description = serializers.CharField() episodes = serializers.IntegerField() cast = serializers.ListField(child=serializers.CharField(max_length=100)) rating = serializers.FloatField() def create(self, data): return Show.object.create(****data) however my json response is formatted wrong, I'm trying to make it { "id": 3, "name": "Breaking Bad", "description": "A high school chemistry teacher diagnosed with inoperable lung cancer turns to manufacturing and selling methamphetamine in order to secure his family's future.", "network": "AMC", "episodes": 62, "cast": [ "Bryan Cranston", "Aaron Paul", "Anna Gunn", "Dean Norris" ], "rating": 9.5 } whats happening is the "cast" part of the json is splitting the cast into multiple characters. for instance it's becoming "cast": [ "[", "'", "B", "r", and so on for every character ] I've tried switching to JSONField, using a ListField for cast in the serializer.py file, using Textfield() for cast in the models -
How to override django local Installed app in saleor platform
enter image description here Hello here are some locally installed app in saleor platform. Now I have to make chnages (override) some codes inside this apps. what are the best practices or how can i do without in disturbance in existing code. Thanks I have tried to overide by following blog But got no result. -
django_crontab no encuentra Template
Utilizo el crontab para verificar datos, y depende la confirmación me envié un correo, utilizo la misma funcion de enviar correos dentro de las views y funciona correctamente, pero al usarlo dentro del crontab, me arroja un error de 'django.template.exceptions.TemplateDoesNotExist' Creo que podría ser un error de la ruta, pero no estoy seguro como debería hacerlo. El error completo: error Funcion que envia los correos: def send_email_pago_premium(cant, url, email, user, fecha_inicio, fecha_fin): print("Enviando email...") try: server = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) server.ehlo() server.starttls() server.ehlo() server.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD) #Construyendo el mensaje mensaje = MIMEMultipart() mensaje['From'] = EMAIL_HOST_USER mensaje['To'] = email mensaje['Subject'] = 'Pagamento Concluido' content = render_to_string('paginas/email/email_pago_premium.html', { 'user': user, 'cant': cant, 'url':url, 'fecha_inicio':fecha_inicio, 'fecha_fin':fecha_fin }) mensaje.attach(MIMEText(content, 'html')) server.sendmail(EMAIL_HOST_USER, email, mensaje.as_string()) print("Email enviado") except Exception as err: print(f"Unexpected {err=}, {type(err)=}") raise -
How i get views.py variable to js file?
views.py def somefunction(request): var = True return render(request, dasboard.html) myfirst.js function myFunction() { } How i get var from views.py into the myfirst.js function? Thank you! -
how to do an if to check if a date is between two dates. Python
I need to check if a certain date is between the month of February, but I can't use year, only month and day. How can i do this using if and else in python? -
#Django How to fetch data with permissions.IsAuthenticatied in views.py using Postman?
I'm trying to fetch data with my Django Restframework API endpoints. This is my UserViewSet in views.py: class UserViewSet(viewsets.ModelViewSet): queryset = PortalsUser.objects().all().order_by('name') serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] So this will need the user to login first to view the user information. I tried to GET my user on Postman, and this is the my Postman configuration I'd like to know am I doing it correctly? Should I input my username and password like this? Thanks for your help! -
Getting localhost for next page url in production
hlo, I have deployed a Django rest app in production. When I call a list API there is a pagination, and I am getting localhost for next page URL. I am using GenericViewSet and LimitOffsetPagination for pagination. My app is running in docker container.And it is pointed to a specific domain. We can access it using domain name "https://abc.xyz.com". But I have used python manage.py runserver:0.0.0.0:8000(it's just for testing) CMD for running the server. -
How to save down Django user's updated social media post?
Goal A user can edit the post that that specific user made. Bly clicking edit than editing than pressing save. Problem When I edit the social media post it does not get saved Description I can make a mew post like in social media Post it in to a list where all the other users post (shortened 200 character visible only) Than I can click on a "Details button" that jumps me to another page where I can see the full length of the post There is a button here called "edit" it should only appear to the post creator If you click edit than a window pop up where you already have your existing post copied in to an inout field here you can edit your post the goal would be it you click save it should save it down but that does not happens Interestingly if i close down the pop up windows with the small window [X] button or the "cancel" button and I go back it memorizes my edit there View function @login_required def social_post_detail(request, pk): social_post = get_object_or_404(social_post, pk=pk) form = None if request.user == social_post.created_by: if request.method == 'POST': print(request.POST) form = social_postForm(request.POST, instance=social_post) … -
NOT NULL constraint failed: tasks_task.user_id
I'm working on a Django project using Python3. I have this error come ups when I'm trying to create a new task. django.db.utils.IntegrityError: NOT NULL constraint failed: tasks_task.user_id The web application works fine, but when I try to create a new task is when the error occurs, I have read all the posts related to the problem, but I have not found the solution. I tried to update my sqlite3, but it didn't work. This is my code from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from .forms import TaskForm def home(request): return render(request, 'home.html') # Create your views here. def signup(request): if request.method == 'GET': return render(request, 'signup.html', { 'form': UserCreationForm }) else: if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user( username=request.POST['username'], password=request.POST['password1']) user.save() login(request, user) return redirect('tasks') except IntegrityError: return render(request, 'signup.html', { 'form': UserCreationForm, 'error': 'Username already taken' }) return render(request, 'signup.html', { 'form': UserCreationForm, 'error': 'Passwords did not match' }) def tasks(request): return render(request, 'tasks.html') def create_task(request): if request.method == 'GET': return render(request, 'create_task.html', { 'form': TaskForm, }) else: try: form = TaskForm(request.POST) new_task = form.save(commit=False) new_task.User = request.user new_task.save() … -
Invalid host header in django
Environment: Request Method: GET Request URL: http://abampdb.......nust.edu.pk:83/ Django Version: 4.0.2 Python Version: 3.9.12 Installed Applications: ['abampdb.apps.AmpdbConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed 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'] Traceback (most recent call last): File "/home/abampdb/projectdir/venv_name/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/abampdb/projectdir/venv_name/lib/python3.9/site-packages/django/utils/deprecation.py", line 125, in __call__ response = self.process_request(request) File "/home/abampdb/projectdir/venv_name/lib/python3.9/site-packages/django/middleware/common.py", line 48, in process_request host = request.get_host() File "/home/abampdb/projectdir/venv_name/lib/python3.9/site-packages/django/http/request.py", line 135, in get_host raise DisallowedHost(msg) Exception Type: DisallowedHost at / Exception Value: Invalid HTTP_HOST header: 'abampdb.......t.edu.pk:83'. You may need to add 'abampdb...........du.pk' to ALLOWED_HOSTS. I have used nginx and gunicorn for the deployement from this link https://djangocentral.com/deploy-django-with-nginx-gunicorn-postgresql-and-lets-encrypt-ssl-on-ubuntu/. I have edited the settings.py Settings.py also with the domain name in the Allowed Host but still getting the same error and after editing i have also run the gunicorn restart command and nginx reload command. here is my Nginx configuration file -
I can't copy content from an html tag into another django template
Good night friends. I'm trying to display the content of a tag in a template, in another template, using the django "extends" method. Works perfectly with when it comes to "normal", "typed" content: this works: {% block part_of_site %} <div id='tag2'>Context</div> {% endblock %} using a variable, you can't copy to another template: {% block part_of_site %} <div id='tag2'>{{ variable }}</div> {% endblock %} -
can i make registration form using python and mysql to show it on profile page?
I want to make a registration and login system but I don't know how to connect form to python and mysql , and then can i get the data and put it in the profile page? how can I take the same data and put in the profile page like variables it'll be changing with every user I tried using Django with Mysql but every time I try using something , another function stops. -
How to display code as code with color using python django
how can I display code as code in the browser using python django. Example if True: print("Hello World") I want the above code to be displayed in the browser with different colors -
Disable logging bad requests while unittest django app
I have a tests in my Django app. They're working well, but i want to disable showing console logging like .Bad Request: /api/v1/users/register/ One of my tests code def test_user_register_username_error(self): data = { 'username': 'us', 'email': 'mail@mail.mail', 'password': 'pass123123', 'password_again': 'pass123123' } url = self.register_url response = client.post(url, data=data) self.assertEqual(response.status_code, 400) self.assertFalse(User.objects.filter(username='us').first()) Console output Found 1 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). .Bad Request: /api/v1/users/register/ ---------------------------------------------------------------------- Ran 1 tests in 0.414s OK Everything works nice, but i want to disable Bad Request: /api/v1/users/register/ output to console. I double checked, there's no print or logging functions, that can possibly log this to console. How can i disable messages like Bad Request: /api/v1/users/register/ logging while tests -
mod_wsgi on Python 3.10 does not update Django templates without Apache restart
I have been running a Django server on Python 3.8 with Apache and mod_wsgi for some time now, and decided it was time to upgrade to Python 3.10. I installed Python 3.10 on my server, installed the Django and mod_wsgi packages, copied the 3.10 build of mod_wsgi.so to Apache's modules folder, and everything works great ... however, it seems with this build of mod_wsgi, changes to template files do not take effect unless I restart Apache. As an example, I added a random HTML template file to my website, and started the server with some initial text in that template. Running on the Python 3.8, I am able to change the contents of that template (e.g. echo "More Text" >> test_template.html) and upon refreshing my browser the new text will show up. However doing the same test in 3.10, the new text will not show up. I have tried different browser sessions and hard reloading, it is not a caching issue on the client side, and looking at the response sizes in Apache's access log confirms the data being sent to the client changes in 3.8 but not in 3.10. I have stood up a test server to isolate the … -
Need random number generated in html for embedding into iframe
I am using this embed code for a site. The site is a Django site. I apologize if my terms are wrong, I'm not a developer. . Periodically I return to the site and the graph will not display, but the logo from the host site does. I suspect that it's a caching issue. I tried "no-store" but I'm not sure if I pasted it in properly. I want to add a random number generator to the embed code. In my mind that would be similar to a refresh - again, not a programmer. Django strips css and possibly more. Can anyone either solve my problem or write the random number generator to make the "border-width" 1, 2, or 3? Here is my site with the bug. https://www.twelvebridges.com/twelve-bridges-market-report/. I encounter the bug on Chrome on a macbook. Never the first visit and a refresh solves it every time. I tried "no-store" but probably in the wrong place. I tried Classic Cache Killer as a Chrome extension on my site. I added a gif on the site even though I cannot really articulate what I thought that would accomplish. -
upload larger files with python , Django and IIS server
I have file upload code in Django + python and I have my site register with IIS server. when running python code from command prompt on localhost:5000 and upload larger files (275 MB) is working perfectly. but when runs from websitedomain which is set with IIS version 10 , error 500 page is coming. I have set system.webServer/security/requestFiltering -> maxAllowedContentLength to 4294967295 -> maxQueryString 2048 and maxUrl 4096. I have also set to system.web/httpRuntime -> maxRequestLength to 2147483647 . I am expecting to upload larger files. any help ? Thank you in Advance PB -
Django - FileField - PDF vs octet-stream - AWS S3
I have a model with a file field like so: class Document(models.Model): file = models.FileField(...) Elsewhere in my application, I am trying to download a pdf file from an external url and upload it to the file field: import requests from django.core.files.base import ContentFile ... # get the external file: response = requests.get('<external-url>') # convert to ContentFile: file = ContentFile(response.content, name='document.pdf') # update document: document.file.save('document.pdf', content=file, save=True) However, I have noticed the following behavior: files uploaded via the django-admin portal have the content_type "application/json" files uploaded via the script abobe have the content_type "application/octet-stream" How can I ensure that files uploaded via the script have the "application/json" content_type? Is it possible to set the content_type on the the ContentFile object? This is important for the frontend. Other notes: I am using AWS S3 as my file storage system. Uploading a file from my local file storage via the scirpt (i.e. using with open(...) as file: still uploads a file as "applicaton/octet-stream" -
Recommended Books & Videos for Vue, Javascript, NUXT, Django
After reading several Django books I found these two books to be the best so far. Two Scoops of Django 3.x A Wedge of Django The best practices for production class websites and class based views with cookiecutter really helps a lot! I'm looking for more Django 3.2/4.0+ books and videos or suscriptions but also for JavaScript, Vue & Nuxt since I may need to use Django with DRF as backend and Nuxt 3 for front end. Any recommendations? -
Parts of Development Setting does not overide production settings
So I have being trying to separate my dev from production side and of my setting. However parts work and part do not. #dev.py from lms.settings.prod import * from decouple import config #overide settings DEBUG = True STRIPE_PUBLIC_KEY =config('DEV_PUBLIC_KEY') STRIPE_SECRET_KEY =config("DEV_SECRET_KEY") STRIPE_WEBHOOK_SECRET =config('DEV_WEBHOOK_SECRET') #prod.py from decouple import config from pathlib import Path import os DEBUG = False STRIPE_PUBLIC_KEY =config('STRIPE_PUBLIC_KEY') STRIPE_SECRET_KEY =config("STRIPE_SECRET_KEY") STRIPE_WEBHOOK_SECRET =config('STRIPE_WEBHOOK_SECRET') My folder structure is lms -settings --__init__.py --dev.py --prod.py