Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i setup scheduling task on Django?
I've create a reporting module using Django for a project i have. Essentially what it does it has a list of reports where you can select a start date and end for the reports and run it. Then the report view runs a cursor query and fetches results. All of this works. But now i want to implement a queuing feature. Where you set a start date and end date then set a date time for the report to be automatically run (Which will be stored in a database) and keep the result. The user then can come back anytime to revisit the report without it being rerun What is the best way to achieve this? Thanks I've tried to use a cron job which run daily to check for reports and run them to achieve this but this fails to fulfill time scheduling -
Sum of two Count in one query
Files and folders can be "inside" folders. I need to get the count of files and folders in each folder in queryset. models.py class Folder(models.Model): id = ShortUUIDField(primary_key=True, default=ShortUUIDField.random, editable=False) user = models.ForeignKey(Profile, on_delete=models.PROTECT) parent = models.ForeignKey("self", null=True, blank=True, related_name="children", on_delete=models.PROTECT) description = models.JSONField() class File(models.Model): id = ShortUUIDField(primary_key=True, default=ShortUUIDField.random, editable=False) user = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.PROTECT) folder = models.ForeignKey(Folder, null=True, blank=True, on_delete=models.PROTECT) description = models.JSONField(default=default_file_description) show_in_catalog = models.BooleanField(default=False) serializers.py class FolderSerializer(serializers.ModelSerializer): title = serializers.CharField(source='description.title') element_count = serializers.IntegerField() class Meta: model = Folder fields = ['id', 'title', 'element_count'] I tried to count it like that: views.py def retrieve(self, request, *args, **kwargs): folder = self.get_object() return Response( dict( parent=folder.parent_id, folders=CatalogFolderSerializer( Folder.objects.filter( parent=folder, user__user__username=CONTENT_USER ).alias( file_count=Count("file", filter=Q(file__show_in_catalog=True)) ).alias( folder_count=Count("children") ).annotate( element_count=F('material_count') + F('folder_count') # This count i need ), many=True, ).data ) ) But it works incorrect :( I need to count it in views.py not in serializer, using SerializerMethodField and smth like that. -
is there a reason why I run the command to create superuser but it throws an error that 'email is not a valid UUID field'?
I am not new to Django, but I am gaining experience, by working on this project. I use Django 4.2. I created a model for users and ran migrations. I tried to create a superuser, but got an error that 'email is not a valid UUID field'. I understand that 'email' is being passed to the 'UUID' field but I specified that for ID field, so there is a problem with the operation but I can't seem to understand where. This is my models.py file import uuid from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.core.exceptions import FieldError class UserManager(BaseUserManager): def create_user(self, email, username, password, **kwargs): if not email: raise ValueError('Email must be given!') kwargs.setdefault('is_active', True) kwargs.setdefault('is_superuser', False) email = self.normalize_email(email) user = self.model(email, username, **kwargs) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **kwargs): if not email: raise ValueError('Email must be given!') kwargs.setdefault('is_active', True) kwargs.setdefault('is_superuser', True) email = self.normalize_email(email) superuser = self.model(email, **kwargs) superuser.set_password(password) superuser.save(using=self._db) return superuser class UserAccount(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) email = models.CharField(max_length=250, unique=True, null=False) username = models.CharField(max_length=250, unique=True, null=False) password = models.CharField(max_length=200, null=False) is_active = models.BooleanField(default=False) is_verified = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) created_time = models.DateTimeField(auto_now_add=True, null=False) last_login = models.DateTimeField(auto_now=True) … -
connect to PostgreSQL server: FATAL: no pg_hba.conf entry for host "" with external database azure
I have a django docker container running. And I try to connect with the azure postgres db. But when I log in in the admin panel from django, I get this error: OperationalError at /admin/login/ FATAL: password authentication failed for user "welzijn" FATAL: no pg_hba.conf entry for host "0.0.145.0", user "welzijn", database "welzijn", no encryption And I thought that I had the solution. Because a lot of resources suggest that you have to edit the pg_hba file and the postgresql file. So I did that: pgb_hba: host all all 0.0.0.0/0 scram-sha-256 And postgresql: listen_addresses = '*' I rebooted the machine. But it seems that it didn't solve the issue. I still get this error: OperationalError at /admin/login/ FATAL: password authentication failed for user "welzijn" FATAL: no pg_hba.conf entry for host "0.0.145.0", user "welzijn", database "welzijn", no encryption Request Method: POST Request URL: http://localhost/admin/login/?next=/admin/ Django Version: 4.2.4 Exception Type: OperationalError Exception Value: FATAL: password authentication failed for user "welzijn" FATAL: no pg_hba.conf entry for host "85.148.145.211", user "welzijn", database "welzijn", no encryption Exception Location: /py/lib/python3.9/site-packages/psycopg2/__init__.py, line 122, in connect Raised during: django.contrib.admin.sites.login Python Executable: /py/bin/python Python Version: 3.9.9 Python Path: ['/usr/src/app', '/py/bin', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/py/lib/python3.9/site-packages'] Server time: Wed, 23 Aug … -
login page is not redirecting to index page even after entering correcting login information
I am trying to buid a django application with login form, my code looks like login.html <form class="container my-5" action="/" method="post"> {% csrf_token %} <div class="row mb-3"> <label for="name" class="col-sm-2 col-form-label">name</label> <div class="col-sm-10"> <input type="text" class="form-control" id="name" name="username"> </div> </div> <div class="row mb-3"> <label for="inputPassword3" class="col-sm-2 col-form-label">Password</label> <div class="col-sm-10"> <input type="password" class="form-control" id="password" name="password"> </div> </div> <button type="submit" class="btn btn-primary">Sign in</button> </form> Views.py from django.shortcuts import render,redirect from django.contrib.auth import authenticate from django.contrib.auth import logout,login from django.contrib.auth.models import User def index(request): if request.user.is_anonymous: return redirect("/login") return render(request,'index.html') def loginuser(request): if request.method=="POST": username=request.POST.get('username') password=request.POST.get('password') print(username,password) user = authenticate(username=username, password=password) if user is not None: login(request,user) return redirect("/") else: return render(request,'login.html') # No backend authenticated the credentials return render(request,'login.html') def logoutuser(request): logout(request) return redirect('/login') urls.py from django.contrib import admin from django.urls import path,include from home import views urlpatterns = [ `your text` path('', views.index, name="index"), path('login', views.loginuser, name="login"), path('logout', views.logoutuser, name="logout"), ] I tried to print username and password but it is not coming in the terminal Can anyone please help me with that? -
Hotwire Turbo Frame in Django application stops django-bootstrap-datepicker-plus from showing
In my Django App I use a Turbo Frame in a DetailView. The Turbo Frame loads a form into the DetailView. This form has a datefield for which I use a Datepicker (django-bootstrap-datepicker-plus). If I call the form directly the Datepicker works just fine, but when the form is called into the DetailView via Turbo Frame the Datepicker does not show. Any suggestions on how to solve this and whats the underlying issue is? Best I tried to use Stimulus to initialize the Datepicker but so far I have no success and I also couldnt find any Q&A in the Internet. -
How can I know on what date and time the user has clicked on a button and then print it in another Django template?
I have these two buttons found in my Django .html: <div class="d-flex justify-content-center" style="margin: 1em;"> <a id="btn-aceptar" href="{% url 'cambiar_estado_factura' factura.id_factura 2 %}" class="btn btn-success btn-lg mx-2" style="width: 150px;">Aceptar</a> <a id="btn-rechazar" href="{% url 'cambiar_estado_factura' factura.id_factura 3 %}" class="btn btn-danger btn-lg mx-2" style="width: 150px;">Rechazar</a> </div> I have those two buttons in the d_facturaspendientes.html and what I want to know is how can I get the date and time when the user clicks on one of the buttons. That date and time, I want to print it in facturasvalidadas.html, but I don't know how to do it. Can someone give me a hand? Below I attach the table and the commented line where the date and time should go: <table class="table" style="padding: 1em;"> <thead> <tr> <th>ID</th> <th>Proveedor</th> <th>Fecha de emisión</th> <th>Fecha de validación</th> <th>Importe</th> <th>Estado</th> </tr> </thead> <tbody> {% for factura in facturas %} <tr class="factura-row-link" onclick="window.location='{% url 'v_facturasvalidadas_details' factura.id_factura %}'"> <td>{{ factura.id_factura }}</td> <td>{{ factura.id_proveedor.nombre }}</td> <td>{{ factura.fecha_factura_recibida }}</td> <td>HERE SHOULD BE THE DATE AND TIME THAT WE HAVE HEARD WHEN THE USER HAS CLICKED ON THE BUTTONS</td> <td>{{ factura.importe }} €</td> <td>{{ factura.id_estado.value }}</td> </tr> {% endfor %} </tbody> </table> I want to know the day and time when the … -
Request Taking too long in Django
I have been trying to build a chemotherapy drug dose scheduling (mathematical model) as part of my thesis. Firstly I did the logic MATLAB and then implemented it in python. Then I tried using Django. While the app runs fine in localhost, but fails when I host it. Mainly because of the time it takes to calculate the whole process. In my localhost it takes around 40 seconds to 1 min to calculate but I get the result. When I host it in railway it gives up after first iteration. It is based on Fuzzy Logic. Also I didn't follow software development principle when creating this, so the code is a mess. I do not know what should I include for reference. I am adding the github link- FES Tool The error I get from railway is Application failed to respond. Any suggestion is apprecated. I tried to host a django project that takes a lot of time calculating in the backend and I failed. -
Is in django way save some data from database in RAM and after fixed time update it
For example I have some data that is fixed for all user. Now for each request I get the same data from DB. Is there way to optimize it. I tryed make a class which stores my needed data and init time by datetime; and it has method which gets current time, compare it with init time, and if difference more than 12 hours it makes new request to database, update value in class and returns it; else it returns old value. It works but i think that it isn't right way. Are some ideas? -
Implementing configurable feature-based roles and permissions in django rest framework
I have a scenerio where I am creating custom roles and assigning permissions to them for each fetaure. The process is fully customized and generic and it works for CRUD operations(like create user, read user, update user and delete user) perfectly. Now there is a little change in requirements where I have multiple operations for one feature like create order, accept order, split order, refer order. Now I want to create a roles and permissions so that it covers this part of my problem as well. Inititally I had four models i.e. Role, Permission, Feature, RoleFeatureAssociation(fields: role, feature, list(permissions)). I was checking permissions upon each request and if the particular user had that particular permission available for that feature then request was processed. Keeping this procedure in view as well how should I manage new requirements since I have multiple operations for feature instead of just create, read, update and delete. -
How can I make the user click on a button in a Django .html to modify one of the database values?
I have these two buttons found in my Django .html: <div class="d-flex justify-content-center" style="margin: 1em;"> <button type="button" class="btn btn-success btn-lg mx-2" style="width: 150px;">Accept</button> <button type="button" class="btn btn-danger btn-lg mx-2" style="width: 150px;">Reject</button> </div> What I need, is that when the user clicks on the button, that it changes a value, in this case of an invoice of my database. That is to say, now the invoice is in factura.id_estado=1; so, if the user clicks on Accept, factura.id_estado must change to 2 (factura.id_estado=2). The same happens when the user clicks on Reject, factura.id_estado will change to 3 (factura.id_estado=3). I don't know if it is necessary or not, but my database is the Django database which is hosted in my Docker. -
Can't apply migrations in Django project
I'm creatig a custom user model, inherit it from AbstractUser. When i'm making migrations i got ValueError('Related model %r cannot be resolved' % self.remote_field.model) ValueError: Related model 'reviews.user' cannot be resolved from django.contrib.auth.models import AbstractUser from django.db import models # Пользовательские роли. ROLES = [ ('user', 'Пользователь'), ('moderator', 'Модератор'), ('admin', 'Администратор'), ] class User(AbstractUser): username = models.CharField( max_length=150, unique=True, ) email = models.EmailField( max_length=254, unique=True, blank=False, ) first_name = models.CharField( max_length=150, null=True, blank=True, ) last_name = models.CharField( max_length=150, null=True, blank=True, ) bio = models.TextField( verbose_name='Биография', blank=True, null=True, ) role = models.CharField( max_length=256, verbose_name='Роль', choices=ROLES, default='user', ) class Meta: verbose_name = 'Пользователь', verbose_name_plural = 'Пользователи' def __str__(self): return self.username class Title(models.Model): name = models.CharField( 'Название', max_length=256, ) year = models.IntegerField('Год выпуска') description = models.TextField('Описание') class Meta: verbose_name = 'объект "Произведение"' verbose_name_plural = 'Произведения' def __str__(self): return self.name I can't understand what is wrong. -
Getting a ValueError when trying to alter a Django model field related to a ManyToManyField
I'm encountering an issue while trying to make alterations to a Django model field in my project. Specifically, I'm attempting to modify the 'likes' field in the 'Tweet' model. However, I'm receiving the following error: "ValueError: Cannot alter field tweets.Tweet.likes into tweets.Tweet.likes - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields)" Here are the relevant parts of my code: import random from django.conf import settings from django.db import models User = settings.AUTH_USER_MODEL class TweetLike(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) tweet = models.ForeignKey("Tweet", on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) class Tweet(models.Model): # id = models.AutoField(primary_key=True) parent = models.ForeignKey("self", null=True, on_delete=models.SET_NULL) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="tweets") likes = models.ManyToManyField(User, related_name='tweet_user', blank=True, through=TweetLike) content = models.TextField(blank=True, null=True) image = models.FileField(upload_to='images/', blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-id'] I'm not quite sure how to proceed and would appreciate any guidance on how to resolve this error. Thank you for your help! I attempted to modify the 'likes' field directly in the model, but it resulted in the error mentioned above. -
Strategy for syncing a SQL database with a spreadsheet?
This is more of a general design pattern and UX question than a technical one. I am working on a SQL database which contains product inventory (using Django). Currently, this inventory is managed by another (non-technical) employee via a spreadsheet which contains all inventory information and is updated daily. In order to support this employee's workflow, I would like to have the option of uploading the spreadsheet to the server, have it processed, and reflect the changes in the inventory (SQL database). Here's the catch: The SQL database can also be updated by customers via our API. When a user purchases an item, it is removed from the inventory, meaning that our employee's spreadsheet becomes out of sync. Furthermore, if users are modifying the database and the employee does not have the most up-to-date version, when the employee goes to upload their spreadsheet, the changes made by users would be overridden. Here are options I am considering: Require our employee to adopt a custom interface to manage inventory and ditch the spreadsheet. I am hesitant on this option because I want to support their existing workflow. Use an API like on Google Drive to update the spreadsheet programmatically whenever the … -
Should I use `cache.close()` after I finish using cache in Django Views?
I found cache.close() saying below in the doc. *I'm learning Django Cache: You can close the connection to your cache with close() if implemented by the cache backend. So, I use cache.close() after I finish using cache in Django Views as shown below: # "views.py" from django.core.cache import cache def test(request): cache.set("name", "John") cache.set("age", 36) print(cache.get("first_name")) # John print(cache.get("age")) # 36 cache.close() # Here return HttpResponse("Test") My questions: Should I use cache.close() after I finish using cache in Django Views? If I don't use cache.close() after I finish using cache in Django Views, are there anything bad? -
django - Optimize request with indirect relation without any foreign keys
I have 2 models and a view which must join them on matching common_field and then perform some aggregation. The problem is for a given N=5000 rows a request is processed ~30 seconds. Here are myapp/models.py: from django.db import models class MainModel(models.Model): common_field = models.CharField(max_length=20) category = models.IntegerField() # some other fields not relevant for the example class AuxiliaryModel(models.Model): common_field = models.CharField(max_length=21) the_date = models.DateField() myapp/serializers.py: from rest_framework import serializers class MainCategoryAgingSerializer(serializers.Serializer): category = serializers.IntegerField() age_0_99 = serializers.IntegerField() age_100_199 = serializers.IntegerField() age_200_299 = serializers.IntegerField() age_300_399 = serializers.IntegerField() age_400_plus = serializers.IntegerField() myapp/views.py: import datetime from django.db import models from django.db.models import Case, Count, F, OuterRef, Subquery, Value, When from django.db.models.functions import ExtractDay from rest_framework import generics from django_custom_join.myapp.models import AuxiliaryModel, MainModel from django_custom_join.myapp.serializers import MainCategoryAgingSerializer class MainCategoryAgingListAPIView(generics.ListAPIView): serializer_class = MainCategoryAgingSerializer def get_queryset(self): return ( MainModel.objects .annotate( the_date=Subquery( AuxiliaryModel.objects.filter( common_field=OuterRef("common_field"), ) .values("the_date"), ), curr_age=ExtractDay(Value(datetime.date.today()) - F("the_date")), ) .values("category") .order_by("category") .annotate( age_0_99=Count( Case( When(curr_age__range=[0, 99], then=1), output_field=models.IntegerField(), ), ), age_100_199=Count( Case( When(curr_age__range=[100, 199], then=1), output_field=models.IntegerField(), ), ), age_200_299=Count( Case( When(curr_age__range=[200, 299], then=1), output_field=models.IntegerField(), ), ), age_300_399=Count( Case( When(curr_age__range=[300, 399], then=1), output_field=models.IntegerField(), ), ), age_400_plus=Count( Case( When(curr_age__gte=400, then=1), output_field=models.IntegerField(), ), ), ) ) myapp/urls.py: from django.urls import path from django_custom_join.myapp.views import MainCategoryAgingListAPIView urlpatterns = … -
ImportError: cannot import name 'urlquote' from 'django.utils.http'
How to solve this problem.I've tried to import like that from urllib.parse import quote django.utils.http.urlquote = quote.But it's not effective.Please let me know if you can solve this problem. Please let me know if you can solve this problem. -
Dokku: how to change heroku stack to heroku-20 or heroku-22 (from heroku-18)
I have been working on a Django (Python) project using Dokku (thus Heroku) for deployments. Up until today, all deployments worked just fine, but since this morning, I get this error message: Requested runtime 'python-3.10.12' is not available for this stack (heroku-18). I know that python-3.10.12 is available on heroku-18 so I assume I (finally) have to change stack since heroku-18 is deprecated. I have tried using this command on Dokku: dokku buildpacks:add --index 1 {APP-NAME} https://github.com/heroku/heroku-buildpack-python.git, but it doesn't solve my problem (heroku-18 is still being used). Any help would be greatly appreciated -
Need Clarification on Correctly Saving Uploaded File Data to Default Storage using Django-minio-storage?
I've received a response that has been helpful so far, and everything has been functioning as expected. However, I've encountered some confusion when attempting to save uploaded file data to the default storage. In my current implementation, I have a method named _save_uploaded_file_data, which ideally should handle the task of saving uploaded file data to the default storage. This comes after successfully uploading the file to MinIO using a presigned URL. Here's the relevant excerpt of my code: Although my code appears straightforward, I'm uncertain about the accuracy of my approach, particularly when it comes to saving the uploaded file data to the default storage, which could potentially be local storage. I would greatly appreciate guidance, insights, or suggestions on the proper way to handle this situation. If you could provide any tips, relevant code snippets, or best practices related to this scenario, it would be immensely helpful. Thank you. models.py class FileModel(models.Model): uploaded_file = models.FileField(upload_to='uploads) minio.py class MinioUploader: def __init__(self, file): self.client = default_storage.client self.bucket_name = settings.MINIO_STORAGE_MEDIA_BUCKET_NAME self.file = file self.put_presigned_url = self._get_put_presigned_url() def _get_put_presigned_url(self): return self.client.presigned_put_object( self.bucket_name, self.tus_file.filename, expires=timedelta(minutes=2), ) def upload_file(self, file_path): file_data = self._read_file_data(file_path) response = self._upload_to_presigned_url(file_data) if response.status_code == 200: self._save_uploaded_file_data(file_data) return response def _read_file_data(self, … -
Annotate using primary key in Django
Consider a model with some stuff and a method property: class MyModel(models.model): blah blah @property def func(self): blah blah Suppose now I want to annotate MyModel objects with the value of the function: MyModel.objects.annotate(func_value=MyModel.objects.get(pk=Subquery(OuterRef('pk'))).func) but this throws the following error: OuterRef object has no attribute 'clone'. How do I properly annotate the function values to the query set? -
Conflict when using django-simple-history with django-computedfields libraries together
In my django app I have a model with some computed fields, i have used django-computedfields to achive that. Now i am trying to add django-simple-history to my model, but aparently there is a conflict when using these two django libraries. When making migrations I am getting the following error. computedfields.resolver.ResolverException: <class 'arbolsaf.models.HistoricalSpeciesModel'> is not a subclass of ComputedFieldsModel This is my code (I am not showing all fields in the model): from computedfields.models import ComputedFieldsModel, computed, compute from simple_history.models import HistoricalRecords class SpeciesModel(BasicAuditModel, ComputedFieldsModel): history = HistoricalRecords() VALUES_CHOICES = ( ("ninguno", "Ninguno"), ("bajo", "Bajo"), ("medio", "Medio"), ("alto", "Alto"), ) cod_esp = models.CharField(_("Código especie"), max_length=50, unique=True) taxonid_wfo = models.CharField(_("Taxon ID WFO"), max_length=50) nombre_comun = models.CharField(_("Nombre común"), max_length=255) nombre_cientifico = models.CharField(_("Nombre científico"), max_length=255) nombre_cientifico_completo = models.CharField(_("Nombre científico completo"), max_length=255) familia = models.ForeignKey("arbolsaf.FamilyModel", verbose_name=_("Familia"), on_delete=models.RESTRICT) genero = models.ForeignKey("arbolsaf.GenderModel", verbose_name=_("Género"), on_delete=models.RESTRICT) epiteto = models.CharField(_("Epíteto"), max_length=50) variedad_subespecie = models.CharField(_("Variedad/Subespecie"), max_length=50, blank=True, null=True) autor = models.CharField(_("Autor"), max_length=255, blank=True, null=True) nativa = models.BooleanField(_("Nativa?")) class Meta: db_table = 'arbolsaf_species' managed = True ordering = ["nombre_cientifico"] verbose_name = 'Especie' verbose_name_plural = 'Especies' -
Djago - Access related_name in queryset using as_manager
I am having some difficulty figuring out how to use foreign key (related_name) in a queryset using as_manager() Below is the mode and queryset. Everything works except the `get_powerbars()' method. I cannot seem to find any information about how to access the reverse foreign key lookup. Anything I try gets me the error (or similar) 'PowerbarQuerySet' object has no attribute 'outlet' What am I missing? If 'related_name' is not available in a queryset, how would one go about returning all the powerbars and their outlets in a simple fashion. import logging from django.db import models logger = logging.getLogger(__name__) class PowerbarQuerySet(models.QuerySet): """Additional queryset functions""" def get_powerbar_ips(self): try: all_bars = ( self.all().values_list("ip", flat=True).order_by("ip") ) return list(all_bars) except self.model.DoesNotExist: return None def get_powerbars(self): try: all_outlets = ( self.all().outlet ) return all_outlets except self.model.DoesNotExist: return None class Powerbar(models.Model): objects = PowerbarQuerySet.as_manager() name = models.CharField(max_length=200) building = models.CharField(max_length=200) group = models.CharField(max_length=200) ip = models.GenericIPAddressField() def __unicode__(self): return f'{self.name} @ {self.ip}' def __str__(self): return f'{self.name}' class Meta: base_manager_name = 'objects' class PowerbarOutlet(models.Model): powerbar = models.ForeignKey(Powerbar, on_delete=models.CASCADE, related_name='outlet') number = models.PositiveIntegerField() label = models.TextField(blank=True, default="") class Meta: unique_together = ("powerbar", "number") ordering = ("powerbar", "number") def __unicode__(self): return f'{self.number} @ {self.powerbar}' def __str__(self): return f'{self.powerbar}' I have … -
HTMX / Django List Of Forms - CSRF Token Issue?
I've got an application where I'm listing out a bunch of forms - it loads a csrf_token into each form. Each form is a simple dropdown for choosing a 'color' for each item in the list. I have a ListView that returns a list of placement objects like so: {% for placement in placements %} {% include 'placements/snippets/placement_update_form.html' %} {% endfor %} The placement_update_form.html looks like this: <form id="placementUpdateForm" action="{{ placement.get_update_url }}" method="post" hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'> <input type="hidden" name="id" value="{{ placement.id }}"> <label for="color">Color</label> <select name="color" id="color{{ placement.pk }}" class="form-select" hx-post="{% url 'placements:placement-update' placement.pk %}" hx-target="closest #placementUpdateForm"> <option value="" {% if not placement.color %}selected{% endif %}>Default</option> {% for value, display_name in placement_colors %} <option value="{{ value }}" {% if value == placement.color %}selected{% endif %}>{{ display_name }}</option> {% endfor %} </select> </form> I am using HTMX to POST the data to an UpdateView on my backend; which redirects to a success_url that is a DetailView that simply returns the placement_update_template and replaces that exact item in the DOM. It works - once. The first POST works and saves the color as expected. The template is replaced in the DOM, but if you choose a different color (triggering a second … -
instead of the username django value, I get "<django.db.models.query_utils.DeferredAttribute object at 0x0000017E365030D0>" (i see in SQLiteStudio)
I wanted to create a user without entering username and password, but only first_name, last_name and phone_number and so that username when creating a user was equal to phone_number models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): image = models.ImageField(upload_to='images/', null=True, blank=True) phone_number = models.CharField(max_length=11, help_text="Введите номер телефона пользователя", verbose_name="Номер телефона") class Meta(AbstractUser.Meta): pass def save(self, *args, **kwargs): self.username = User.phone_number super().save(*args, **kwargs) def __str__(self): return self.last_name forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from users.models import User class UploadImageForm(forms.ModelForm): class Meta: model = User fields = ['image'] class UserCreateForm(UserCreationForm): username = forms.CharField(label='username', max_length=100) phone_number = forms.CharField(label='phone_number', max_length=11) class Meta(UserCreationForm.Meta): model = User fields = ('username', 'phone_number') def save(self, *args, **kwargs): self.username = self.phone_number super().save(*args, **kwargs) admin.py from django.contrib import admin from django.contrib.admin import ModelAdmin from django.contrib.auth.admin import UserAdmin from django.utils.translation import gettext_lazy as _ from .forms import UserCreateForm from .models import * @admin.register(User) class CustomUserAdmin(ModelAdmin): add_form = UserCreateForm list_display = ('last_name', 'phone_number', 'is_staff') list_display_links = ('last_name', 'phone_number') search_fields = ('last_name', 'phone_number') ordering = ['last_name'] add_fieldsets = ( ( None, { "classes": ("wide",), "fields": ("username", 'phone_number'), }, ), ) fieldsets = ( (_("Personal info"), {"fields": ("first_name", "last_name", "phone_number", 'image')}), ( _("Permissions"), { "fields": ( "is_active", … -
Django:- Identification and Access Control
I'm working in an intelligence agency. Each and every agent of that agency has to provide their generated number on a certain page before they can access some pages. In our CustomUser model, we have a field that asks the user for their full name. We want the name to appear in the 'name' field of the Access model in real-time. What we want is that when someone types their number in the Access model, their full name in the CustomUser model should appear in the 'name' field of the Access model in real-time. My signals: @receiver(post_save, sender=User) def generate_number(sender, instance, created, **kwargs): if created: random_number = ''.join(random.choices(string.digits, k=10) Account.objects.create(user=instance, secret_number=random_number) My models: class Account(models.Model): user = models.ForeinKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) secret_number = models.IntegerField() Class Access(models.Model): user = models.ForeinKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) account_number = models.IntegerField() name = models.CharField(max_length=50) Note: We don't want to use the current user, which means that we want to allow someone on the platform to use another agent number to log in. I don't know if this is possible in django, that's why I'm asking this question. Thanks.