Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I use a string as the keyword in a values_list() statement?
I have an input variable and how can i assign it to value_list() options = "name, code" Model.objects.values_list(options) -
Django lock product read based on quantity
I'm new to Django been learning great stuff I'm stuck to one point. So I've been building a project like eCommerce, here each product has a certain quantity. I had made a custom API in ModelViewSet Here is my reference code def product(self, request): product_obj = Product.objects.filter(some_filter).first() product_resp = ProductSerializer(product_obj) return Response(product_resp, 200_ok**) So my issue is when a simultaneous call occurs, I saw people suggesting locks and approaches to update the count on right after gaining the instance how do we restrain a particular object/row to not appear in the simultaneous API call while lock/update on status is being carried out? Thank you in Advance! -
How to create a custom Pagination Class with page numbers?
I'm trying to create a custom pagination class. Here is my try: class CustomPagination(PageNumberPagination): page_item_count = 10 page = 1 def get_paginated_response(self, data): page = self.page next_page = None previous_page = None if page.has_next(): next_page = page.next_page_number() if page.has_previous(): previous_page = page.previous_page_number() return Response({ "page_count": page.count, "result_count": len(data), "next": next_page, "previous": previous_page, "has_next_page": page.has_next(), "has_previous_page": page.has_previous(), "result": data, }) This code is not properly working now and it's not what I want. I want give queryset parameter with query as page_item_count and page. I want to return something like that: return Response({ "page_count": page.count, # Page count. i.e. there are 100 items, and we show 10 per page, then it must be 10. "result_count": len(data), # object count. i.e. 100 "next": next_page, # Next page number. It's a number like 2,3,4,5... Not a link "previous": previous_page, # Prev page number, like 2,3,.... "has_next_page": page.has_next(), # boolean "has_previous_page": page.has_previous(), # boolean "result": data, # objects to be returned }) How can I achieve this? -
Python: Regex matching query, find matching digits inside the string
We have created an invoice numbering rule, in which the default pattern is AA-{num(x)}/{YYYY}. So let's say the first user which logged in didn't care about his pattern, and he started creating invoices. He has created few invoices and the last one that he managed to create had a numbering rule which is AB-003/2021. Everything seems cool and the back-end validation is pretty much working, but as I little did know the user is still able to make a custom pattern, for example, let's say that he can set the pattern to SZ{num(x)}. So let's say that the user wants to change the rule to this pattern and he starts using this SZ51 rule. The main problem is that our back-end server would eventually crash because we have only created a validation for this default AA-{num(x)}/{YYYY} pattern. As I spoke to one of our senior team lead back-end developers, he told me that we can start cutting the string from the right and loop every char and see if it is a digit or not. But if the user is able to set every pattern that he wants, that's a difficult thing to maintain. What if the user wants this … -
Django create/update multiple models in one rest request
I have a form in Vue which takes in data that is spread into multiple models when sent to django . Rest JSON is data = { people:{ name: "MyName", age: 34 }, classes:{ name:"Valgris", tag:3492, comment:"gob gdjoisu is tsutsi" } } -THE MODELS FIELD IN DJANGO ARE class Classes(models.Model): name = models.CharField(_ max_length=50) age = models.IntegerField() class People(models.Model): name = models.CharField(_ max_length=50) tag = models.IntegerField() comment= models.TextField() --- I tried tried using perform_create in my view, and also use create in serializer but I am unable to do it. request.data does not seem to like me popping out data and saving the result. It just doesn't work well. Is there a way out. or do I have to send two request to create People and Classes model -
Django modelcluster: When/How to invalidate cached_properties?
In a project of mine, I ran into an issue with a cached_property. Following is a minimal example reproducing this: # models.py from django.db import models from django.utils.functional import cached_property from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel class Author(ClusterableModel): name = models.CharField(max_length=100) @cached_property def fictional_books(self): return self.books.filter(fictional=True) class Book(models.Model): title = models.CharField(max_length=100) author = ParentalKey(Author, on_delete=models.CASCADE, related_name='books') fictional = models.BooleanField() def __str__(self): return self.title >>> from app.models import * >>> a = Author.objects.create(name='John Smith') >>> print(', '.join([ str(book) for book in a.fictional_books ])) >>> a.books.add(Book(title='My Fun Story', fictional=True)) >>> a.books.add(Book(title='My Real Story', fictional=False)) >>> print(', '.join(a.fictional_books)) >>> del a.fictional_books >>> print(', '.join([ str(book) for book in a.fictional_books ])) My Fun Story What can be seen here is the cached property fictional_books retaining its old value of an empty query set, because it was first accessed when there were no fictional books associated with that author. However, after adding books to that author, this is obviously not correct anymore, and once the cached result is deleted, we get the correct result. One obvious solution to this would be to avoid cached_property completely and to use property instead. However, as the access to that property might hit the database, it seems … -
Using Django signals (add data to model)
I'm trying to add data from one model to another using django signals , When an instance in my 'CartItem' model is created, I'm trying a calculation and add the result data to another model called 'Cart' and it's field called 'total. Not sure why the 'cart_receiver' signals not working ? models.py class CartItem(models.Model): item = models.ForeignKey(Product, blank=True, on_delete=models.CASCADE, null=True) items_cart = models.ForeignKey('Cart', blank=True, on_delete=models.CASCADE, null=True) quantity = models.IntegerField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return 'item:{} cart:{} quantity:{}'.format(self.item, self.items_cart, self.quantity) def cart_receiver(sender, instance, created, *args, **kwargs): if created: price = instance.item.price quantity = instance.quantity updated_total = int(quantity) * Decimal(price) Cart.objects.create(user=instance.items_cart,subtotal=updated_total,total=updated_total,updated=datetime.now()) post_save.connect(cart_receiver, sender=CartItem) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return 'id:{} user:{} subtotal:{} total:{} updated:{}'.format(self.id, self.user, self.subtotal, self.total, self.updated) objects = CartManager() -
Django and nginx do not accept PATCH requests, resulting in a 400 bad request error
I work on a Django project + django-rest-framework. On localhost, PATCH requests work perfectly fine. However, on server, PATCH requests do not work. I get a 400 Bad request error. I use nginx to configure the web server. Here is my configuration: server { listen 80; server_name x.y.z.com; root /var/www/path-to/project; location / { error_page 404 = 404; proxy_pass http://127.0.0.1:5555/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_intercept_errors on; } } I get this error when I try PATCH requests on server : How can I make so that django accept PATCH requests? The log does not show anything. As if it does not even receives the request. I run the django server like this: python manage.py runserver 5555 -
Wagtail i18n confusion
I've hooked up my site for internationalization as described here: https://docs.wagtail.io/en/stable/advanced_topics/i18n.html#enabling-locale-management My issue is, there doesn't seem to be anywhere that describes how the following works "It records which pages are translations of each other using a shared UUID stored in the translation_key field" Is this automatic? If so, how does it work out what is a translation of what? If not automatic, how do I set a page as a translation of another? -
Django - model in multiple apps (multiple tables)
I am trying to import a model from one app into another creating a new table etc. # app1/models.py class MyModel(models.Model): myfield = models.CharField(...) ... # app2/models/__init__.py from app1.models import MyModel as MyShadowModel What I would expect: python manage.py makemigrations would see changes in app2 and create the according tables. Why does it not happen? What would I have to do to achieve this? Background A Django project shall process Data and make changes visible. It consists of two apps: app1 contains already processed data app2 processes changes and shall show what data in app1 would look like. The idea: app2 processes the data into a "shadow" model. Therefore i would like to use the exact same model as app1 in my models in app2 -
Detailed Explanation On How To Setup Quotaguard on Django For Heroku
I have gone through the django documentation and quotaguard documentation, but my application still does respond after I put the IP addresses on block.io. I would like a detailed guide on how to setup quotaguard on heroku -
Channels doesn't run wsgi file in testing
In this asgi file I am using the tokens to return the users, and that works very fine. But in testing Django act like this asgi file not exists att all despite I already set it in the settings.py. When I go the the consumers and try print(scope.get('user')) I got null, but when I run the same print in the normal ws link in the front end I got the user printed correctly #asgi.py from urllib.parse import parse_qs from channels.db import database_sync_to_async from channels.routing import ProtocolTypeRouter, URLRouter from django.contrib.auth.models import AnonymousUser from django.core.asgi import get_asgi_application # from jwt import decode from rest_framework_simplejwt.tokens import UntypedToken from Alerts.routing import websocket_urlpatterns from Functions.debuging import Debugging from users.models import User @database_sync_to_async def get_user(querys): token = parse_qs(querys.decode("utf8"))['token'][0] token_data = UntypedToken(token) user_id = token_data["user_id"] try: return User.objects.get(id=user_id) except User.DoesNotExist: return AnonymousUser() class QueryAuthMiddleware: def __init__(self, app): # Store the ASGI application we were passed self.app = app async def __call__(self, scope, receive, send): print(scope) #<==🔴 scope['user'] = await get_user(scope["query_string"]) return await self.app(scope, receive, send) application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": QueryAuthMiddleware( URLRouter( websocket_urlpatterns ) ), }) when I run WebSocket in the front end and it connects I got the code line print(scope) #<==🔴 runs correctly. … -
Django pass a list of values in update query
I have a Django query like this: object = BPMap.objects.filter(name = 'ABC', color = 'RED').values('quantity') Say the output returned from the above query is <QuerySet [100, 200, 300]> Now I want to use update on the above queryset but pass a different list of values such as [150, 250, 350] I want a query which is similar to the below: BPMap.objects.filter(name = 'ABC', color = 'RED').update('quantity', [150, 250, 350]) I know the above query is wrong. Please guide me how to do it. Thanks in advance. Sorry if its trivial, I new to Django. -
Best way of building middleware for intercepting requests in Django-Vuejs project
I'm working on a Django-Vuejs based project. In my project, a user can have a folder. Inside that, he can create multiple files. Let say, user restricted users from India to access that folder. This folder restriction will now be followed in files as well. But, user can override these settings on file level i.e., user can change restrict settings for single file. So that, if one folder has 5 files. Folder is restricting India and now only one file allowing India. That means, one file will allow India, rest four will restrict India. My question here is how my middleware should be designed for these settings? Should I create interceptors in Vuejs and define middleware for each route /folder/1 and /file/1 or create custom middleware in Django and check for the requested path in request and accordingly check for the access settings? What's the best way to achieve this? I've tried with rest_framework Permissions on folder level. It's working perfectly if the settings are only on folder level. But if settings get changed on file level, it still checks for folder permission and send response accordingly (since file is inside the folder). -
Apply function to all string variables in Django template
Is it possible to apply some function to all string variable in a Django template? Just like escape is applied unless safe filter is specified. Thanks in advance. -
nginx server: [emerg] still could not bind ()
I hosted my django application on an ec2 instance using ubuntu machine with nginx server, everything worked I could type http://www.adress-aws-monapp.com to access my application with the public address aws offered me. After use I turned off the machine and when I booted again to use it on http://www.adress-aws-monapp.com instead of showing me my app it shows me the nginx home page . This means that I have to resume the configuration so that my application is available again (when I type http://www.adress-aws-monapp.com) but after several attempts to restart my nginx server I get no satisfying result. I need your help please! I try to restart the server but at this level I get this error [1]: https://i.stack.imgur.com/S12ao.png -
The best web framework for dynamic webpage [closed]
What is the best web framework for dynamic webpage? I have tried Django but it is not good to handle multiple requests at a time. -
django validate answers to math tasks
I want to write a website that gives elementary math tasks to its visitors, quite similar to this: Javascript - Hidden maths answer. In contrast to the JS example my idea is for the visitor to finish all tasks first, then press a button "check answers" and have all answers marked with a smiley if answer is right or the correct result if visitor's answer is wrong. To this - if I'm right - it's necessary to redirect the visitor's answers and the task-list to a different view. Also I want to use Django templates and CBviews. I have this view for setting up the math tasks - view.py: class Plus_im_10erPageView(TemplateView): form_class = ResultForm template_name = 'plus_im_10er.html' success_html = 'plus_im_10er_check.html' def tasks(self): task_list = [] for i in range(10): while True: x = random.randint(0, 9) y = random.randint(0, 9) z = x + y if z <= 10: task_list.append((x, y, z)) break return task_list def get_context_data(self, **kwargs): context = super(Plus_im_10erPageView, self).get_context_data(**kwargs) task_list = self.tasks() context['tasks'] = task_list self.context = context return context The ResultForm is a simple IntegerField like this - forms.py: class ResultForm(forms.Form): result = forms.IntegerField(label='answer') Next is the template - plus_im_10er.html: {% extends 'base.html' %} {% block content … -
How to display a visitor's IP address by ipware app?
I want to get the user's IP address when he visits my site, I found many solutions but I picked one of them which is: ipware application that I installed it but when I used it the result returned: 127.0.0.1 which is localhost not the IP of my device my experience using IP is weak but I understand a little bit why it returned that result I think that because I'm on the localhost so, it uses a private IP as I thought so if that answer is correct How could I try to print the user's IP of the anonymous user before I upload the website on production to show the expected result and sure that everything ok now? from ipware import get_client_ip print(get_client_ip(request)) -
Uncaught TypeError: Cannot set property 'value' of null in django
I am trying to change django's form field in a javascript file. But I can not do that because django's form field is null. However, the following django's form fields have an initial value of 181. This is my django's form: class userRequest(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) lat_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lat_Origin"}),required=False,initial=181) lon_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lon_Origin"}),required=False,initial=181) lat_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lat_Dest"}),required=False,initial=181) lon_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lon_Dest"}),required=False,initial=181) This is my view: def home(request): blablaTrips={} skyscannerTrips={} trips_busTrain={} if request.method == 'POST': form = userRequest(request.POST) print(request.POST) if form.is_valid(): #print(form.cleaned_data) id_delete=set() for trip in Trip.objects.all(): if (hasattr(trip,"busOrTrainTrip")==False): id_delete.add(trip.id) Trip.objects.all().filter(id__in=id_delete).delete() #Borro los viajes en avión y en blablacar date=form.cleaned_data['date'] start_date_local=dt(date.year,date.month,date.day) start_coordinates=str(form.cleaned_data['lat_Origin'])+','+str(form.cleaned_data['lon_Origin']) end_coordinates=str(form.cleaned_data['lat_Dest'])+','+str(form.cleaned_data['lon_Dest']) else: form = userRequest() try: busTrips=trips_busTrain.filter(busOrTrainTrip__system='B') except: busTrips={} try: trainTrips=trips_busTrain.filter(busOrTrainTrip__system='T') except: trainTrips={} ''' blablaTrips,skyscannerTrips,busTrips,trainTrips => Pertenecen al modelo Trip ''' context = {'form' : form,'blablaTrips':blablaTrips,'skyscannerTrips':skyscannerTrips,'busTrips':busTrips,'trainTrips':trainTrips} return render(request,'app/home.html',context=context) And it is what I am trying to do in JS file (lat and lng are number atributes). It gives me an error: Uncaught TypeError: Cannot set property 'value' of null I don't know what's wrong. if (is_origin) { document.getElementById('origin_address').value = results[0].formatted_address; console.log(lat); console.log(lng); document.getElementById("lat_Origin").value = lat; document.getElementById("lon_Origin").value = lng; remove_mapMarkers('origin_address', marker) } else { console.log(lat); console.log(lng); document.getElementById('destination_address').value = results[0].formatted_address; document.getElementById("lat_Dest").value = lat; document.getElementById("lon_Dest").value = lng; remove_mapMarkers('destination_address', marker); } -
DataTable not working with Bootstrap 4 in Django
I am new to DJango but have experience with Python. I am creating a Notes Sharing Site. Idea is users will upload notes, admin will accept it and only accepted notes are public. The user can see all of its notes including the pending and rejected ones. Problem: Admin is able to see all the users. I am heavily using bootstrap for design because I am trying to focus on back-end. I am using bootstrap tables of viewing the users and viewing the notes ( viewing notes works perfectly because I am not using data table in that table ). Real problem is in viewing users ( by admin ), normal bootstrap table is working perfectly but it is not being modified by data-table. I have not used data able in past it is my first time. HTML code: view_users.html {% extends 'admin_core.html' %} {% load static %} {% block head %} <style> td { text-transform: capitalize; } </style> <scirpt type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></scirpt> <scirpt type="text/javascript" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></scirpt> <scirpt type="text/javascript" src="https://cdn.datatables.net/1.10.25/js/dataTables.bootstrap4.min.js"></scirpt> <link rel="stylesheet" href="cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css"> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.25/css/dataTables.bootstrap4.min.css"> <script> $(document).ready(function() { $('#user-table').DataTable(); }); </script> {% endblock head %} {% block body %} <div class="container"> <h2 class="text-center my-4">Users</h2> <div class="table-responsive"> <table class="table table-bordered md-2" id="user-table"> … -
How to get an input in views without post button? [closed]
I want to get a value in my views. So, I create a form and put a hidden field for taking the value. But I should get this value without the post button. When I click approve-btn, Is it possible to save the above form using javascript? How can I get this value in my views? template.html {% for waiting in assign_list_yellow %} <li class="list-group-item list-group-item-warning"> {{ waiting.rank.rank_name }} Approval {% if forloop.counter == 1 %} {% if waiting.rank.rank_name == 'Senior Analyst' or waiting.rank.rank_name == 'Analyst' or waiting.rank.rank_name == 'Lead' or waiting.rank.rank_name == 'Manager' %} {% else %} {% if approval_documents_regman.rank == waiting.rank.rank_name %} <form id="rank-form"> {% csrf_token %} <input type="hidden" name="rank_name" value="{{ waiting.rank.rank_name }}" /> </form> <a href="{% url 'approvals:approval_details' approval_processes.id %}#attachments" target="_blank"> <button class="btn btn-primary btn-xs" id="approve-btn" >View Attachment</button>&nbsp;&nbsp; </a> views.py def approve_pending(request, pk): # print(request.POST['rank_name']) ... -
django path is not recognizing its intended view
code: urls.py path('tools/<int:rate>/', ToolsView.as_view(), name="get-all-tools"), path('tools/post/', ToolsView.as_view(), name="save-tool"), code: views.py class ToolsView(APIView): def get(self, request, rate): objs = ToolsModel.objects.values_list()[:rate] if objs is None: return Response(status=status.HTTP_404_NOT_FOUND) data = [] for obj in objs: print(obj) json = {} json['toolid'] = obj[0] json['tool_name'] = obj[1] json['tool_from'] = obj[2] json['tool_qty'] = obj[3] json['tool_state'] = obj[4] data.append(json) return Response(data=data, status=status.HTTP_200_OK) def post(self, request): data = request.data serialize = ToolsSerializer(data=data) if serialize.is_valid(): serialize.save() return Response(status=status.HTTP_201_CREATED) return Response(status=status.HTTP_404_NOT_FOUND) Whenever i call for tools/post/ intended to call post method http://127.0.0.1:8000/help/tools/post/ i get get() missing 1 required positional argument: 'rate' but rate parameter is actually needed for 'tools/<int:rate>/' which invokes my get method ,example, http://127.0.0.1:8000/help/tools/5/ Needed help with these. Thanks in advance! -
How to create OneToMany relationship?
I have model class Meeting(models.Model): name = models.CharField(max_length = 255) How create model GroupMeeting witch can be connected with many meetings and one meeting can have only one GroupMeeting class GroupEntryControl ( models . Model ): meeting = models . ForeignKey ( Meeting , on_delete = models.SET_NULL group_id = models . IntegerField () name = models . CharField ( max_length = 255 ) in this case I have opposite situation many GroupEntryControl have one Meeting How to do it without changing Meeting class !! -
Count field choices in a model?
Im new to django and Im helping in creating a website, now what they've requested is to show a specific number and Im trying to use a for loop it goes something like this: class Students(models.Model): ... section = (('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6')) BlockNumber = models.CharField(max_length=10, choices=section) now what I want to do is to count each section choice in the Students model class. I've tried using the code below to count each choice: def yearCount(request): year = Students.objects.all(Count('year')) blocks = Students.onjects.all(Count('section')) context = {'year': year,'blocks': blocks} return render(request, './chairperson/students/student_bsit1.html', context) Any help would be appreciated, thank you.