Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Models to Client
So I'm a kid trying Django for the first time, and I'm trying to convert one of my old Python games (a board game called Ludo) into the client side of this. For this, I need to call every instance of the model Goti (defined in the models.py part of Django). I need to do this in the template.html file. How should I do that? For reference, it would be calling all instances of Goti, and pushing it into a list called gotis[] so that I don't have to keep calling every instance. As I said earlier, how do I do that? -
502 gateway error | gunicorn and nginx server not working
Everything was working correctly I run gunicorn and nginx and my website was working perfectly but after making some changes in gunicorn.service my website is now giving 502 gateway error I undo the changes and make gunicorn.service file as it is but still now it is not working If someone know solution for this please answer this. /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service GNU nano 4.8 /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/bankproject/Live-Banking-Solutions-Applications ExecStart=/home/ubuntu/bankproject/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ bankproject.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-available/myproject server { listen 80; server_name 54.199.217.173; client_max_body_size 20M; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/bankproject/Live-Banking-Solutions-Applications; } location /media/ { root /home/ubuntu/bankproject/Live-Banking-Solutions-Applications; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } Nginx error.log file 2022/12/25 21:36:31 [error] 1147#1147: *1 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 106.195.3.113, server: 54.199.217.173, request: "GET /admin/ HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/admin/", host: "54.199.217.173" 2022/12/25 21:36:34 [error] 1147#1147: *1 connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: 106.195.3.113, server: 54.199.217.173, request: "GET /admin/ HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/admin/", host: "54.199.217.173" -
Need Advice in Javascript - New font family for every div
I'm making a post site, but I'm trying to make each post have it's own individual font family. You can see here with the cursive font, it is assigning it properly, but to all of a class. I need to break each post into it's own individual iteration. Since I am doing it on load, i can't seem to grab their Id's or Attributes easily and put them into an array. my current solution is something like this, full code below The randfontlist doesn't return a normal object, it returns something I've never seen before, like the entire post or something. Does anyone have a smart solution to iterate through the items with .randfont tag? Thank you randfontlist = $('.randfont').toArray() randfont_idlist = $('.randfont').attr("id").toArray() $(`.randfont`)[i].addClass(random) .html {% for poopfact in poopfacts %} <div class="col"> <div class="row"> <p>{{ poopfact.date }} </p> <p class="randfont randfont{{poopfact.id}}" id="{{poopfact.id}}">{{ poopfact.fact }}</p> <p> {{ poopfact.author }}</p> </div> .script $( document ).ready( function() { $('.randfont').load(randomizeFonts()) function randomizeFonts() { let fonts = ['caveat', 'indieflower', 'nanum', 'pacifico', 'pmarker', 'tangerine']; const randfonts = $('.randfont') for (let i = 0; i < randfonts.length; i++) { var random = fonts[Math.floor(Math.random() * fonts.length)]; //get the ids of those items and put it into another … -
Creating a list from django model
Hello I am working on a Django project for a job portal. I want to create a model to store a list of requirements which will be rendered in the html page. Please any idea how I can make this possible ? I haven't tried anything yet, I need bright ideas please... -
How to change add and remove tags with JS in django template
I have a quiz Django app which consists of two parts. One is showing 10 sentences with their audio to remember, one per page, and the second is asking questions for the same set of sentences. First part was set up with js function which creates pagination in my html the following way: <button id="prev">prev</button> <button id="next">next</button> <script> var my_objects = `{{ my_objects|safe}}:` #list of items from my view function function paginate(action) { console.log(action) if (action ==='next') { page_number++; } else{ page_number--; } audio.src = `path/to/audio`; $('#dd').empty(); $('#dd').append('<li><h1>'+ my_objects[page_number].fields['content'] +'</h1></li>'); $('#dd').append(audio); $('#dd').append(translation); $('#page_number').val(page_number); } document.addEventListener('DOMContentLoaded', function() { document.querySelector('#next').onclick = function() { paginate('next'); #same goes for 'prev' button. } }) </script> Now when the user paginated through all the sentences I want to show the continue button and if the user clicks it, start the second part. The second part has absolutely same page except I need to hide content of my objects and leave only audio or vise versa and add textarea tag for the user's input. After that I need to loop over my objects again - now in the form of questions. I need to do that without page re-rendering. I tried to make it with tag disabling … -
How to get only the most recent post from each user, ordered by created date
I'm trying to create a social media site in Django where the homepage will display a list of each friend's most recent post, with the newest at the top. At the moment I'm ignoring the friendship functionality and just displaying posts from all users. My current code gets the most recent post from users, but doesn't then order that list by created date. views.py: class PostList(generic.ListView): model = Post # Gets the most recent post from each user # However, the returned set is not ordered by created_on queryset = Post.objects.order_by('author', '-created_on').distinct('author') template_name = 'home.html' I can't change the order_by call as it throws this error: SELECT DISTINCT ON expressions must match initial ORDER BY expressions I know it's possible because I did it ~5 years ago but I don't know what approach I took then and the code is lost. -
Which is better way to rotate logs of Django Application, logging Module of Python or Logrotate of linux?
I want to rotate my logs of Django application, I am able to rotate the logs (based on size) successfully with logging module of python but its causing issue because same log file is getting accessed by celery process and other processes and because of that sometimes application is writing logs in debug.log.1 instead of debug.log file (assume my log file name is debug.log). I suspect this is because my celery process and django server (uwsgi server) is running by different user and because of permission issue it is behaving like that. I am thinking of using logrotate of linux to rotate my log instead of using python class logging.handlers.RotatingFileHandler Can anyone help me in choosing the best way to rotate the log also if you can help me understand why my application is suddenly writing logs in debug.log.1 file instead of debug.log that would be great. -
why i get this Error: missing 1 required positional argument: 'request'
urls.py path("approve_questions/", Approve_questions.posst, name="muster"), # i wann call this function(Approve_questions.posst) in a class path("approve_questions/", Approve_questions.as_view(), name="approve_questions"), class Approve_questions(ListView): form = QuesModel.objects.filter(flaag__exact="False") def get(self, request, *args, **kwargs): form = self.form context = {"form": form} return render(request, "approve_question.html", context) def posst(self, request): return print("anim") how i call about urls.py a function in a class. In this case i wanna call posst but i get the Error: Approve_questions.posst() missing 1 required positional argument: 'request' How i can fix that? Thank you Guys!!! -
How to detect change in HTML page after a successful redirect from form?
views.py class ChangePasswordView(PasswordChangeView): form_class = ChangePasswordForm success_url = reverse_lazy("login") login.html {% if XXXXXX %} <p style="color:green;">Password changed successfully! Please login.</p> {% endif %} Basically I want the following message to appear on my login html page if password was changed. Is there a way to detect if form was successful (by passing some parameter to HTML), or if user was redirected from certain URL to current html page? -
No module named 'gotya.views', django/python
**Even if I have written down gotya.views inside of my url file, it does not recognized by the docker. I can run it in my local and its too strange. What am I doing wrong? ** Code: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static #Static function helps us to publish media files at prod creating url pattern from django.conf import settings from gotya.views import homepage, communicate urlpatterns = [ path('admin/', admin.site.urls), path('account/', include('account.urls')), path('', include('gotya.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Result: Exception in thread django-main-thread:gotya | Traceback (most recent call last):gotya | File "/usr/local/lib/python3.11/threading.py", line 1038, in _bootstrap_innergotya | self.run()gotya | File "/usr/local/lib/python3.11/site-packages/sentry_sdk/integrations/threading.py", line 69, in rungotya | reraise(*_capture_exception())gotya | File "/usr/local/lib/python3.11/site-packages/sentry_sdk/_compat.py", line 57, in reraisegotya | raise valuegotya | File "/usr/local/lib/python3.11/site-packages/sentry_sdk/integrations/threading.py", line 67, in rungotya | return old_run_func(self, *a, **kw)gotya | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^gotya | File "/usr/local/lib/python3.11/threading.py", line 975, in rungotya | self._target(*self._args, **self._kwargs)gotya | File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrappergotya | fn(*args, **kwargs)gotya | File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 134, in inner_rungotya | self.check(display_num_errors=True)gotya | File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 475, in checkgotya | all_issues = checks.run_checks(gotya | ^^^^^^^^^^^^^^^^^^gotya | File "/usr/local/lib/python3.11/site-packages/django/core/checks/registry.py", line 88, in run_checksgotya | new_errors = check(app_configs=app_configs, databases=databases)gotya | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^gotya | File "/usr/local/lib/python3.11/site-packages/django/core/checks/urls.py", line 14, in … -
How to order a django query after a distinct operation
I have the following code: # Gets the most recent post from each user # However, the returned set is not ordered by created_on queryset = Post.objects.all().order_by('author', '-created_on').distinct('author') Trying to, for example, tack another order_by onto the end of the query, or changing the current order_by parameters, results in this error: SELECT DISTINCT ON expressions must match initial ORDER BY expressions Is there a way to accomplish my goal here (a list of each user's most recent post, ordered from newest to oldest)? -
django rest framework I want to return in response all the models that have relation to user model as a user login
I want to show all the related to user model field as the user logins in response in a apiview. Views .py code class UserLoginView(APIView): renderer_classes = [UserRenderer] def post(self, request, format=None): serializer = UserLoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) email = serializer.data.get('email') password = serializer.data.get('password') user = authenticate(email=email, password=password) if user is not None: if Profile.objects.filter(user=user).first().is_verified: token = get_tokens_for_user(user) # profile = user.profile.all() # pbys = user.propertiesbystreet.all() # pbyb = user.propertiesbyblocks.all() return Response({'msg': 'Login Success', 'data': serializer.data, 'token': token}, status=status.HTTP_200_OK) else: return Response({'msg': 'Account is not verified'}, status=status.HTTP_404_NOT_FOUND) else: return Response({'errors': {'non_field_errors': ['Email or Password is not Valid']}}, status=status.HTTP_404_NOT_FOUND) Serializers class from serializer.py class UserLoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(max_length=255) userdata = UserDetailsSerializers(read_only=True) class Meta: model = User fields = ['email', 'password', 'userdata'] -
POST method doesn't return output
I'm an absolut beginner in Django, so my problem is probably very basic, but I am currently stuck and I would appreciate any help. I'm trying to create a form where the user can write a text that will be then simply printed out on the webpage. Here is my html file template Here is my views.py views.py Here is my forms.py forms.py Here is my urls.py urls.py. I don't get any errors, but the output doesn't appear on my webpage. I think the function get_translation doesn't work, but I can't figure out why. Thank you for having a look! -
Django / SimpleTestCase / How Mocking the connection with database works?
I am trying to understand how the test/mocking procedure works inside Django (connection to Postgresql) Here is my project structure : wait_for_db.py import time from psycopg2 import OperationalError as Psycopg20pError from django.db.utils import OperationalError from django.core.management.base import BaseCommand class Command(BaseCommand): """Django command to wait for the database""" def handle(self, *args, **options): """ Entry point for command""" self.stdout.write("waiting for database") db_up = False while db_up is False: try: self.check(databases=['default']) db_up = True except (Psycopg20pError, OperationalError): self.stdout.write("database unavailable, waiting 1 seconds") time.sleep(1) self.stdout.write(self.style.SUCCESS("Database available!")) test_commands.py from unittest.mock import patch from psycopg2 import OperationalError as Psycopg2Error from django.core.management import call_command from django.db.utils import OperationalError from django.test import SimpleTestCase @patch("core.management.commands.wait_for_db.Command.check") class CommandTests(SimpleTestCase): def test_wait_for_db_ready(self, patched_check): """ Test waiting for the database to be ready. """ patched_check.return_value = True call_command("wait_for_db") patched_check.assert_called_once_with(databases=['default']) # AssertionError: Expected 'check' to be called once. Called 0 times. @patch('time.sleep') def test_wait_for_db_delay(self, patched_sleep, patched_check): ''' Test that waiting for db when getting operationalError the first two times we call the mock method to raise Psycopg2Error then we raise three times the operationalError ''' patched_check.side_effect = [Psycopg2Error] * 2 + \ [OperationalError] * 3 + [True] call_command("wait_for_db") self.assertEqual(patched_check.call_count, 6) patched_check.assert_called_with(databases=['default']) Indeed this commands docker-compose run --rm app sh -c "python manage.py test" gives … -
How to setup Django channels on GCP App Engine?
I have a Django application that uses the channels package for WebSocket. I'm using the daphne interface server to run the app on the Google Cloud App Engine Flex environment, but the backend service is not able to serve concurrent requests. Is there anyone who faced similar problems before? -
Django: Move migration file to another application
With the help of "contribute_to_class" function of django model Field, I added one extra field in django.contrib.auth.Permission model. This is given below: if not hasattr(Permission, 'module'): module = models.ForeignKey( MModule, on_delete=models.CASCADE, related_name='permissions', default=None, blank=True, null=True ) module.contribute_to_class(Permission, 'module') Everything works fine! The migration file created and migration works perfect. But the problem is that, migration file created at, lib/python3.10/site-packages/django/contrib/auth/migrations/ can I move this migration file into some other applications I am having (instead of keeping it inside system library) ? The migration file created is given below: # Generated by Django 4.1.3 on 2022-12-25 18:16 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('roles_permissions', '0002_mmodule_parent_module'), ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.AddField( model_name='permission', name='module', field=models.ForeignKey( blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='permissions', to='roles_permissions.mmodule' ), ), ] can I move this migration file into some other applications I am having ? -
Type error when accessing Django request.POST
I'm attempting to build an XML document out of request.POST data in a Django app: ElementTree.Element("occasion", text=request.POST["occasion"]) PyCharm is giving me an error on the text parameter saying Expected type 'str', got 'Type[QueryDict]' instead. I only bring up PyCharm because I know its type checker can be overzealous sometimes. However, I haven't been able to find anything about this issue specifically. Am I doing something wrong? Or should I try to silence this error? -
Update Page and Value using JQuery / Ajax in Django
I am using Django Where I want to update page and it's value without reloading the page. I am getting the value from my database and I want to post this value in my template page and also I want to update my html page without reloading it again and again. Here I am sharing my details: views.py: def process(request): hash_id = request.session.get('hash_id') print(hash_id) check = request.session.pop('check_status',) if hash_id and check: stat = status_mod.objects.filter(hash_id = hash_id).order_by('-id').first() if stat: stat = stat.stat_id print(stat) return render(request, 'enroll/status.html', {'status': stat}) models.py: class status_mod(models.Model): id = models.BigIntegerField(primary_key=True) stat_id = models.BigIntegerField() hash = models.ForeignKey(hash, on_delete=models.CASCADE, blank=True, null=True, related_name="hash_status") class Meta: db_table = "****" urls.py: path('status', views.process, name='process') status.html: <td> <form action = "/modules" method="get"> {% if status == 1 %} {% csrf_token %} <button link="submit" class="btn btn-default btn-sm"> <span class="badge badge-dot mr-4"> <i class="bg-success"></i>Completed</button> </form> {% else %} <button type="button" class="btn btn-default btn-sm"> <span class="badge badge-dot mr-4"> <i class="bg-warning"></i>Running</button> {% endif %} </td> jquery / ajax in status.html page: <script> $(document).ready(function() { setInterval(function() { $.ajax({ type: 'GET', url: "{% url 'process' %}", success: function(response){ console.log(response) }, error: function(response){ alert("NO DATA FOUND") } }); }, 2500); }); </script> Here I want that when Status value will … -
Django Channels 4.0.0 + Docker Redis stops sending messages after some time
I am using Django 4.1.3 + Channels 4.0.0 and Docker with Redis 5 in it. It runs on Daphne 4.0.0. Also I have frontend written on React that uses reconnecting websocket for making undead connection to server. But after some time (I can’t say for sure, but about 1 - 2 days) frontend stops recieving messages from Channels. Restarting Redis container fixes this issue as 1 - 2 days as I said. Here is the docker-compose.yml: services: ... redis: image: redis ports: - "6379:6379" container_name: redis restart: always command: redis-server --appendonly yes --replica-read-only no Any thoughts what it could be and and how to fix it? Ps. thank for your time -
How to create base context for class based views Django?
I have multiple class based views that require the same context. How can I create a 'base' context that applies to all the class based views, so that I don't need to repeat the same code over and over again in every class based view? It is maybe possible to create a context class and use that in the get_context function of all the class based views? class ManagerSignUpView(CreateView): model = User form_class = ManagerSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) if self.request.user.is_authenticated: if Student.objects.filter(user=self.request.user).exists(): # if a Student with the request username exists user = User.objects.get(username=self.request.user) student = Student.objects.get(user=user) context['name'] = f'{student.first_name} {student.last_name}' if user.is_student: context['user_type'] = 'Student' elif Teacher.objects.filter(user=self.request.user).exists(): # if a Teacher with the request username exists user = User.objects.get(username=self.request.user) teacher = Teacher.objects.get(user=user) context['name'] = f'{teacher.first_name} {teacher.last_name}' if user.is_teacher: context['user_type'] = 'Teacher' elif user.is_manager: context['user_type'] = 'Manager' elif user.is_superuser: context['user_type'] = 'Admin' context['user_type_to_create'] = 'manager' return context def form_valid(self, form): first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') location = form.cleaned_data.get('location') user = form.save( first_name=first_name, last_name=last_name, location=location, ) return redirect('home') class AdminSignUpView(CreateView): model = User form_class = AdminSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) if self.request.user.is_authenticated: if Student.objects.filter(user=self.request.user).exists(): # … -
How do I avoid overwrite in django models
I have class called AlbumImage class AlbumImage(models.Model): album = models.ForeignKey(Album, on_delete=models.PROTECT,related_name="raters") image = models.ImageField(upload_to="Album") when i upload first image called (for example) image1.png every thing in ok ,,,, But if I upload another image with the same name(image1.png), and go back to the first object, I will find the second image in its place. How do I avoid overwrite ? -
Create super user in Django with email instead of username
This is the first time that I ask something... So I'll try to be precise. I am building a django app for my final project, and I have encountered some trouble with the authentication system. What I'm trying to do is create a superuser with the command: python manage.py createsuperuser But I want to use the email adress, instead of the username field. For this reason, I wrote the following code: My CustomUser: class CustomUser(AbstractUser): username = models.CharField(max_length=50, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] creation_date = models.DateTimeField(auto_now_add=True) modification_date = models.DateTimeField(auto_now=True) name = models.CharField(max_length=50, blank=False, null=False) last_name = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(unique=True) date_of_birth = models.DateField(blank=False, null=False) nif = models.CharField(max_length=9, blank=False, null=False) sex = models.CharField(max_length=1, choices=SEX_CHOICES) phone = models.CharField(max_length=15, blank=True, null=True) mobile = models.CharField(max_length=15, blank=True, null=True) specialty = models.CharField(max_length=30, choices=SPECIALTY_CHOICES) license_number = models.CharField(max_length=50) def __str__(self): string = 'Name: ' + self.name + ' ' + self.last_name + ', email: ' + self.email return string def has_role(self, center, role): try: center_role = CenterRole.objects.get(user=self, center=center, role=role) return True except CenterRole.DoesNotExist: return False And I also created a CustomUserManager (I thought that, by doing that, I wouldn't encounter any more problems): class CustomUserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): … -
Resizing image with passed parameters using Django Rest Framework raises AttributeError: _committed
I need to resize an uploaded image before saving it. Here's my model from django.db import models def upload_to(instance, filename): return f'images/{filename}' class Image(models.Model): title = models.CharField(max_length=64) url = models.ImageField(upload_to=upload_to, width_field='width', height_field='height') width = models.PositiveIntegerField(null=True, blank=True) height = models.PositiveIntegerField(null=True, blank=True) here's serializer class ImageSerializer(ModelSerializer): class Meta: model = Image fields = '__all__' def create(self, validated_data): if validated_data.get('height') and validated_data.get('width'): resized_image = resize_image( image=validated_data.pop('url'), width=validated_data.pop('width'), height=validated_data.pop('height') ) image = Image.objects.create(url=resized_image, **validated_data) else: image = Image.objects.create(**validated_data) return image and the resize_image function from PIL import Image def resize_image(image, width, height): img = Image.open(image) img = img.resize((width, height), Image.ANTIALIAS) return img I totally don't get what could be a reason of raising AttributeError: _committed by this code. -
How to show content only to user that created it?
I have program like todo list. And I need to filter db to show only content that user created I have code like this: name = Gift.objects.filter(author=request.user) But it show error Cannot resolve keyword 'author' into field. Choices are: gift_name, id, person_name, user, user_id -
How can one html form input field update two Django models?
I have two models, Region and Room. One room can only be in one region but one region can have many rooms. When the user is creating a room (createRoom view), I want them to enter a region, which should both update the Region model and also assign this Region to the room. models.py class Region(models.Model): region = models.CharField(max_length=200, unique=True) etc.... class Room(models.Model): region = models.ForeignKey(Region, on_delete=models.SET_NULL, null=True) etc.... forms.py class RoomForm(ModelForm): class Meta: model = Room fields = ['region', etc....] class RegionForm(ModelForm): class Meta: model=Region fields = ['country', 'region'] views.py def createRoom(request): form_room = RoomForm() form_region = RegionForm() if request.method == 'POST': form_room = RoomForm(request.POST) form_region = RegionForm(request.POST) if form_room.is_valid() and form_region.is_valid(): room = form_room.save(commit=False) region = form_region.save(commit=False) room.region = region.region room.save() region.save() return redirect ('home') template.html <form class="form" action="" method="POST"> {% csrf_token %} {{form_room.media}} <div class="form__group"> <label for="region_name">Region</label> {{form_region.region}} </div> </form> The line room.region = region.region in views.py I was hoping would set the region object of the Region model as the region object of the Room model. I receive no errors when submitting the form. However the Room model's region object stays empty.