Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How do I use the ManyToManyField attribute in a class in MinValueValidator?
I have two models. One has a price attribute and I would like to use it to set a minimum value in lastbid. I don't really understand how to do this. class Auctionmodel(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) title = models.CharField(max_length=300) content = models.TextField() price = models.IntegerField() pic = models.CharField(max_length=300, blank=True) category = models.ManyToManyField(Category, related_name='auctioncategory') class Bids(models.Model): whosebid = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) bidauction = models.ManyToManyField(Auctionmodel, blank=True, related_name="bbidauction") currentprice = bidauction.price lastbid = models.IntegerField(validators=[MinValueValidator(currentprice)]) -
how to write a Django rest framework custom authentication
I need a third party package for Django rest framework authentication that in the first login, give API-KEY from user and generate access token and refresh token for he. it is like the Json Web Token but the difference is I want to give API-KEY not user password. please help me thanks a lot -
How to have urls in an svg in django
I want to have an svg image that is in memory to have urls embedded in it, that when the user clicks they go to another page. I am able to create the image: import matplotlib.pyplot as plt from io import BytesIO sns_plot = plt.scatter([1, 2, 3], [4, 5, 6]) sns_plot.set_urls(['https://www.bbc.co.uk/news', 'https://www.google.com/', None]) fig = sns_plot.get_figure() img_in_memory = BytesIO() fig.savefig(img_in_memory, format="svg") image = base64.b64encode(img_in_memory.getvalue()) image = image.decode(settings.DEFAULT_CHARSET) sns_plot.get_figure().clf() and display it in the template: <img src="data:image/svg+xml;base64,{{image}}" class="img-fluid mx-auto d-block"/> If I right click and save the image the links are clickable but when the image is displayed in the browser they are not? -
Django django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
So I'm trying to integrate a model with mongoDB usng djongo driver, and when I tried to insert a record from within models.py it is giving me this error. AppRegistryNotReady("Models aren't loaded yet.") here are my code files. models.py from djongo import models class Iname(models.Model): item_name = models.TextField() class Meta: abstract = True class Iquantity(models.Model): item_quantity = models.TextField() class Meta: abstract = True class Iprice(models.Model): item_price = models.TextField() class Meta: abstract = True class Order(models.Model): email = models.EmailField(primary_key = True, name = "email") name = models.CharField(max_length=30, help_text="Enter Customer Name", name = "name") address = models.TextField(help_text="Enter customer's Address", name = "address") item_names = models.ArrayField(model_container = Iname) item_quantities = models.ArrayField(model_container = Iquantity) item_prices = models.ArrayField(model_container = Iprice) objects = models.DjongoManager() o = Order() o.email = "jayesh@gmail.com" o.name = "dhsdb" o.address = "agdkhdvf" o.item_names = ['chocolate', 'pencil'] o.item_quantities = [5, 10] o.item_prices = [10, 3] o.save() serializers.py from .models import Order, Iname, Iprice, Iquantity from rest_framework import serializers class ItemSerializer(serializers.ModelSerializer): class Meta: model = Iname class QuantitySerializer(serializers.ModelSerializer): class Meta: model = Iquantity class PriceSerializer(serializers.ModelSerializer): class Meta: model = Iprice class OrderSerializer(serializers.ModelSerializer): item_names = ItemSerializer() item_quantities = QuantitySerializer() item_prices = PriceSerializer() class Meta: model = Order fields = "__all__" views.py from rest_framework.decorators import api_view … -
Django SlugRelatedField with multiple keys which are unique
I have a model like the followings. class Tree(AuditedModel): id = models.AutoField(primary_key=True) genre = models.ForeignKey('Genre', on_delete=models.CASCADE) specie = models.ForeignKey('Specie', on_delete=models.CASCADE) name = models.CharField(max_length=63) class Meta: get_latest_by = 'created' unique_together = (('genre', 'specie'),) ordering = ['-created'] I do have a separate serializer for the above model and, Then I do have another model ,serializer (for another model), which serializes it as follows. class TreeSubplant(AuditedModel): id = models.AutoField(primary_key=True) tree = models.ForeignKey('Tree', on_delete=models.CASCADE) name = models.CharField(max_length=63) class TreeSubplantSerializer(serializers.ModelSerializer): tree = models.SlugRelatedField('id', queryset=Tree.objects.all()) name = models.CharField(max_length=63) class Meta: model = TreeSubplant But my question is, as tree's genre and specie would be the directly used parameters with the client, is there a way that we can make use to use interact with the backend in this scenario. -
OSError: [Errno 99] Cannot assign requested address when testing the sendtestemail of kiwi tcms
I am encountering this error below when running the command "docker exec -it kiwi_web /Kiwi/manage.py sendtestemail user1@example1.tld": OSError: [Errno 99] Cannot assign requested address I can't find other logs pertaining to this error. The full error log: File "/Kiwi/manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/venv/lib64/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/venv/lib64/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/venv/lib64/python3.8/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/venv/lib64/python3.8/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/venv/lib64/python3.8/site-packages/django/core/management/commands/sendtestemail.py", line 35, in handle send_mail( File "/venv/lib64/python3.8/site-packages/django/core/mail/__init__.py", line 87, in send_mail return mail.send() File "/venv/lib64/python3.8/site-packages/django/core/mail/message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) File "/venv/lib64/python3.8/site-packages/django/core/mail/backends/smtp.py", line 124, in send_messages new_conn_created = self.open() File "/venv/lib64/python3.8/site-packages/django/core/mail/backends/smtp.py", line 80, in open self.connection = self.connection_class( File "/usr/lib64/python3.8/smtplib.py", line 253, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib64/python3.8/smtplib.py", line 337, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib64/python3.8/smtplib.py", line 308, in _get_socket return socket.create_connection((host, port), timeout, File "/usr/lib64/python3.8/socket.py", line 808, in create_connection raise err File "/usr/lib64/python3.8/socket.py", line 796, in create_connection sock.connect(sa) OSError: [Errno 99] Cannot assign requested address -
Slice queryset after order_by() in Django
I have order_by() model django and got queryset following result: queryset = <QuerySet [<MyModel: MyModel object (4)>, <MyModel: MyModel object (2)>, <MyModel: MyModel object (1)>, <MyModel: MyModel object (3)>, <MyModel: MyModel object (5)>]> The result is not sorted by id. And I want slice queryset that have order MyModel with id greater than 1 to get the following results: new_queryset = <QuerySet [<MyModel: MyModel object (4)>, <MyModel: MyModel object (2)>]> Is there any way to slice without loop like this to reduce the query ? for index in range(len(queryset)): if queryset[index].id == 1: new_queryset = queryset[:index] break Thank You in Advance. -
I am getting the error Error code: Unhandled Exception on python anywhere
I am trying to deploy my blog app using python anywhere. After I did all the steps and I clicked only my link I got the error Error code: Unhandled Exception. I do not know what is causing my issue any help would be appreciated. # +++++++++++ DJANGO +++++++++++ # To use your own django app use code like this: import os import sys # ## assuming your django settings file is at '/home/codewizblog/mysite/mysite/settings.py' ## and your manage.py is is at '/home/codewizblog/mysite/manage.py' path = '/home/codewizblog/codewizblog/code-wiz-blog' if path not in sys.path: sys.path.append(path) os.chdir(path) os.environ.setdefualt("DJANGO_SETTINGS_MODULE", "blog.settings") import django django.setup() #os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' # ## then: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() -
Determining Whether the User Entered In A City Or A Country In Folium
I am trying to design a program where the user will enter in the name of a country, city, or small town and then have the marker on a world map accurately show the location as well as the name of that country, city, or small town. Any ideas on the approach I can take to accomplish this? The following is the current Python source code I have at the moment: def DisplayMap(request): if request.method == 'POST': mapForm = MapDataForm(request.POST) if mapForm.is_valid(): mapForm.save() # return redirect('/') will redirect the user back to # 127.0.0.1:8000/ which is the homepage of the application. # Instead the user must be redirected back to the page that # is loaded with the 'display-map' url path name. return redirect('display-map') else: mapForm = MapDataForm() # For the following line to work, we must have at least one 'MapDatabase' object. address = MapDatabase.objects.all().last() location = geocoder.osm(address) latitude = location.lat longitude = location.lng country = location.country city = location.city if latitude == None or longitude == None: address.delete() return HttpResponse('Your search input was invalid.') # Here the map object is being created. # The following line of code will center the map and zoom in at # an …