Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
list action with modal(not intermidiate page) to update model with input value
I want to update a list of model with input values but using modal instead of intermediate page, I googled a lot but I don't find any help, can someone give me some helps ? -
QR Application in Python
I want to create Django application. The logic is next: I scan the QR-code using QR- scanner, and then send this code to the web app. After that the app connect with Data Base and regarding to this information display some information. Could you give advice how to start this project, maybe some examples? i don't understand how looks the process of sending qr code from Qr scanner to app. -
Google Cloud Run + Django + RabbitMQ (or another message broker)
I have a contenerized Django application, which I deployed on Google Cloud Run. For the most time no requests are made to the app, so GCP can reduce it to 0 instances (and the billing is small). Some requests provide time consuming tasks and I need to handover them to another service by RabbitMQ (or possibly another message broker). I wanted to use pika at the Django app side, but if I understand correctly it forces it to be running all the time. So is there a solution, where I can pass messages to message broker from Django app and also listen to message queue, but the app can reduce to 0 instances when the queue is empty (and increase instances if it's not)? Thanks -
Date filter binned data
I have a model in django that contains a start and end date for a financial year and a value for demand volume. start_date = models.DateField(null=True) end_date = models.DateField(null=True) new_demand = models.PositiveIntegerField(default=0) I would like to filter this data on a given date range that may not coincide with the date ranges of the data, taking a proportion of the demand from each data point that may fall somewhere in the filter date range. I am assuming I need to work out if the data point falls over the edge of the filter and divide the demand by the number of days inside the filter? But I am having a hard time trying to write this. any help would be appreciated! :) -
How to count my checkboxes and insert to my vizualization of my table?
I have a problem that looks really simple to solve but I can't find the solution. I have in my django model a field nb_engins corresponding to an integerfield, my model is of this type : models.py class Flottes(models.Model): name = models.CharField(max_length=255, null=True) nb_engins = models.IntegerField(validators=[MaxValueValidator(9999999999)], default=0) engins = ArrayField(models.CharField(max_length=555, blank=True), null=True) calculateur = models.CharField(max_length=555, null=True) type_fichier = models.CharField(max_length=255, null=True) created_at = models.DateTimeField(auto_now_add=True, null=datetime.date.today) Here are now my 2 functions, one is used to retrieve the selected checkboxes and the other to validate my form component.ts // Get List of Checked Items getCheckedItemList(){ this.checkedList = []; this.count = 0; for (var i = 0; i < this.engins.length; i++) { if(this.engins[i].isSelected) this.count = this.count+1; this.checkedList.push(this.engins[i]); } this.checkedList = JSON.stringify(this.checkedList); } submitForm(): void { const { value } = this.form; // get selected fruit from FormGroup value const selectedEngin = value?.engins?.filter((f: Engins) => f.checked) || []; // form value binded console.log('current form value: ', value); console.log('only selected form value: ', selectedEngin); // original value from database not change console.log('original engins list: ', this.engins); this.result = { name: value?.name || '', selectedEngin, nb_engins: value?.checkedList|| '', calculateur: value?.calculateur || '', type_fichier: value?.type_fichier|| '', } alert('La flotte a été enregistré avec succès !'); this.api.registerFlotte(this.form.value) .subscribe((res:any)=>{console.log(res)}); … -
Infinity loop when i override the get() method in a class based view django
I want to override the get method. But I get the error : The view auctions.views.AuctionsDetail didn't return an HttpResponse object. It returned None instead. If I use a httpresponse I reload the function and call the function again. How can solve this? Its a detail view ''' def get(self, request, *args, **kwargs): list_auction = self.kwargs['pk'] set_current_bid=Bids.objects.filter(listing_auctions__id = list_auction).latest('id') print(f'offer {set_current_bid.offer}') return HttpResponseRedirect(reverse('auctions_detail', args=(list_auction,))) ''' -
Django quick quest on making queries for blog posts and categories
I have a blog page showing all the user's posts. Each post has a 'Category'. (Ex: Post 1 --> category: general coding, Post 2 --> category: general coding, Post 3 --> category: web dev) If I wanted to show all the categories that the user posted in (Ex: User profile page listview--> Categories posted --> general coding, web dev ) , would I have to use a 'for loop' and put them in a list? Or is there a better way to do this. posts = user.post_set.all() category_list = [] for post in posts: if post.category not in category_list: category_list.append(post.category) models.py class Category(models.Model): category_name = models.CharField(max_length=50, default='general coding', verbose_name="Categories") class Post(models.Model): title = models.CharField(max_length=100, help_text="100 characters or less") content = models.TextField() category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) liked = models.ManyToManyField(Profile, blank=True, related_name='likes') -
Django model constraint for ensuring one or both fields are not empty strings
Following this answer I want to set up a constraint on a Django model that ensures one or both of two fields are set. However, while that answer assumes the empty fields are NULL, in my case they are always empty strings. I'm not sure how to check for that in the constraint. from django.db import models from django.db.models import Q class Person(models.Model): firstname = models.CharField(max_length=150, blank=True, null=False, default="") surname = models.CharField(max_length=150, blank=True, null=False, default="") class Meta: constraints = [ models.CheckConstraint( name="%(app_label)s_%(class)s_firstname_and_or_surname", check=( Q(firstname__exact="", surname__exact!="") | Q(firstname__exact!="", surname__exact="") | Q(firstname__exact!="", surname__exact!="") ), ) ] This should work except that, unlike surname_isnull=False, surname__exact!="" isn't valid syntax. I know that if I had a queryset I could use exclude(surname__exact="") to mean "is not empty", but I'm not sure how to do that in this constraint with Q() expressions. -
how safe is it to use post requests through ajax?
I'm making inventory control applications in django. All data from the database is taken through ajax and api, that is, get, post and put requests. I use django view only to display html templates I need advice on how safe it is to use code like this: function iterTable() { let items = []; let docDate; let docContragent; let docWare; let comment; let table = document.querySelector(".invoice-add-table table"); for (var i = 1, row; row = table.rows[i]; i++) { if(row == document.querySelector('.add-elements')) { break; } docDate = document.querySelector('input[name="invoice-date"]').value docContragent = document.querySelector('select[name="invoice-contragent-select"]').value docWare = document.querySelector('select[name="warehouse-select"]').value comment = document.querySelector('textarea[name="invoice-comment"]').value // ITEMS let name = row.cells[1].querySelector('span').dataset.id let quantity = row.cells[2].querySelector('input').value let buy_price = row.cells[3].querySelector('input').value let sell_price = row.cells[5].querySelector('input').value items.push({ "product": name, "buy_price": buy_price, "sell_price": sell_price, "quantity": quantity, }); } let invoice = { "warehouse": docWare, "date": docDate, "comment": comment, "contragent": docContragent, "items": items } let json = JSON.stringify(invoice); const csrftoken = Cookies.get('csrftoken'); $.ajax({ data: json, contentType: "application/json; charset=utf-8", type: "POST", // GET or POST headers: {'X-CSRFToken': csrftoken}, url: "http://127.0.0.1:8000/warehouse/api/notes/", success: function (response) { alert('ok') }, error: function (response) { console.log(response.responseJSON.errors) } }); return false; } document.querySelector('span[name="note-submit-btn"]').addEventListener("click", iterTable); serialisers.py def create(self, validated_data): last_num = ConsignmentNote.objects.filter(warehouse__company=self.context['request'].user.company).latest('id') items = validated_data.pop('items') note = ConsignmentNote.objects.create(**validated_data, doc_type = 1, number … -
How to connect AWS Opensearch with Django project on AWS Lambda
I'm working on a project that is almost finished except for one thing and I'm in despirate need of help.. The backend of my project that is written in Django/Python is deployed on AWS Lambda using a library called Zappa because my knowledge about AWS is really low and this seemed (for the first version) the best and fastest way to have my project up and running. It uses a AWS RDS PostgreSQL database to handle my database. The frontend of my project is written in Javascript/ReactJS has been put on a S3 bucket en made publicly available through Cloudfront by following this tutorial. Now, all of the above already works perfectly, it's just that now, because we have a lot of data that needs to be send from our backend/database to our frontend through API's, I want to make use of elasticsearch. So, I started using the AWS Opensearch Service (and using elasticsearch version 7.10) which then generated an endpoint for me to connect at. This all works great on my localhost, I can connect by using the code below, create my indexes using the ElasticsearchDSL library. Also because the endpoint is publicly availbable, I can just make an … -
Weight converter program in python using while loop [closed]
python use to printing the variables Question: weight:? lbs or kg:k 32 kilos -
How to test query_params?
how can i test query_params? I have provided a response and a request, but it still doesn't work. Initially, the error was like this: price = int(self.context.get('request').query_params.get('price', None)) AttributeError: 'NoneType' object has no attribute 'query_params' test_api.py class IpotekaApiTestCase(APITestCase): def setUp(self) -> None: self.offer_1 = Ipoteka.objects.create(bank_name='test', term_min=1, term_max=3, rate_min=1.5, rate_max=4.8, payment_min=12345, payment_max=123456) self.offer_2 = Ipoteka.objects.create(bank_name='test_1', term_min=1, term_max=3, rate_min=1.5, rate_max=4.8, payment_min=12345, payment_max=123456) def test_get(self): url = reverse('offer-list') response = self.client.get(url) view = IpotekaModelViewSet.as_view({'get': 'list'}) request = RequestFactory().get('/') context = {'request': view(request), 'response': response} serializer_data = IpotekaSerializer([self.offer_1, self.offer_2], context=context, many=True).data self.assertEqual(status.HTTP_200_OK, response.status_code) self.assertEqual(serializer_data, response.data['results']) serializers.py def get_payment(self, obj) -> int: try: price = int(self.context.get('request').query_params.get('price', None)) deposit = int(self.context.get('request').query_params.get('deposit', None)) term = int(self.context.get('request').query_params.get('term', None)) if price == 0 or term == 0: return 0 return self._get_offer_result(price, deposit, term, obj) except (ValueError, TypeError): return 0 Got this error: File "D:\Work\Django\Test_ipoteka\ipoteka\serializers.py", line 22, in get_payment price = int(self.context.get('request').query_params.get('price', None)) AttributeError: 'Response' object has no attribute 'query_params' ---------------------------------------------------------------------- Ran 1 test in 0.014s FAILED (errors=1) I also deleted response but it didn't help -
OR match in Python Redis scan
I'm using Django Redis to manage our application's Redis cache. Let's say I have the following keys in the cache: user-1:color user-1:sport user-2:color user-3:color user-3:whatever I want to delete all keys for user-1 and user-2. I know I can use the delete_pattern() method (see docs): for user_id in [1, 2]: cache.delete_pattern(f"user-{user_id}:*") However, this is very slow. See these links for more details about why: https://github.com/sebleier/django-redis-cache/issues/169 https://morganwu277.github.io/2017/07/16/Django-Redis-Scan-Too-Long/ I would like to try building a broader pattern so I only need to make one call to delete_pattern(). According to the docs, the pattern is glob syntax but I've tried the following and it's not working: cache.delete_pattern(f"user-{1,2}:*") Any ideas on how to construct this pattern? -
Slight change in admin panel design by running server on 0.0.0.0 instead of 127.0.0.1
I was previously running my server locally, but tried to allow access to my local network. I just added my IP address to the ALLOWED_HOSTS in settings.py and ran py manage.py runserver 0.0.0.0:8000 instead of py manage.py runserver. Even though all of the pages can be loaded and displayed correctly, when I went on the admin panel, I noticed that the design was slightly different, with all fonts changed and some icons removed. I ran the server on both 0.0.0.0:8000 and 127.0.0.1:8000 at the same time, and the difference remained, so that seems to come from the IP address used. My guess is that it's some static files not being loaded, but even if it's the case, I don't know why it happens. Could someone explain why this is happening ? -
Django medias(pictures) suddenly not loading
I am developing a website with Django, I had a lot of pictures in my project, uploaded from the admin panel and saved in the Media folder which I created for these uploads separately, It was working fine and exact way I wanted in months, Suddenly they are just not loading, getting 404 for all of them, without any change in project, they are just not loading. My media path in Settings.py : MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") I have added this to the end of my urls.py of the app: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and as i said, it was working fine for a long, suddenly this happened -
How to execute Django view through Stripe signal?
After a customer has unlocked a post, I want to add his profile to the list of profiles that have unlocked the post. def unlockpostview(request, post_id): if userthatisunlockingprofile in post.unlockedby.all(): pass else: post.unlockedby.add(userthatisunlockingprofile) When the user has paid I listen to the Stripe's succeeded event and execute the view like so: if (result.paymentIntent.status === 'succeeded') { $.get("{% url 'postsapp:unlockpostview' post.post_id %}") window.alert("Unlocked") } My problem was that anybody could go to the post and simply add /unlock to the end of the URL and execute the view. Then I added if request.is_ajax(): to the view but this still isn't the optimal solution. I do not expect a complete solution to this but please point me in the right direction if you can. Thanks :) -
Strange behavior with django and websocket behind nginx
I have a Docker Django app which uses django channels and Redis to stream data. All this is behind Nginx. Everything works seems to work well. I can reach my sites under subdomains and i also can connect with the websocket. The only issue is that the websocket streams the data and every short time (a few seconds) it blocks for almost exactly 5 seconds and then continue streaming... Like if every short time a background task is started that block my code. In the logs i can't see any error. Also the values that i receive at client side are sometimes duplicated and sometimes also out of oder... I posted my code. I hope it is not too much... I have a test thread in django sending test data: # websocket/apps.py from django.apps import AppConfig from threading import Thread from channels.layers import get_channel_layer from asgiref.sync import async_to_sync def task_handler(): count = 0 run = True while run: channel_layer = get_channel_layer() # <-- THIS BLOCKS SOMETIMES FOR 5 SECONDS async_to_sync(channel_layer.group_send)('group_1', {'type': 'send_message', 'message': str({'c': count})}) count+=1 time.sleep(0.1) class WebsocketConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'websocket' def ready(self) -> None: Thread(target=task_handler, daemon=True).start() This is my asgi.py file: # asgi.py import os … -
Tom-Select won't clear input when reset button is clicked
I'm using tom-select on my django form. On the form I also make a reset button to clear all input fields. All input values are cleared when I click the button, except the one using tom-select. form.py class ItemInputForm(ModelForm): def __init__(self, *args, **kwargs): super(ItemInputForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.layout = Layout( Row( .... Column('item', css_class = 'col-md-4'), css_class = 'row' ), .... Div( HTML('<button type="submit" class="btn btn-danger col-md-4 me-4"><i class="fa-solid fa-print"></i> Print</button>'), HTML('<button type="reset" class="btn btn-warning col-md-4"><i class="fa-solid fa-rotate-left"></i> Reset</button>'), css_class = 'text-center' ), .... tom-select on the template $(document).ready(function() { var item_select = new TomSelect("#id_item",{ create: false, placeholder: 'Search', valueField: 'value', searchField: 'text', maxItems: 1, closeAfterSelect: true, render: { option: function(data, escape) { return '<div>' + '<span class="text">' + escape(data.text) + '</span>' + '<span class="value">' + escape(data.value) + '</span>' + '</div>'; }, item: function(data, escape) { return '<div title="' + escape(data.value) + '">' + escape(data.text) + '</div>'; }, }, }); item_select.clear(); When I refresh the page, the input field is clear because of item_select.clear(), but it didn't work if I want to clear with reset button. How to clear the tom-select input with reset button? -
How can I solve validation logic in Django
In this code , if it is always displaying password does not match when I'm still giving the correct password. I'm unable to figure out exactly what's happening here! Pls help me with this. def Guide_register(request): if request.method == 'POST': firstname = request.POST.get('first_name') lastname = request.POST.get('last_name') username = request.POST.get('username') email = request.POST.get('email') password1 = request.POST.get('password1') password2 = request.POST.get('password2') image = request.POST.get('image') city = request.POST.get('city') if password1 == password2: if Guide_Register.objects.filter(username=username).exists(): messages.error(request,'Username already exists!') return redirect('guideregister') else: if Guide_Register.objects.filter(email=email).exists(): messages.error(request,'Email already exists!') return redirect('guideregister') else: guide = Guide_Register.objects.create(first_name=firstname,last_name=lastname,username=username,email=email,password=password1,confirm_password=password2,guide_photo=image,city=city) messages.success(request,'You are registered successfully as Guide!') return redirect('guidelogin') else: messages.error(request,'Password does not match!') return redirect('guideregister') else: return render(request,'accounts/guide_register.html') -
Apache error on ubuntu ERROR: Site (SiteName) does not exist
I'm facing a problem when I run sudo a2ensite test.watermaps-eg.com.conf to add a new site to apache2 it gives me ERROR: Site test.watermaps-eg.com does not exist! What I tried to do Added the file test.watermaps-eg.com.conf inside sites-enabled. Added the apache2 configurations inside the file. <VirtualHost *:80> ServerName https://test.watermaps-eg.com </VirtualHost> <VirtualHost *:80> ServerAdmin admin@innoventiq.com ServerName test.watermaps-eg.com DocumentRoot /home/ubuntu/test_water_maps_django ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/test_water_maps_django/static <Directory /home/ubuntu/test_water_maps_django/static> Require all granted Order Allow,Deny Allow from all AllowOverride all </Directory> <Directory /home/ubuntu/test_water_maps_django/kml_files> Require all granted </Directory> <Directory /home/ubuntu/test_water_maps_django/water_maps> Require all granted Order Allow,Deny Allow from all AllowOverride all <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess test_water_maps_django python-path=/home/ubuntu/test_water_maps_django python-home=/home/ubuntu/test_water_maps_django/venv WSGIProcessGroup test_water_maps_django WSGIScriptAlias / /home/ubuntu/test_water_maps_django/water_maps/wsgi.py WSGIPassAuthorization On </VirtualHost> I ran the command sudo a2ensite test.watermaps-eg.com.conf and it returns the mentioned above error. -
How to correctly write a condition in view Django?
The meaning of the program is to select analogues from the list and link them. I bind all values. I think the problem is in the wrong if. How to fix it My view: def editpart(request, id, **kwargs): if request.method == 'POST': part.name = request.POST.get("name") part.description = request.POST.get("description") analogs = Part.objects.all() for analog_zap in analogs: analog = analog_zap.analog if Part.objects.filter(analog_analog = analog): part.analog.add(analog_zap.id) My model: class Part(models.Model): name = models.CharField('Название', max_length=100) analog = models.ManyToManyField('self', blank=True, related_name='AnalogParts') -
Can d field which is already declared as unique can be used with another field and make a constraint unique together?[DJANGO CUSTOM USER MODEL]
This is my model class User(AbstractUser): """User model.""" username = None uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) email = models.EmailField(_('email address'), unique=True) domain=models.CharField(max_length=100) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: constraints = [ models.UniqueConstraint(fields=['email', 'domain'], name='unique_userID') ] will this work as email field is already unique?? -
How to Do Soft Delete in Django
Hi I am new to Django and I have just completed CRUD using django and postgresql. now my aim is to do SOftDelete but I am unable to do it below is my code def Delemp(request,id): delemployee = EmpModel.objects.get(id=id) delemployee.delete() showdata=EmpModel.objects.all() return render(request,"Index.html",{"data":showdata}) I am unable to convert the function in such a way that It would perform softdelete instead of hard delete,please help -
Django Model creation based on JSON structure to store in MongoDB using Djongo driver
I'm trying to create a model which can accept my JSON object and store it in MongoDB. I'm using djongo as a connector driver for my project. After making and trying lots of variations of model I'm unable to store the data in the format. I'm having problem in how to use ArrayField and EmbeddedField od Djongo models. Please suggest me the acceptable solution. the format I want to store in MongoDB collection is this. [ { "email": "himanshu@gmail.com", "customerName": "Himanshu Maiyani", "customerAddress": "B-4-102, Gadhpur Township", "orderItems": [ { "itemDescription": "pencil", "itemQuantity": 10, "itemPrice": 35.0 }, { "itemDescription": "books", "itemQuantity": 12, "itemPrice": 600.0 }, { "itemDescription": "school bag", "itemQuantity": 1, "itemPrice": 800.0 } ] }, { "email": "jayesh@gmail.com", "customerName": "Jayesh Maiyani", "customerAddress": "C-1-103, Gadhpur Township", "orderItems": [ { "itemDescription": "watch", "itemQuantity": 5, "itemPrice": 5000.0 }, { "itemDescription": "earphone", "itemQuantity": 2, "itemPrice": 995.5 } ] } ] these is a list of two objects of the same model. And I want make my orderItems attribute flexible to accept any number of item objects. and yes I'm also curious to know that what serializers I should implement to render them on django REST framework. Thank you. -
In django is there any way to access uploaded files in multiple requests?
I am building an application where users can upload their files and go to the payment page. After payment completion, I want to store the files uploaded by the user in the database. If the user does not complete the payment, then I do not want to save the files on the server or database. Is there any way to do that?