Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Animated pictures in JavaScript, problem: flickering screen and resizing
As I mentioned in the title I have a problem properly embedding my animation in my Django project. At some point, I decided to update the logo used by my web page built-in Django. Having small experience with JavaScript I was looking for approaches that fit my needs. I built an animation engine having some inspiration from this StackOverflow answer. (Thanks to user gilly3). My approach is, though, different in this topic because I realised that if I would have a lot of pictures then sticking/concatenating them together in one file might be difficult. I've decided to use another approach and use a bunch of files instead of one. For that sake, I built a function with a generator which I could call in another function to display all pictures in order. This animation engine looks like this: function* indexGenerator() { let index = 1; while (index < 28) { yield index++; } if (index = 28) yield* indexGenerator(); }; var number = indexGenerator(); setInterval(function animationslider() { var file = "<img src=\"../../../static/my_project/logos/media/slides_banner_f/slide_" + number.next().value + ".jpg\" />"; document.getElementById("animation-slider").innerHTML = file; $("#animation-slider").fadeIn(1000); }, 100); $("#animation-slider").fadeIn(1000); doesn't do the trick with values from 10-1000. I record what this looks like: https://youtu.be/RVBtLbBArh0 I … -
Protecting Rest API Routes against expired token using Django Rest Framework and JWT Authentication
I am pretty new to Django Rest Framework and I have created JWT Authentication. I have set the access token expiry time to 4 seconds. After when the token expires, I am still able to access the API route. It is not restricting me, nor it is throwing any error such as 401 unauthorized. Please someone help if you can. This is my SimpleJwt settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(seconds=4), 'REFRESH_TOKEN_LIFETIME': timedelta(days=90), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(seconds=4), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=90), } This is my route which I am protecting against expired tokens: @api_view(['GET']) @permission_classes([IsAuthenticated]) def get_notes(request): user = request.user notes = user.notes_set.all() serializer = NoteSerializer(notes,many=True) return Response(serializer.data) -
Can I iterate my context at view to put into my template?
I've created this function at my views to iterate through my pages. for chapter in chapters: context["chapter_page"] = math.ceil((changelogs.index(changelog) + 1) / 2) context["chapter"] = chapters return context I am still making a for a loop in my template, so I cannot remove him. I added this context, but the only returned page is the last page, which means, that my context["chapter_page"] is not iterating. {% for chapter in chapters %} <li> <a href="?page={{ chapter_page }}&#{{ chapter.number }}"> {{ chapter.number }} </a> </li> {% endfor %} Of course, I could not add this logic direct to my template, it is not accepted by Django. {% for chapter in chapters %} <li> <a href="?page={{ math.ceil((chapters.index(chapter) + 1) / 2) }}&#{{ chapter.number }}"> {{ chapter.number }} </a> </li> {% endfor %} I am expecting to do a loop and return each iterated number at my href=page -
Referencing a specified attribute in a model using related field
Assuming you have a Person model with attributes id and username amongst others. class Person(models.Model): id = models.AutoField(primary_key=True) username = models.CharField(unique=True) # other fields In Django Rest Framework there exists the PrimaryKeyRelatedField which represent the target of the relationship using its primary key. When using it in a serializer, it would look something like this class PersonSerializer(serializers.Serializer): id = serializers.PrimaryKeyRelatedField( queryset=User.objects.all(), ) username = serializers.CharField(required=True) However I would like a field that would target the username as well. Something similar to class PersonSerializer(serializers.Serializer): username = UsernameRelatedField(queryset=User.objects.all()) One potential solution I have come across is creating a custom relational field but it doesn't seem to work as expected. I would like to check if a username exists for a user. -
In my virtual environment pip is not working
(env) PS C:\Users\ZEWDU\Documents\EthLink> pip Fatal error in launcher: Unable to create process using '"C:\Users\ZEWDU\Documents\env\Scripts\python.exe" "C:\Users\ZEWDU\Documents\EthLink\env\Scripts\pip.exe" ': The system cannot find the file specified. I was working on my django project and when I try to install packages using pip I get the above error. Not tried anything yet? -
Django queryset mysql
in want and equivalent of this sql query in Django SELECT Gender, ServCode FROM [openimisproductTestDb_16_08_22].[dbo].[tblInsuree] JOIN [openimisproductTestDb_16_08_22].[dbo].[tblServices] ON [openimisproductTestDb_16_08_22].[dbo].[tblInsuree].AuditUserID = [openimisproductTestDb_16_08_22].[dbo].[tblServices].AuditUserID WHERE Gender = 'F' AND ServCode = 'F4' data = Service.objects.filter(code = 'F4').count() | Insuree.objects.filter(gender = 'F').count() I tried like that but the one just adds when I want the women included in the insured table and the F4 code contained in the service table. both tables have the auditUserID column in common -
Two forms on same template in django. How to collaborate the template with the views.py?
I have a template with two forms like this and two textareas where the uploaded content will be returned: <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" id="form_pdf" > <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button> </div> </form> <textarea class="inline-txtarea form-control" cols="70" rows="25"> <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" id="form_excel" > <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" name="form_excel" class="btn btn-warning">Upload!</button> </div> </form> <textarea class="inline-txtarea form-control" cols="65" rows="25"> {{content_excel}}</textarea > and the views.py: class ReadingFile(View): def get(self, request): form = ProfileForm() return render(request, "main/controle_punt140.html", { "form": form }) def post(self, request): types_of_encoding = ["utf8", "cp1252"] submitted_form = ProfileForm(request.POST, request.FILES) content = '' if submitted_form.is_valid(): uploadfile = UploadFile(image=request.FILES["upload_file"]) name_of_file = str(request.FILES['upload_file']) uploadfile.save() for encoding_type in types_of_encoding: with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r', encoding=encoding_type) as f: if uploadfile.image.path.endswith('.pdf'): pass else: content = f.read() return render(request, "main/controle_punt140.html", { 'form': ProfileForm(), "content": content }) return render(request, "main/controle_punt140.html", { "form": submitted_form, }) and forms.py: class ProfileForm(forms.Form): upload_file = forms.FileField() and urls.py: urlpatterns = [ path('', views.starting_page, name='starting_page'), path('controlepunt140', views.ReadingFile.as_view(), name='controlepunt140') ] So this works for the first upload function(pdf). The output is returned to the textarea. But how to have it also work with the second upload function content_excel? I.E: … -
Modify request query string in django decorator
I have a very specific/custom requirement. I have a decorator that is validating request parameters, based on some checks to database I need to add some additional parameters to the request. def validate_request(): """APIkey/uuid or a user session must be present to call api end points Else return a 403""" def decorator(func): def wrapper(request, *args, **kwargs): api_key = request.META.get("HTTP_X_API_KEY") if api_key is not None: //Based on some checks in db, update/add request params return func(request, *args, **kwargs) else: return HttpResponseForbidden('api_key header or user session not found') return wrapper return decorator -
How to insert an item into a Queryset which is sorted by a numeric field and increment the value of the field of all subsequent items
Let´s say, there is a Django model called TaskModel which has a field priority and we want to insert a new element and increment the existing element which has already the priority and increment also the priority of the following elements. priority is just a numeric field without any special flags like unique or primary/foreign key queryset = models.TaskModel.objects.filter().order_by('priority') Can this be done in a smart way with some methods on the Queryset itself? -
How can i resolve django fraudulente site in chrome?
In fact i have a django web app that i host in continous deployment. When i try to open this app in chrome i have a warning red page which notice that the site is fraudulent and in addition i have to enabled the chrome advance protection to be protect of malicious site. In the show more button i can access the site by clicking on open the insecure site. Trying to open the site in edge browser i didn't see any kind of warning and the site open successfully. By this point i think that it's something relative to the security settings of chrome. bellow is the error: *fraudulent website Attackers at xxxxxxxxxxx might trick you into doing something dangerous, like installing software or revealing your personal information (for example, passwords, phone numbers, or credit cards). know more To use Chrome's highest level of security, enable enhanced protection Recently, Google's "Safe Browsing" feature detected phishing from bluecamp.azurewebsites.net. Phishing sites pretend to be other sites to trick you. * You can report a detection issue or, if you understand the risks to your security, access this unsafe site. Then i navigate to the security settings of chrome and disabled the … -
Load all elements of a page at once
I set up a countdown goal when the page loads my countdown is the last to load. How could I make my countdown timer load along with the rest of the page. .html <head> <script type="text/javascript" src="{% static 'js/timer.js' %}" defer></script> </head> <body> <h1> TIMER </h1> <div id="timer"></div> <script type="text/javascript"> let timerQuestion = 1.5; </script> </body> timer.js let temps = timerQuestion * 60 const timerElement = document.getElementById("timer") setInterval(() => { let minutes = parseInt(temps / 60, 10) let secondes = parseInt(temps % 60, 10) minutes = minutes < 10 ? "0" + minutes : minutes secondes = secondes < 10 ? "0" + secondes : secondes timerElement.innerText = `${minutes}:${secondes}` temps = temps <= 0 ? 0 : temps - 1 }, 1000) -
'DateField' object has no attribute 'value_from_datadict'
I've been researching everywhere for an answer for this, but I'm just trying to add a widget to my DateField created on my models.py, where you can see the actual calendar, as if you were doing it directly through html with an input type=date. Since I have a few date fields, this has become a problem because they all need to have the same format as the rest of the form and the widget. Feel like the question has been answered but none of the answers or things I've found have returned a correct answer. models.py class InfoPersonal(models.Model): Fecha = models.DateField() cargo_act = models.CharField(max_length=100) Nombres_y_Apellidos_completos = models.CharField(max_length=100) Lugar = models.CharField(max_length=100) Fecha_de_Nacimiento = models.DateField(null=True) Discapacidad= models.BooleanField() grado = models.CharField(max_length=100, blank=True) Edad = models.IntegerField(validators=[MinValueValidator(18), MaxValueValidator(80)]) Tipo_de_Sangre = models.CharField(max_length=50, choices=sangre_choice) Estatura = models.FloatField(validators=[MaxValueValidator(3.0), MinValueValidator(0.5)]) Direccion_Domicilio_actual = models.CharField(max_length=100) Manzana = models.CharField(max_length=100) Villa = models.CharField(max_length=100) parroquia = models.CharField(max_length=100) Telefono_Domicilio = models.IntegerField(blank=True, null=True) Telefono_Celular = models.IntegerField(blank=True, null=True) Telefono_Familiar = models.IntegerField(blank=True, null=True) cedula = models.IntegerField() estado_civil = models.CharField(max_length=50, choices=list_estado_civil) #Conyuge Nombre_completo_del_conyuge= models.CharField(max_length=100,blank=True) Direccion_Domiciliaria=models.CharField(max_length=100,blank=True) Telefono=models.IntegerField(blank=True, null=True) Cedula_de_Identidad=models.IntegerField(blank=True, null=True) Fecha_de_NacimientoC=models.DateField(blank=True, null=True) Direccion_Trabajo=models.CharField(max_length=100,blank=True) Telefono_del_trabajo=models.IntegerField(blank=True,null=True) #Hijos Nombres= models.CharField(max_length=100,blank=True) Lugar_y_Fecha_de_NacimientoH = models.CharField(max_length=100,blank=True) Esposo_con_Discapacidad = models.BooleanField(blank=True) Hijos_con_Discapacidad= models.BooleanField(blank=True) #InfoFamiliares Apellidos_y_Nombres_1= models.CharField(max_length=100,blank=True) Telefono_Familiar_1 = models.IntegerField(blank=True,null=True) Fecha_Nacimiento_1 = models.DateField(blank=True,null=True) Relacion_de_Parentesco_1 = models.CharField(max_length=100,blank=True) Apellidos_y_Nombres_2= models.CharField(max_length=100,blank=True) Telefono_Familiar_2 … -
lower() was called on None
I have created a custom function to create custom username in a class Inheriting DefaultSocialAccountAdapter. The code is as follows. def _build_username(self,data): from allauth.utils import generate_unique_username if(not data.get('username')): first_name=data.get('first_name','').lower() last_name=data.get('last_name','').lower() suggested_username = (f"{first_name}{last_name}",) username = generate_unique_username(suggested_username) return username But it throws lower() was called on None I was trying to convert the name to lowercase because that is how our database supports usernames. This happens when i try to perform google login authentication method. -
django MultiValueDictKeyError when trying to retrieve "type"
I have a django page that exports the contents of a list to a csv. The filename is set up to include the organization name, but I want it to also include the type of file as well. As far as I can tell, the values are being pulled from here: <div class="p-1 col-12 fw-bold mb-2"> <label class="text-r mb-1">Select File Type:</label> <select name="type" class="form-select" aria-label="Default select example"> <option value="accounts">Accounts</option> <option value="contacts">Contacts</option> <option value="membership">Membership</option> <option value="cg">Community Group</option> <option value="cgm">Community Group Member</option> <option value="so">Sales Order</option> <option value="item">Item</option> <option value="event">Event</option> <option value="tt">Ticket Type</option> <option value="si">Schedule Item</option> <option value="attendee">Attendee</option> </select> </div> <div class="p-1 col-12 fw-bold mb-2"> <label class="text-r mb-1">Organization Name:</label> <input class="form-control" placeholder="Organization Name" type="text" name="name" required /> </div> The python function that calls it is as follows: class CsvView(View): def post(self, request, *args, **kwargs): output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet() data = request.POST["raees"] name = request.POST["name"] d_type = request.POST["type"] data = list(data.split(",")) last = data[-1] first = data[0] data[0] = first.replace("[", "") data[-1] = last.replace("]", "") row = 0 col = 0 for i in data: i = i.replace("'", "") worksheet.write(row, col, i) row = row + 1 workbook.close() output.seek(0) filename = f"{name} {d_type} Issue Tracker.xlsx" response = HttpResponse( output, … -
Django querry set sql
please i want to whrite this sql code in a django code to extract data inside SELECT * FROM tblInsuree FULL JOIN tblServices ON tblInsuree.AuditUserID = tblServices.AuditUserID -
linux shell script won't change to directories/sub directories as expected
I trying to build a shell script to setup a Django directory structure. I know the PC/DOS batch language fairly well and I'm trying to accomplish a directory structure setup. I'd like help having my sh script change/create directories and to run commands.. However... I'm getting an error far below when I run the script immediately below... $ sh setup3.sh proj222 app222 mkdir $1 cd $1 python3 -m venv venv$1 source venv$1/bin/activate pip install django && pip install django-oso && pip install django-debug-toolbar && sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib && pip install Django psycopg2 && python3 -m pip install Pillow django-admin startproject config . mkdir apps mkdir templates mkdir tests mkdir utils cd apps ls django-admin startapp $2 ls cd $2 touch urls.py ls # cd .. python3 manage.py migrate python3 manage.py runserver No such file or directory thalacker@HPLaptop17Linux:~/codeplatoon/djangoProjects$ sh setup3.sh proj222 app222 setup3.sh: 28: source: not found Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: django in /home/thalacker/.local/lib/python3.10/site-packages (4.1.1) Requirement already satisfied: asgiref<4,>=3.5.2 in /home/thalacker/.local/lib/python3.10/site-packages (from django) (3.5.2) Requirement already satisfied: sqlparse>=0.2.2 in /home/thalacker/.local/lib/python3.10/site-packages (from django) (0.4.2) Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: django-oso … -
Django rest framework ModelViewSet displying cuttom HTML instead of default
I am new to Django & DRF and I am trying to replace the default api view given from ModelViewSet (scr1,scr2,scr3) with custom HTML templates. Default view works just fine, i've tested with postman and it can do CRUD functions(at least it seems so), but I have no idea how to substitute the default views with custom html pages. I did follow DRF docs - it worked, also searcged solutions(this one was promising), but I simply can't adopt it my situation. Please help! models.py: from django.db import models class Package(models.Model): prod_name = models.CharField(max_length=255, default=0) quantity = models.IntegerField(default=0) unit_price = models.IntegerField(default=0) def __str__(self): return self.prod_name class Orders(models.Model): order_id = models.CharField(max_length=255, default=0) package = models.ManyToManyField(Package) is_cod = models.BooleanField(default=False) def __str__(self): return self.order_id serializers.py: from rest_framework import serializers from .models import Package, Orders class PackageSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField() prod_name = serializers.CharField(max_length=255, default=0) quantity = serializers.IntegerField(default=0) unit_price = serializers.IntegerField(default=0) class Meta: model = Package fields = "__all__" class OrderSerializer(serializers.HyperlinkedModelSerializer): package = PackageSerializer(many=True) def get_or_create_packages(self, packages): print("this is package in gocp:", packages) package_ids = [] i = 0 for package in packages: print("i=", i) i += 1 package_instance, created = Package.objects.get_or_create(pk=package.get('id'), defaults=package) print("package id:", package.get('id')) package_ids.append(package_instance.pk) print("package_ids:", package_ids) return package_ids def create_or_update_packages(self, packages): package_ids = … -
Django - How to style search filter?
I am having issues styling the search filter. I tried using widget and i was only able to adjust the size of the search filter. My search filter still looks very generic and as a beginner, i have trouble understanding how to style it. I know how to style it using css which is shown in the code below This is my filter code: class Product (django_filters.FilterSet): search = CharFilter( field_name="search", lookup_expr="icontains", widget=forms.TextInput(attrs={ 'size': 100, }) ) css for search bar: .search{ float: right; padding: 6px; border: none; margin-top: 8px; margin-right: 16px; font-size: 17px; } -
How to validate the json format of request in django middleware?
I am creating a new middleware in django. In that I am checking the input in request_body. For that I need to check if the request body is json or not. But while raising exception like malformed request or bad request data I am getting 500 server error. How to handle this? def validate_json(request): try: req_data = json.loads(request) except: raise api_exception.BadRequest() json_body = validate_json(request) You can refer to above psuedo code. I want bad rrequest data 400 as response but getting 500 server error. -
How can I post HTML element value to MySQL Database in Django using Ajax (Without using Form)
I am new to Django and currently facing a problem to post html tag data into database. tables.html <div class="containers pt-5 pb-3 px-4 py-4"> <input type='hidden' name='csrfmiddlewaretoken' value='{{ csrf_token }}' /> <div class="d-none"> <p>User ID: </p><p class="user-id">{{id}}</p> </div> <h3>Case Number:</h3><h2 id="number"></h2> <h4>Description:</h4> <p class="mb-5" id="display"></p> <div class="button d-inline-block" style="max-width: 50%;"> <button type="submit" id="pick" class=" pick-button btn btn-outline-primary border-radius-lg p-3">Pick Case</button> </div> <div class="d-inline-block float-lg-end" style="max-width: 50%;"> <button class="btn btn-outline-danger border-radius-lg p-3">Close</button> </div> </div> <script> $("#pick").click(function(){ var user = $('.user-id').text(); var ca = $('#number').text(); ca = $.trim(ca); $.ajax({ type:"POST", url:"{% url 'dashboard:pick_case' %}", data:{ user_id:user, case_id:ca, csrfmiddlewaretoken: '{{ csrf_token }}' }, success:function(data){ alert(data); } }); }); </script> Views.py def pick_view(request): if request.method == 'POST': case_id = request.POST.get('case_id') print(case_id) status = 2 picked = Transaction() picked.Case_ID = case_id picked.Status = status picked.save() return HttpResponse("Case Picked Successfuly!") else: return HttpResponse("POST ERROR") urls.py urlpatterns = [ path('dashboard', views.dashboard_view, name='dashboard_view'), path('tables', views.case_view, name='case_view'), path('tables', views.pick_view, name='pick_case'), ] models.py class Transaction(models.Model): ### Case Progress Table Case_ID = models.ForeignKey(CaseTable, on_delete=models.CASCADE) Status = models.ForeignKey(Status, on_delete=models.CASCADE) Date_Time = models.DateTimeField(default=timezone.now) I tried the above code and i am able to retrieve the data from the HTML tags but not able to store in the Database. Please Help!! -
change attrs in a CheckboxSelectMultiple widget on every item with django form
I need to build a pre-filled field in a form that have CheckboxSelectMultiple widget. I thought to use different attrs={"checked":""} value on each id of the form filed. Is possible to loop on items? from django import forms from myapp.models import MyModel class MyForm(forms.Form): qs = MyModel.object.value_list("id","value") qsa = MyModel.object.value_list("id", "is_checked") myfield = forms.ModelMultipleChoiceField(queryset=qs, widget=form.CheckboxSelectMultiple) extrafield = forms.CherField(widget=forms.Textarea) def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) for id, is_checked in self.qsa: if is_checked is true: self.fields["myfield"].widget.attrs["checked"] = "" <form action="some_action"> <input type="checkbox" id="1" name="1" value="value_1"> <label for="value_1"> value_1</label><br> <input type="checkbox" id="2" name="2" value="value_2"> <label for="value_2"> value_2</label><br> <input type="checkbox" id="3" name="3" value="value_3"> <label for="value_3" checked="checked"> value_3</label><br><br> <input type="submit" value="Submit" > </form> -
How to stop the celery when the function finishes its task?
I created a countdown and I put this countdown in a context_processor file, the mission is that when someone creates an order this order has a time and every category has a different time to make that order so when if I created more than one category the time will be different in the countdown. the code worked for me but there's a problem which is sometimes the countdown works and when the time gets to "00:00:00" the countdown breaks (that is the target) and other sometimes when the countdown works and when the time gets to "00:00:00", the time repeat itself once again (which results in unexpected behavior). I'm trying to stop the celery worker by that condition but it didn't work for me: if _order_time == "00:00:00": # _order.update(in_progress=False) TODO self.expires = 0 in fact, I tracked what happens over there then I got the issue, so when the countdown works I shouldn't do any kind of request to get the expected time but if there are any requests happened even if it can be "back" or "forward" the unexpected behavior for countdown starts to appear. Note: when I start the celery worker I do the following command: … -
Get prevoius day total daily km in models property method
Hello Developers i am stuck in a problem , i want to get sum of daily km on models @property. so i can easily render data in templates. class Log(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) date_time = models.DateTimeField(default=timezone.now, blank=True, null=True) @property def daily_km(self): return Logsheet.objects.filter(log=self).aggregate(Sum('total_km'))['total_km__sum'] and related_name models is below class Logsheet(models.Model): log = models.ForeignKey(Log, on_delete=models.CASCADE, related_name="logsheets") driver = models.ForeignKey(Driver, on_delete=models.CASCADE, blank=True, null=True) trip = models.IntegerField(blank=False, null=False) distance_from = models.FloatField(blank=True, null=True, ) distance_to = models.FloatField(blank=True, null=True, ) time_from = models.TimeField(blank=False, null=False, default=timezone.now) time_to = models.TimeField(blank=False, null=False, default=timezone.now) source = models.CharField(max_length=100, blank=True, null=True) destination = models.CharField(max_length=100, blank=True, null=True) total_km = models.FloatField(blank=True, null=True,) and while i am successfully get sum of daily km on that day,i case of previous day sum of daily km is not calcutaed by me help me out. Thank You! -
the user created in the admin panel cannot log in to the admin panel
I have a custom user model: class CustomUser(AbstractUser): ACCESS_LEVELS = ( ('user', 'Авторизованный пользователь'), ('admin', 'Администратор') ) email = models.EmailField( max_length=254, unique=True, verbose_name='Эл. почта' ) access_level = models.CharField( max_length=150, choices=ACCESS_LEVELS, blank=True, default='user', verbose_name='Уровень доступа', ) @property def is_admin(self): return self.is_superuser or self.access_level == 'admin' class Meta: verbose_name = 'Пользователь' verbose_name_plural = 'Пользователи' def __str__(self): return ( f'email: {self.email}, ' f'access_level: {self.access_level}' ) Registered in the admin panel: @admin.register(CustomUser) class UserAdmin(admin.ModelAdmin): list_display = ('username', 'email', 'access_level') search_fields = ('email', 'access_level') list_filter = ('email',) def save_model(self, request, obj, form, change): if obj.is_admin: obj.is_staff = True obj.save() When I create a superuser or a user with staff status and try to log in, a message appears: Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. So I Googled the issue and tried everything I could. Here are all the problems I investigated: Database not synced: I synced it and nothing changed. No django_session table: I checked; it's there. Problematic settings: I just added the created apps to INSTALLED_APPS. User not configured correctly: is_staff, is_superuser, and is_active are all True. Old sessions: I checked the django_session table and it's empty. Missing or wrong URL pattern: … -
How to aggregate filtered listapiview queryset and return value once
How to perform aggregations on filtered querysets and return the value only once? My existing code below. In the serializer, of course PZ.objects.all() makes it aggregate all items. I don't know how to get the queryset from the serializer level. To make the total value appear once, it would be a good idea to add a field in the view. However, overriding def list(): makes the filtering stop working. I need this because I am working on a table that shows documents with filtering capabilities. In addition, there will be pagination. After selecting, for example, a creation date range, the values of the documents must be summed. View: class PZListAPIView(ListAPIView): queryset = PZ.objects.all() serializer_class = PZModelSerializer filterset_fields = { 'id': ['exact', 'in', 'contains', 'range'] } Serializer: class PZModelSerializer(serializers.ModelSerializer): net_value_sum = serializers.SerializerMethodField('get_net_value_sum') class Meta: model = PZ fields = '__all__' def get_net_value_sum(self, obj): return PZ.objects.aggregate(Sum('net_value'))['net_value__sum'] Response: [ { "id": 41, "net_value_sum": 28.0, "status": "C", "net_value": "6.00" }, { "id": 42, "net_value_sum": 28.0, "status": "S", "net_value": "10.00" } ] Desired response: [ "net_value_sum": 28.0, { "id": 41, "status": "C", "net_value": "6.00" }, { "id": 42, "status": "S", "net_value": "10.00" } ]