Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I show all users except an user who is currently logged in using Django
I am trying to show all users but i dont want to show the user who is logged in. This is what i tried: def get_home_page_url(request): user = User.objects.all() h = User.objects.get(id=pk) print(h) # filtered_user = User.objects.filter(id=request.user).exclude(id=request.user) # print("ALL USERS:" + str(filtered_user)) args = { 'user': user, # 'filtered_user': } return render(request, 'home.html', args) I tried these but I am getting error and error. -
Django translation manager path issue in Heroku
I used Django with translate manger and it works normally in my local host. When I deployed it to Heroku, then translation function is not worked. The code is settings.py: PROJECT_ROOT = os.path.dirname(os.path.realpath(__name__)) LOCALE_PATHS = ( os.path.join(PROJECT_ROOT, 'locale'), ) Then I tried to makemessages in Heroku File "/app/.heroku/python/lib/python3.9/site-packages/translation_manager/management/commands/makemessages.py", line 70, in handle os.chdir(get_settings('TRANSLATIONS_PROJECT_BASE_DIR')) FileNotFoundError: [Errno 2] No such file or directory: '' How can I fixed this issue? -
Change drf action url
I have an action on a viewset. The action name is image, is it possible to make url like path/to/api-point/3/image.jpg instead of path/to/api-point/3/image. -
Python update inherited dictionary
I have class class Base: filters = { 'today': '__today' } and another class class Filter(Base): new_filters = { 'yesterday': '__yesterday' } filters = {**self.filter, **new_filter} You may see the filter class above, I tried to add an additional key but it doesn't seem to work, Can anyone tell me what is the best way to do it? -
How to restrict view in Django from other users?
I am trying to make a page that only can be seen by the user for who the results belongs to. So I like to make that only the user with user_name_id=1 (and the superuser) could see the page that is localhost:8000/mpa/sum/1/ I tried in the html this: {% if request.user.is_superuser %} <div class="container text-justify p-5"> <div class="display-4 text-left text-primary my-3"> ... {% else %} You are not able to view this page! {% endif %} This works fine with the superuser but how could I do this with the users? views.py @login_required def individual_sum(request, user_name_id): ... lots of query context = { ... lots of contexts } return render(request, 'stressz/individual_sum.html', context) models.py class IndividualSum_text(models.Model): def __str__(self): return str(self.user_name) user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) ...integerfields and textfields here -
Does anyone have experience working as a developer in Austria? [closed]
Is anyone here that works as a software developer in Austria? I had a job offer and I need some details. -
Django CreateView not creating a new user from 3 related models through ModelForm
I've created models in a Django project, one of which is an extended User model. Initially, I was creating a user through 2 forms, UserCreationForm and EmployeeForm based of a ModelForm, then using a function based view to validate the data and save it. It all worked fine until I tried to introduce the third form and wanted to use the CreateView. Here are the models: class Employee(models.Model): SENIOR = 'Sr' JUNIOR = 'Jr' FIRST = 'I' SECOND = 'II' THIRD = 'III' GENERATIONAL_SUFFIX = [ (SENIOR, 'Senior'), (JUNIOR, 'Junior'), (FIRST, 'First'), (SECOND, 'Second'), (THIRD, 'Third'), ] MALE = 'male' FEMALE = 'female' OTHER = 'other' SEX = [ (MALE, 'Male'), (FEMALE, 'Female'), (OTHER, 'Other'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) phone_regex = RegexValidator(regex=r'^\d{11}$', message="Phone number must be entered in the format: '09151234567'.") phone_number = models.CharField(validators=[phone_regex], max_length=11, blank=True) middle_name = models.CharField(max_length=20, blank=True) sex = models.CharField(max_length=6, choices=SEX, blank=True) suffix = models.CharField(max_length=3, choices=GENERATIONAL_SUFFIX, blank=True) birthday = models.DateField(null=True, blank=True) hire_date = models.DateField(null=True, blank=True) image = models.ImageField(blank=True, default='blank_profile_picture.jpg') slug = models.SlugField(max_length=60, blank=True, null=True) updated = models.DateTimeField(auto_now=True) @property def get_full_name(self): first_name = self.user.first_name middle_name = self.middle_name last_name = self.user.last_name if middle_name is None: full_name = f'{first_name}{" "}{last_name}' return full_name else: full_name = f'{first_name}{" "}{middle_name}{" "}{last_name}' return … -
Django annotate sum on fk_set
I'm trying to annotate sum of fields in related set: My models: class Report(models.Model): class ReportCommissionPosition(models.Model): report = models.ForeignKey(Report) reservation = models.OneToOneField("reservations.Reservation") class Reservation(models.Model): class Payment(models.Model): amount = models.DecimalField(max_digits=10, decimal_places=2) reservation = models.ForeignKey('reservations.Reservation') PAYMENT_TYPES=( ('TRANS', 'TRANS'), ('SELL', 'SELL'), payment_accounting_type = models.CharField(max_length=50, choices=PAYMENT_TYPES) I need to annotate each position of report.reportcommissionposition_set with two fields: trans_amount - Sum of all the payments with payment accounting type == 'SELL' (through reservation => payment) sum_amount - Sum of all the payments with payment accounting type == 'TRANSFER' (through reservation => payment) I have tried: for position in commission_position: position.sell_pay = position.reservation.payment_set.filter(payment_accounting_type='SELL').aggregate(amount=Sum('amount'))['amount'] But this creates new query for every element. Any thoughts? -
I don't know why my django signup form can't create the new user
I made a signup form and a signup view in the Django project. But it seems that 'create_user' does not work. There is no error. Signup view just sends the browser to Home without creating a new user object The user model is using email as a username. I tried to do this with ModelForms but it was the same. I don't know why happens this. users/forms.py class StudentSignUpForm(forms.Form): first_name = forms.CharField() last_name = forms.CharField() email = forms.EmailField( widget=forms.EmailInput(attrs={"placeholder": "Enter your emaill adress"}) ) password = forms.CharField( widget=forms.PasswordInput(attrs={"placeholder": "Enter the Password"}) ) password_confirm = forms.CharField( widget=forms.PasswordInput(attrs={"placeholder": "Confirm the Password"}) ) def clean_email(self): email = self.cleaned_data.get("email") try: models.User.objects.get(email=email) raise forms.ValidationError("This email already exists.") except models.User.DoesNotExist: return email def clean_password_confirm(self): password = self.cleaned_data.get("password") password_confirm = self.cleaned_data.get("password_confirm") if password != password_confirm: raise forms.ValidationError("Password confirmation does not match.") else: return password def save(self): first_name = self.cleaned_data.get("first_name") last_name = self.cleaned_data.get("last_name") email = self.cleaned_data.get("email") password = self.cleaned_data.get("password") user = models.User.objects.create_user(email, password) user.first_name = first_name user.last_name = last_name user.save() users/views.py class StudentSignupView(FormView): template_name = "users/student_signup.html" form_class = forms.StudentSignUpForm success_url = reverse_lazy("core:home") def form_vaild(self, form): form.save() email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(self.request, username=email, password=password) if user is not None: login(self.request, user) return super().form_valid(form) templates/users/student_signup.html {% … -
How can I pass dictionary in Django Rest Framework?
In django, I was able to pass data using dictionary. Like I set the objects in my dictionary and pass it in return render and call the object in frontend (return render(request, 'c.html', context) right? so How can I do this in django rest? -
django-notifs raising an exception: django.core.exceptions.FieldDoesNotExist: Notification has no field named 'timestamp'
I'm trying to apply Notifications system to my django (version 3.2) app for the first time using the tutorial: https://django-notifs.readthedocs.io/en/stable/index.html# I'm stuck at the installation process. First I solved the (fields.E180) SQLite does not support JSONFields. After running makemigrations, it worked fine. BUT after running manage.py migrate, it threw the following error: raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: Notification has no field named 'timestamp'. Please help me out :( -
Django application with Apache and mod_wsgi on Windows server:
Added this to my windows server httpd.conf: LoadFile "c:/users/rootadmin/appdata/local/programs/python/python39/python39.dll" LoadModule wsgi_module "c:/users/rootadmin/appdata/local/programs/python/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "c:/users/rootadmin/appdata/local/programs/python/python39" WSGIPythonPath "C:/Users/rootadmin/DSS_code/tdid/DSS/" <VirtualHost *:80> WSGIScriptAlias / C:/Users/rootadmin/DSS_code/tdid/DSS/DSS/wsgi.py <Directory "C:/Users/rootadmin/DSS_code/tdid/DSS/DSS"> Require all granted Alias /static "C:/Users/rootadmin/DSS_code/tdid/DSS/static" <Directory "C:/Users/rootadmin/DSS_code/tdid/DSS/static"> Require all granted When trying to run apache getting following error in error log: AH00418: Parent: Created child process 4596 Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\Apache24\bin\httpd.exe' sys.base_prefix = 'C:\Users\rootadmin\AppData\Local\Programs\Python\Python39' sys.base_exec_prefix = 'C:\Users\rootadmin\AppData\Local\Programs\Python\Python39' sys.platlibdir = 'lib' sys.executable = 'C:\Apache24\bin\httpd.exe' sys.prefix = 'C:\Users\rootadmin\AppData\Local\Programs\Python\Python39' sys.exec_prefix = 'C:\Users\rootadmin\AppData\Local\Programs\Python\Python39' sys.path = [ 'C:\Users\rootadmin\AppData\Local\Programs\Python\Python39\python39.zip', '.\DLLs', '.\lib', 'C:\Apache24\bin', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00001200 (most recent call first): [Sat Aug 28 04:19:40.123798 2021] [mpm_winnt:crit] [pid 2312:tid 600] AH00419: master_main: create child process failed. I have been digging around but nothing has worked so far. Any suggestions ? -
502 Bad Gateway in django app on vps why?
I am trying to deploy a django project but i get 502 Bad Gateway [i used this tutorial https://dev.to/ndemo/how-i-deployed-my-django-app-to-vultr-vps-3k1i][1] i used supervisor , guncorn and nginx ./virtualenvs/legaland_env/bin/gunicorn #!/bin/bash NAME="django_project" DIR=/home/django/django_project USER=django GROUP=django WORKERS=3 BIND=unix:/home/django/run/gunicorn.sock DJANGO_SETTINGS_MODULE=django_project.settings DJANGO_WSGI_MODULE=django_project.wsgi LOG_LEVEL=error cd $DIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- /etc/supervisor/conf.d/sqh.conf [program:sqh] startsecs=0 command=/home/admin/legaland/virtualenvs/legaland_env/bin/gunicorn user=admin autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/admin/legaland/gunicorn-error.log /etc/nginx/sites-available/sqh upstream app_server { server unix:/home/admin/legaland/run/gunicorn.sock fail_timeout=0; } server { listen 80; # add here the ip address of your server # or a domain pointing to that ip (like example.com or www.example.com) server_name ; keepalive_timeout 5; client_max_body_size 4G; access_log /home/admin/legaland/logs/nginx-access.log; error_log /home/admin/legaland/logs/nginx-error.log; location /static/ { alias /home/admin/legaland/Legaland/src/static_root/; } # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } -
how to change http to https in django
If you continue to load with http from a site that can be accessed with https, the process is still alive, but you cannot enter the screen. For this I also clear the cache and turn off the pc, but the same thing happens. I ran Django with python manage.py runsslserver --certificate django.crt --key django.key. For this I set secure_ssl_redirect to true in settings.py to change http to https, but to no avail. Also, when I created a new Django project and ran it on the same server, this problem did not occur. Please help me. I've been wandering around for 2 weeks. -
Django - Getting an object from an obeject
Views: class Book_PrommotionViewSet(viewsets.ViewSet): def list(self, request): queryset = Prommotion.objects.filter(active=True) serializer = PrommotionSerializer(queryset, many=True) return Response(serializer.data, HTTP_200_OK) Prommotion Model: class Prommotion(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) precent = models.DecimalField(decimal_places=2, max_digits=255, null=True, blank=True) active = models.BooleanField(default=False) date_from = models.DateField() date_to = models.DateField() book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = 'Prommotion' verbose_name_plural = 'Prommotions' Book Model: class Book(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255, null=True, blank=True) author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True, blank=True) price = models.DecimalField(decimal_places=2, max_digits=255) published = models.DateField() edition = models.CharField(max_length=255) isbn_code = models.CharField(max_length=255) pages = models.IntegerField(blank=True, null=True, default=0) description = models.TextField(null=True, blank=True) cover = models.CharField(max_length=30, choices=Cover.choices(), default=None, null=True, blank=True) genre = models.CharField(max_length=30, choices=Genre.choices(), default=None, null=True, blank=True) language = models.CharField(max_length=30, choices=Language.choices(), default=None, null=True, blank=True) format = models.CharField(max_length=30, choices=Format.choices(), default=None, null=True, blank=True) publisher = models.CharField(max_length=30, choices=Publisher.choices(), default=None, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Meta: verbose_name = 'Book' verbose_name_plural = 'Books' So, im trying to get the object "Book" from prommotion. Book is a ForeignKey in "prommotion" and i filtered all the prommotions that are active. And i need to get the "Book" object from the Prommotion if its active … -
Is there a Django Graphql Generator?
I am wondering if there a way to automatically generate graphql queries and mutations in Django applications. Using Ariadne + Django + Python 3.9 system i created is here: https://github.com/bastianhilton/Alternate-CMS -
Django sum values of from a for loop in template
I want to show the sum for the values (cals, protein, carbs, etc) of multiple foods in a new table but have no idea how to do it in a django template. Heres what the for loop displays {% for food in meal.foods.all %} <div class='table-container'> <table class='food-table'> <thead> <tr> <th>Name</th> <th>Calories</th> <th>Protein</th> <th>Carbs</th> <th>Fat</th> <th>Sugar</th> <th>Sodium</th> </tr> </thead> <tbody> <tr> <td>{{ food.name }}</td> <td>{{ food.calories }}</td> <td>{{ food.protein }}g</td> <td>{{ food.carbs }}g</td> <td>{{ food.fat }}g</td> <td>{{ food.sugar }}g</td> <td>{{ food.sodium }}mg</td> </tr> </tbody> </table> </div> {% endfor %} The new table would look like this but just display the totals. -
How do I create a delete button in the Image field?
I'm new to programming and I'm taking my first steps, especially in django, in this case I used ImageField to upload images on the site I'm programming, but it only shows the path of the image and I was wondering how I could add a delete button to the page to edit a post...enter image description here enter image description here -
Save a field as hash and compare it in django
I created my own user model: class CustomUser(AbstractBaseUser,PermissionsMixin): phone_number = models.CharField(verbose_name="Mobile Number", max_length=11, unique=True, blank=False, null=False) security_code = models.IntegerField(verbose_name="Security Code",default=create_security_code) security_code_creation = models.DateTimeField(auto_now=True) a user can login with password or security code. I will text them the security code if needed. but I don't want to store security code as plain text in my database. I want to store it like password (hashed). I found from django.contrib.auth.hashers import make_password which I can use to create a hashed version of security code. my question is should I write a separate authentication backend or simply write/use a function like check_password that is implanted in AbstractBaseUser? -
Validating nested dictionaries containing dynamic keys using DRF Serializers
I am working on writing serializers for an existing API for the purpose of auto-generating OpenAPI documentation for the project. One of the issues I'm running into is defining serializers to validate the returned data from some of the views. Here is the structure of the data: { "airmass_data": { "site-A": { "times": ["2021-09-09T09:54","2021-09-09T10:04"], "airmasses": [2.900041850251779, 2.687634707193725] }, "site-B": { "times": ["2021-09-09T09:54","2021-09-09T10:04"], "airmasses": [2.900041850251779, 2.687634707193725] }, ... }, "airmass_limit": 3.19 } There can be an arbitrary number of "site-X" keys, and they are dynamically generated - which is definitely part of my issue. Here is how I've set up my serializers, which I think mostly matches my dictionary structure: class SiteAirmassDatumSerializer(serializers.Serializer): times = serializers.ListField(child=serializers.CharField()) airmasses = serializers.ListField(child=serializers.FloatField()) class SiteAirmassSerializer(serializers.Serializer): site = SiteAirmassDatumSerializer(source='*') class AirmassSerializer(serializers.Serializer): airmass_data = SiteAirmassSerializer(source='*') airmass_limit = serializers.FloatField() However, when passing my dictionary into the the serializer and attempting to validate it, the serializer.errors attribute has: { "airmass_data": { "site": [ "This field is required." ] } } Is there a good way to write a set of serializers such that it deals with dynamically generated keys? I am mostly trying to write this to validate the general structure of the returned dictionary - not necessarily the keys … -
Heroku wont connect to my django database
my database is the default sqlite3 database, I tried with multiple projects but Heroku won't connect to the database, hope u guys will help me I'm new to Heroku i don't know if I'm missing something these are my settings setup for Heroku, I have no static files import django_heroku import dj_database_url ALLOWED_HOSTS = ['*'] DATABASES = { 'default': dj_database_url.config() } django_heroku.settings(locals()) -
In Django template button is not working as expected
In my project, I used the function toggle_follow which is working fine but in my template on the first click nothing changed in the second click it turns to unfollow as expected, and after again clicking it becomes to follow which is also expected. After that, it doesn't work. Though the follow shows in the following tab and update the list but the button stopped working. The problem is, the follow counter is not updating properly and not storing into database as If I follow someone and another user visit the same profile, the user by default see that he is following the user also whom I'm following which is not as expected. However, for first three time the result is expected and working properly. my models.py >>> class Follow(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follow") followed = models.ForeignKey(User, on_delete=models.CASCADE, related_name="followers") class Meta: verbose_name = "following" verbose_name_plural = "followings" unique_together = ["user", "followed"] def str(self): return f"{self.user} is following {self.followed}" def followed_post(self): return self.followed.posts.order_by("-date").all() my views.py >>> @login_required def toggle_follow(request, id): if request.method == "GET": return HttpResponse(status=405) if request.method == "POST": try: follow_obj = Follow.objects.get(user=request.user.id, followed=id) except Follow.DoesNotExist: try: to_follow = User.objects.get(pk=id) except User.DoesNotExist: return HttpResponse(status=404) else: new_follow_obj = Follow(user=request.user, followed … -
How to learn python pandas with django?
Trying to integrate python pandas scripts with django, but it's not working. Is there any good course or book to recommend? -
Django: Is there a way to let Heroku manage js and css files but let images come from S3 bucket?
I am buiding an app with django. I uploaded all my static files to an S3 bucket. Js and css files included. And in DEBUG = False I'm getting my files from that bucket I am hosting my app in Heroku, so I couldn't serve images from there. That's way I'm getting my images from an externar source. But now I'm facing some problems when I have all my files in the S3 bucket. And I also think it's not really necessary to serve js and css from there too. So is there a way to let images come from the S3 bucket but serve my js and css files from the host (heroku)? -
Django filtering ForeignKey
This is view: def post(self, request): author_request = request.data.get("author") queryset = Book.objects.filter(author=author_request) serializer = BookSerializer(queryset, None) return Response(serializer.data, HTTP_200_OK) This is model: class Author(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) full_name = models.CharField(max_length=255, null=True, blank=True) about = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.full_name class Meta: verbose_name = 'Author' verbose_name_plural = 'Authors' So, when i try to filter the book by author i get the error. The error tells me that the POST data that i entered which is "Aleksa Petrovic" a name of a author that exists in the database is not an UUID. So when i filter it, it filters by UUID and i want it to filter by "full_name"