Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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" } ] -
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; } …