Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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" } ] -
How to format DurationField input as min:sec:millisec Django
I want to force users to input lap times into a Form using the format min:sec:millisec (e.g. 00:00:000). I also want to display these times in this format in a DetailView but I want to store them as milliseconds to calculate personal bests and lap differences. I have tried to set the default DurationField value as 01:01:001 but it displays in the format HH:MM:SS.MS Here is my model: class SwimTime(models.Model): swimmer =models.ForeignKey(Swimmer, on_delete=models.CASCADE) time = models.DurationField(_('Time'), default= timedelta(minutes=1, seconds=1, milliseconds=1)) distance = models.PositiveIntegerField(_('Distance'),null = False, default=50) strokeType = models.CharField(_('Stroke Type'),max_length=20, choices=strokeTypes, default='FC') date = models.DateField(_('Date Recorded'),default = timezone.now) def save(self, *args, **kwargs): self.full_clean() return super().save(*args, **kwargs) -
Adding custom godaddy domain to railway web app
I deployed my web app on Railway. They gave the following settings: I went to GoDaddy where I bought a custom domain - and it was impossible to enter @ as Name. I called support - their representative entered the following settings himself. But it still doesn't work, 72 hours have passed. How should I resolve this? -
Django Form : cleaned_data.get(field name) is returning None in clean() method
I am following the Django documentation of Django form but unable to understand what is the issue in my code. I am writing the below code in the clean method to check if both name and email starts with lowercase s or not but Django is returning None in cleaned_data.get(field name) method and I am getting "Attribute error" : 'NoneType' object has no attribute 'startswith'. Please help me on this: Reference: https://docs.djangoproject.com/en/4.1/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other from django import forms from django.core.exceptions import ValidationError class GirlsFeedback(forms.Form): name = forms.CharField(label = 'Enter Your Name', label_suffix = " ", required=True, disabled=False, min_length = 5, max_length = 100, strip=True) password = forms.CharField(label='Enter Your Password', label_suffix = " ", required=True, disabled=False, min_length=8, max_length=10, help_text="Minimum 8 and Maximum 10 characters are allowed.", widget=forms.PasswordInput) email = forms.EmailField(error_messages={'required': 'Email is mandatory'}) def clean(self): cleaned_data = super().clean() name = cleaned_data.get('name') email = cleaned_data.get('email') if name.startswith('s') and email.startswith('s') !=True: raise ValidationError('Name and email both should start with a lowercase s') Error: AttributeError at /feedback3/ 'NoneType' object has no attribute 'startswith' Request Method: POST Request URL: http://localhost:8000/feedback3/ Django Version: 4.1.2 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'startswith' Exception Location: C:\Users\singh\Desktop\Journey\Django Journey\Geeky Shows\Eleven\Feedback3\forms.py, line 72, in clean Raised during: Feedback3.views.feedback Python … -
Django TestCase using self.client.post() is sending a GET resquest
I'm creating a integration Test Class. The self.client.get is working fine, but self.client.post is sending GET and I'm receiving a [httpResponse("Method Not Allowed", 405)]. from django.test import TestCase import json class Test_Integration(TestCase): def test_create_exist_product(self): response = self.client.post('http://127.0.0.1:8201/v1/products/create', {"name": "product7", "latest_version": "0"}, follow=True, secure=False) print(response) self.assertEqual(response, "Product name already exists") Function def create_product(request): logger.info("Entering function create_product..") logger.info("REQUEST TYPE: "+str(request.method)) if request.method == "POST": CODE HERE return HttpResponse("Method Not Allowed", 405) Log errors: Found 4 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). INFO 2022-11-16 13:45:12,066 views 13612 19052 Entering function create_product.. INFO 2022-11-16 13:45:12,068 views 13612 19052 REQUEST TYPE: GET <HttpResponse status_code=200, "405"> ====================================================================== FAIL: test_create_exist_product (project.Tests.test_integration.Test_Integration) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\backend\project\Tests\test_integration.py", line 23, in test_create_exist_product self.assertEqual(response, "Product name already exists") AssertionError: <HttpResponse status_code=200, "405"> != 'Product name already exists' ---------------------------------------------------------------------- Ran 4 tests in 6.523s FAILED (failures=1) Destroying test database for alias 'default'... -
How can I display total likes received to an user to his post on django
I want to display total likes received to an user to his posts on django and display it by monthly basis def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["views"] = posts.objects.filter(likes=self.request.user) return context -
Create a new record using another for default values
What would be the best way to implement a feature whereby a user selects an existing record as a template for the creation of a new one? Ideally I'd like a list of all existing records in a ListView and the user clicks on one of these records and is taken to a CreateView whereby the fields are populated with the selected record's values as new default, starting values. Would this method essentially be a standard ListView-to-UpdateView however the save method would instead create a new record instead of updating? -
How to get the data from a post request using Django Python Templates
I have two projects, the first one is Node.JS. jsonobj = JSON.stringify(generateMockData) xhrToSoftware.send(jsonobj); xhrToAPI.open("POST", "http://127.0.0.1:8000/path/", true); xhrToAPI.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhrToAPI.send(jsonobj); It's sending data to the second project Django Python. I can receive the data using my views.py. post_data = json.loads(request.body.decode("utf-8")) value = post_data.get('data') print(value) But I want to directly get the data from Node.JS to my Django Templates (javascript or jquery) is that possible? for example: <script> //get the data that posted by the node.js </script> I tried using this one: fetch('http://127.0.0.1:8000/path/') .then(response => response.json()) .then(data => { console.log(data); }) .catch(error => console.error(error)); but I'm having an error it says that: SyntaxError: Unexpected token '<', "<!-- <d"... is not valid JSON I think that's because I'm returning an html file in my views.py: def data(request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) # for simulation value = post_data.get('data') return render(request, 'waterplant/iot/data.html') so, I change it to jsonresponse like this: def data(request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) # for simulation value = post_data.get('data') return JsonResponse({"msg": value}, status=200) After that I'm having an error ValueError: The view views.data didn't return an HttpResponse object. It returned None instead. I think that's because the value is empty yet. How can I prevent that? … -
one upload function for pdf and a second upload function for excel
I have a template with two upload functionaliteis: one for pdf and one for excel. And I have two texareas for showing the data from the uploaded file: one textarea for data from the pdf and one texarea for the data from excel But my problem now is, how to combine this two in the views.py? So this is how the template looks: {% extends 'base.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <link rel="stylesheet" type="text/css" href="{% static 'main/css/custom-style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'main/css/bootstrap.css' %}" /> </head> <body> <div class="container center"> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" > <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-warning">Upload!</button> </div> </form> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" cols="70" rows="25"> {{content}}</textarea > </div> </div> </div> </form> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" > <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-warning">Upload!</button> </div> </form> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" cols="65" rows="25"> {{content_excel}}</textarea > </div> </div> </div> </form> </div> </body> </html> {% endblock content … -
How to overwrite a default value in Views
I have several views which use the same model and template due to the need for unique urls. Each view needs to set its own unique default values for several of the model's fields. For example in View 1, the models' field titled 'name' should have a default value of 'Name for a View 1 item', likewise 'Name for a View 2 item' under View 2 etc. How would I specify / overwrite a default value for a field in a view? -
SQL User History Table, Get last updated SPECIFIC FIELD
I have such a user_history table. Every time my users table is updated, records are dropped here as well. How can I get the date when my user updated his last salary information, that is, 2.01.2022 with SQL? I need to get the date it went from 200 to 300 (money field),so "2.01.2022" I need to do this with DJANGO ORM but I couldn't even do more normal SQL query. I tried to use sql lag,lead methods, but I could not succeed. -
My AWS pipeline keeps on failing, but not sure why one of the instances fails there?
My set up is : - Elastic Beanstalk Env - GitHub - S3 Bucket (for storage of static-files) The source stage is fine but thank it fails. ERROR: Latest action execution message Deployment completed, but with errors: During an aborted deployment, some instances may have deployed the new application version. To ensure all instances are running the same version, re-deploy the appropriate application version. Failed to deploy application. Unsuccessful command execution on instance id(s) 'i-08ec1ec805e434ba5'. Aborting the operation. [Instance: i-08ec1ec805e434ba5] Command failed on instance. Return code: 1 Output: Engine execution has encountered an error.. Instance deployment failed. For details, see 'eb-engine.log'. -
How to display items on html table from django model base on its category
I have items in a Stock model and each item has a category that it belongs to. I want to show it in HTML tabular form like this, part no desc bal b/d etc CATEGORY1 1 item1 55 2 item2 69 3 item3 33 CATEGORY2 4 item4 54 5 item5 77 CATEGORY3 6 item6 55 7 item7 99 and so on... I want it to iterate through the Stock model, find the distinct category, display the items that relate to that category, and display the category name as a caption above the related items. model.py class Stock(models.Model): user = models.ForeignKey(User, on_delete = models.SET_NULL, null = True) part_No = models.CharField(max_length=100, null=True) item_name = models.CharField(max_length=100, null=True) category = models.CharField(max_length=100, null=True) unit = models.CharField(max_length=50, null=True) balance_bd = models.IntegerField(default='0', null = True) received = models.IntegerField(default='0', null = True) issued = models.IntegerField(default='0', null=True) unit_price = models.DecimalField(max_digits=20, decimal_places=2, null=True) obsolete = models.BooleanField(default=False, null=True) views.py def stock(request): stocks = Stock.objects.all() context = { 'stocks':stocks, } return render(request, 'base/stock.html', context) html template <!-- DATA TABLE--> <div class="table-responsive m-b-40"> <table class="table table-borderless table-data3"> <thead> <tr class="bg-primary"> <th>NO</th> <th>PART NO</th> <th>DESCRIPTION</th> <th>CATEGORY</th> <th>UNIT</th> <th>BALANCE B/D</th> <th>RECEIVED</th> <th>TOTAL BAL</th> <th>ISSUED</th> <th>TALLY CARD BAL</th> <th>UNIT PRICE</th> <th>TOTAL PRICE</th> <th>ACTION</th> </tr> </thead> <tbody> … -
how to set query for show followed posts in home page
its my models.py ` class Relation(models.Model): from_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower') to_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following') created = models.DateTimeField(auto_now_add=True) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') avatar = models.FileField(default='default.jpg', verbose_name='avatar') age = models.PositiveSmallIntegerField(default=0) location = models.CharField(max_length=30, blank=True) work_at = models.TextField(null=True, blank=True) bio = models.TextField(null=True, blank=True) ` i want to make query to show all followd posts in main page make query for show followed posts in home page? -
how to apply distinct and group by in django or in postgres?
table production code part qty process_id 1 21 10 10 1 22 12 10 2 22 15 10 1 21 10 12 1 22 12 12 how to get data like this in postgresql or in django process_id qty 10 27 12 12 I tried in this way Production.objects.filter(q).values('process').distinct('code').annotate(total_qty=Sum('quantity')) -
Django querry set
I would like to have an example of a dango query that allows you to select elements contained in two different tables in a database in a single query I would like to have an example of a dango query that allows you to select elements contained in two different tables in a database in a single query -
Django-filter custom filter for custom field
I am using django-filter package to filter my queryset. However, for one of the fields I need to receive input similar to MultipleChoiceFilter but without using a fixed list of choices. For example: STATUS_CHOICES = ( (0, "Regular"), (1, "Manager"), (2, "Admin"), (3, "Staff"), ) class SomeFilter(django_filters.FilterSet): mychoices = django_filters.MultipleChoiceFilter( choices=STATUS_CHOICES, method="get_some_data" ) def get_some_data(self, queryset, field_name, value): print(value) # ['1','2','3'] class Meta: model = SomeModel when I use MultipleChoiceFilter, the URL looks like myurl/path/?mychoices=1&mychoices=2&mychoices=3 and then I receive these input values as a list e.g. ['1', '2', '3'] However, I need to create new filter field, say, openlistchoices where I can send a url request url/path/?ch=something1&ch=something2&ch=1234&ch=abc234 and still be able to have values as a list. Basically I want to create a filter for one of the fields where I have full control of what's being input. I'll sanitise and whitelist what's being received. -
Django Get Last Object for each Value in List
I have a model called Purchase, with two fields, User and amount_spent. This is models.py: class Purchase(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) amount_spent = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) I want to get the last purchases from a list of users. On views.py I have a list with some User's objects, and I want to get the last purchase for each user in the list. I can't find a way of doing this in a single query, I checked the latest() operator on QuerySets, but it only returns one object. This is views.py: purchases = Purchase.objects.filter(user__in=list_of_users) # purchases contains all the purchases from users, now I need to get the most recent onces for each user. I now I could group the purchases by user and then get the most recent ones, but I was wondering it there is a way of making this as a single query to DB. -
How to auto insert slashes in expiry date fields into django forms input
I want to insert a slash after 2 digit press like the same mechanism of MM/YY through Django forms input. The following has my code that is not working well. Models.py from django.db import models from creditcards.models import CardExpiryField class MyUser(models.Model): cc_expiry = CardExpiryField('expiration date', null=True) def __str__(self): return self.cc_expiry forms.py from django import forms from .models import MyUser from django.forms import TextInput class MyUserForm(forms.ModelForm): class Meta: model = MyUser fields = ('cc_expiry') widgets = { 'cc_expiry': TextInput(attrs={'placeholder': 'MM/YY'}), } views.py def cc_page(request): form = MyUserForm(request.POST or None) context = { "form": form } if form.is_valid(): form.save() return render(request, 'cc_thanks.html') return render(request, 'index.html', context) index.html {% load static %} {% load widget_tweaks %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="regForm" method="post" action=" "> {% csrf_token %} <div class="tab"> {{ form.cc_expiry.errors }} <p>{{ form.cc_expiry|add_class:"form-control" }}</p> </div> </form> </body> </html> In the following has the simple HTML JS code for the automatic insert slash after 2 digit press and it's working fine. And the similar result I expected. <input maxlength='5' placeholder="MM/YY" type="text" onkeyup="formatString(event);"> <script type="text/javascript"> function formatString(e) { var inputChar = String.fromCharCode(event.keyCode); var code = event.keyCode; var allowedKeys = [8]; if (allowedKeys.indexOf(code) !== -1) { return; } … -
can we run console command by django function
I want to run this command with the help of django function can we do this? python manage.py rebuild_index i want this when post_save function run how i can do this? -
How to upload document on an Article using article id when it does not even exists
currently i am in a very weird situation. I am trying to upload document using article id and user id to an article. But the issue is when I try to select article id from the document model, it gives error that article doesnt exists. And tbh that is true, because how can i upload document to an article when it doesnt even exists. So how can i use article id in such situation? Below is my document model in which i am sending user id and article id for uploading document. documentmodels.py class DocumentModel(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="DOCUMENT_ID") user_fk_doc=models.ForeignKey(User, on_delete=models.CASCADE, related_name="users_fk_doc") article_fk_doc=models.ForeignKey(Article, on_delete=models.CASCADE, related_name="articles_fk_doc") document=models.FileField(max_length=350, validators=[FileExtensionValidator(extensions)], upload_to=uploaded_files) filename=models.CharField(max_length=100, blank=True) filesize=models.IntegerField(default=0, blank=True) mimetype=models.CharField(max_length=100, blank=True) created_at=models.DateField(auto_now_add=True) and below is the articles models, class Article(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="ARTICLE_ID") headline=models.CharField(max_length=250) abstract=models.TextField(max_length=1500, blank=True) content=models.TextField(max_length=10000, blank=True) published=models.DateTimeField(auto_now_add=True) tags=models.ManyToManyField('Tags', related_name='tags', blank=True) isDraft=models.BooleanField(blank=True, default=False) isFavourite=models.ManyToManyField(User, related_name="favourite", blank=True) created_by=models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="articles") -
Django Admin Limit Model list
i have this models in my project: ` class Luce(models.Model): appartamento = models.ForeignKey('Appartamento', on_delete=models.CASCADE, related_name="bollette") numero = models.IntegerField() data = models.DateField() dal = models.DateField() al = models.DateField() importo = models.FloatField() file = models.FileField(upload_to='fatture/%Y/%m/%d') def __str__(self): return "Fattura Luce dal " + str(self.dal.strftime('%d/%m/%Y')) + " al " + str(self.al.strftime('%d/%m/%Y')) def file_link(self): if self.file: return format_html("<a href='%s'>Scarica</a>" % (self.file.url,)) else: return "No allegato" file_link.allow_tags = True class Meta: verbose_name = "Luce" verbose_name_plural = "Luce" class Appartamento(models.Model): nome = models.CharField(max_length=50) camere = models.IntegerField() class Meta: verbose_name = "Appartamento" verbose_name_plural = "Appartamenti" def __str__(self): return self.nome ` What i would do is to limit the visibility of model "Luce" in the way some users ( staff user ) can access only to their "Appartamento" My admin.py is this one: ` class LuceAdmin(admin.ModelAdmin): list_display = ('data', 'dal', 'al', 'importo', 'file_link') search_fields = ['data', 'dal', 'al'] list_filter = ('appartamento',) admin.site.register(Luce, LuceAdmin) class AppartamentoAdmin(admin.ModelAdmin): list_display = ('nome', 'camere') admin.site.register(Appartamento, AppartamentoAdmin) ` What ca i do ? I mean some staff user has limited access only to objects of type "Luce" assigned to one specific category "Appartamento". THanks -
Server Error (500) - rendering lists in django
I am getting a Server Error (500) when i'm trying to render a list to one of my web pages in Django. def find_jobs(request): job_details = [job_position for job_position in JobPost.objects.all() if job_position.Status is not JobPostStatus.Closed] Seeker_applied_job = seeker_applied_job() print(job_details) content = {'title': "Job seekers", 'jobs': job_details, 'message': "to view job postings", } print(content) return render(request, 'seek_job.html', content) the print(job_details) line returns this [<JobPost: Opportunist at OpportunityM>, <JobPost: Digital Marketer at OpportunityM>, <JobPost: Nurse at NHS>] When I remove 'jobs': job_details from content, the seek_job.html page renders. But when I try adding it back, it returns a Server Error (500) page. I have another view function similar to this one which works fine.