Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"int_list_validator" is not working in Django forms
I made the following Django form. from django.core.validators import int_list_validator class RoomForm(forms. Form): room_numbers = forms.CharField(validators=[int_list_validator], required=False, max_length=4000) In this form even if I submit a string like 'hello' the form gets submitted. I mean I can get the value 'hello' in views.py. I don't understand why because "int_list_validator" should not allow it. -
Django Slugify Not Showing Turkish Character
I wanna make business directory and i made category model here at the below. class FirmaKategori(models.Model): kategori = models.CharField(max_length=250) description = models.CharField(max_length=5000) slug = models.SlugField(max_length=250, null=False, unique=True, allow_unicode=True) def __str__(self): return self.kategori def get_absolute_url(self): return reverse('firma-kategori-ekle') def save(self, *args, **kwargs): self.slug = slugify(self.kategori, allow_unicode=False) super().save(*args, **kwargs) I made this, and if i allow_unicode=True, Forexample i made a category its name is Takım Tezgahları, became takım-tezgahları, but i want takim-tezgahlari Varyation 1: When i delete all allow_unicode=True tags, result is Category name = Ulaşım Sektörü Slug link: ulasm-sektoru Varyation 2: When i make all allow_unicode=True tags, result is Category name = Ulaşım Sektörü Slug link: ulaşım-sektörü I want ulasim-sektoru How can i solve this. -
How to create django media sub path with filebrowser
When uploading a media file through filebrowser in django-tinymce, I want to create a new folder under the upload folder based on the uploaded date (like ckeditor). For example, if you upload the abc.png file on December 3, 2022, I want to keep the path of [/{django-project}/media/upload/2022/12/3/abc.png], not [/{django-project}/media/abc.png]. I know that the file name can be edited by using the signals of the filebrowser, but I don't know how to change the file path. For example, if you upload the abc.png file on December 3, 2022, I want to keep the path of [/{django-project}/media/upload/2022/12/3/abc.png], not [/{django-project}/media/abc.png]. Is it possible to do this without modifying the module source files? -
How do i loop through the fields of a form in python?
I am trying to find out how "complete" a users profile is as a percentage. I want to loop through the fields of a form to see which are still left blank and return a completion percentage. My question is how do I reference each form value in the loop without having to write out the name of each field? Is this possible? completeness = 0 length = 20 for x in form: if form.fields.values[x] != '': completeness += 1 percentage = (completeness / length) * 100 print(completeness) print(percentage) -
What the type of timefield in django-ninja schema
in my model i have time = models.DateTimeField() and i put the type in my shcema : from datetime import date, time class BookingOut(Schema): user_id: int doctor_id: int date: date time: time to get the data but the django didn't accept this format for the time but accept it in the date this the error what should i put for the time i searched alot and didn't get anything useful plz help me -
Adding a search cum input bar in Django
creating an inventory management system for an automobile business. Need a search cum input bar, on a form, that allows for the input as well as searching on the database behind it. For example, if i type "hyundai", it should give me drop down of the Hyundai cars already available but if i type "hyundai sonata", i should be able to enter that value and submit the form even if there's nothing with that name in the database. I'm, working with Django Python I have tried creating a separate field for the input of any new value, and then a different bar that drops down all values from the database. The problem here is that for the car to show up on the drop down, it needs to be first added to the database through a different field which isnt that seamless. I'm a 3rd semester data science student therefore my description might be a bit off but do let me know if more details are needed. Even if i can get the actual name of these search cum input bars, it would be really helpful. Thank you in advance -
Integrate Odoo 15 with Django
I'm trying to build a Django REST API Project by retrieving data from Odoo, for that I need first of all to connect to odoo database. Any idea of how to do that !? -
Django Rest API ordering filters for custom serializer method
I will ordering product in "total_price" values. But my database does not contain a "total_price" value. I then produce in serializer like this: total_price = serializers.SerializerMethodField('get_total_price') def get_total_price(self,instance): price = instance.sell_price - instance.discount_price return price my rest api class: class ProductList(generics.ListAPIView): serializer_class = ProductSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter] ... ordering_fields = ['created_date', 'sell_price'...] ... My error page: FieldError at /api/product/ Cannot resolve keyword 'total_price' into field. Choices are:sell_price,discount_price .... -
How to use tag in django without using any 3rd partly library
One or more tags that the user can add to the entry i. A user can set this while creating a new entry. A user can also change this while updating an existing entry. Multiple tags can be added to the same entry,, how to using this in django models* How to implement tags -
How to add multiple image upload functionality in Django form.Imagefield()?
How to allow users to upload multiple images through Django Forms, which was fetched in Django template by using form.ImageField() it was providing the following output: <input type="file" name="image" accept"Image/*" id="id_image"> This is allowing to upload only one image, But need to provide multiple upload option. But I need the following output using Django Form with my custom class <input type="file" multiple accept"Image/*" id="id_image" class="myclass1 myclass2"> How can I achieve this? -
Request from server returns HTTP 403 but request from local machine returns HTTP 200
I'm facing pretty much what the title says. I have an Ubuntu server running 20.04.5 LTS running a Django application. I'm using the requests module to send API requests. However, whenever I try a request from the server - either from the application or a separate Python script or even cURL - I always get a 403 Forbidden response. But if I run the same command from my local machine - cURL/Postman/script - I get a 200 Response. The requests code is import requests headers = { 'Content-Type': 'application/json', } body = { /*Stuff related to authentication*/ } token_url = 'https://example.com/token' print("Attempting to get access token using the REQUESTS http module:") response = requests.post(token_url, json=body, headers=headers) print("Request Data:\n") print(f"Request Headers: {response.request.headers}") print(f"Response HTTP Status: {response.status_code}\nResponse body is {response.text}") Obviously, example.com isn't really the endpoint I'm attempting to hit up. The corresponding output from my server is Attempting to get access token using the REQUESTS http module: Request Data: Request Headers: {'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'application/json', 'Content-Length': '226'} Response HTTP Status: 403 Response body is Response content b'' I've been facing this issue since I updated my server about 2-3 days ago. requests suddenly has … -
how to solve Textblob import Exception in Django views
how to solve Textblob import Exception in Django views from textblob import TextBlob Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Zain Ul Abideen\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Users\Zain Ul Abideen\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "E:\small tools\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "E:\small tools\venv\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "E:\small tools\venv\lib\site-packages\django\core\management\base.py", line 475, in check all_issues = checks.run_checks( File "E:\small tools\venv\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "E:\small tools\venv\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "E:\small tools\venv\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() File "E:\small tools\venv\lib\site-packages\django\urls\resolvers.py", line 494, in check for pattern in self.url_patterns: File "E:\small tools\venv\lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "E:\small tools\venv\lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "E:\small tools\venv\lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "E:\small tools\venv\lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Zain Ul Abideen\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module … -
How to connect to mariadb5.5.52 using python3
My development environment python3.8 mariadb 5.5.52 pymysql 1.0.2 django 4.1.3 try to migrate but vscode tips django.db.utils.NotSupportedError: MariaDB 10.3 or later is required (found 5.5.52). -
DRF parses number array as string array
When I make a POST request from JavaScript to my Django Rest Framework backend, my array of numbers is interpreted as a list of strings on the backend, causing this error: cargo: ["Incorrect type. Expected pk value, received str."] This is how I make the request in JavaScript: const data = new FormData(); data.append("cargo", JSON.stringify([1, 2])); fetch(url, {method: "POST", body: data}).then(//<more code> In my Django Rest Framework serializer, I define the cargo field like this: cargo = serializers.PrimaryKeyRelatedField( many=True, queryset=models.CustomCargo.objects.all() ) I post an array of numbers but DRF thinks it's an array of strings so I get an error because it's expecting integers (PrimaryKeyRelatedField). I need to use multipart/form-data because I'm posting a file too, so I can't use application/json, which does work. Is there a way to fix this in the JavaScript code (I'd rather not convert strings to integers on the backend)? -
How do we solve the quotation inside of a quotation problem while using django in my HTML file?
I can't use the same type of string in the same type of string in HTML I have a static folder in the root dierctory of my django project and I was changing a downloaded template's link to match the django project. Here is the HTML attribute style="background-image: url("{% static 'assets/img/why-us.png' %}")" as you can see I tried using backslash () to resolve the problem but it was no avail. -
Easiest way to Normalizing data in models Parent Child tables Django Models
Trying to find the easiest way to make an meta abstract Child Model and meta abstract Parent Model with the same column "data" unique, The Child Models that I create will inherit the meta abstract Child Model will have column names in reference to the Parent Model Names. Something that can get_or_create into the Parent Models, while saving into the Child Model from django.db import models from django.apps import apps class ParentCharField(models.CharField): description = "A unique not null charfield for normalized parent tables" def __init__(self, *args, **kwargs): kwargs['unique'] = True kwargs['null'] = False super().__init__(*args, **kwargs) class ParentModel(models.Model): data = ParentCharField(max_length=10) class Meta: abstract = True class ChildModel(models.Model): def getModels(self): return apps.get_models() def get_model_name(self, value): model_name = value.capitalize() models = apps.get_models() for i in models: p = i.__name__.split('.')[-1] if model_name in p: return i def get_parent_object(self, name, value): object_cls = self.get_model_name(name) if object_cls: objected, created = object_cls.objects.get_or_create(data=value) return object_cls.objects.get(id = objected.id) def save(self, *args, **kwargs): fields = [i.name for i in self._meta.fields][1:] newargs = [] newkwargs = {} if args: p=0 for i in args: newargs.append(self.get_parent_object(fields[p],i)) p += 1 if kwargs: for i, v in kwargs.items(): newkwargs[i] = self.get_parent_object(i, v) models.Model.save(self, *newargs, **newkwargs) class Meta: abstract = True class Cik(ParentModel): pass … -
OSError: [Errno 24] Too many open files in Django app served by Gunicorn
I have an exception in my Django application served by Gunicorn / Nginx with no detailed information available. The error is captured in Sentry logging system on a regular basis. Any hints in which direction I should dig? exception OSError: [Errno 24] Too many open files socket.py in accept at line 292 self <socket.socket fd=9, family=AddressFamily.AF_UNIX, type=SocketKind.SOCK_STREAM, proto=0, laddr=/opt/trading-backend/trading-backend.sock> gunicorn/workers/sync.py in accept at line 28 gunicorn/workers/sync.py in run_for_one at line 69 gunicorn/workers/sync.py in run at line 125 gunicorn/workers/base.py in init_process at line 142 gunicorn/arbiter.py in spawn_worker at line 589 -
how to run loader on successful form submission only?
I want that the loader should start ONLY and ONLY when the form has been successfully submitted (instead of just the onclick submit button event that the code does currently). How can I do so? <div id="loader" class= "lds-dual-ring hidden overlay" > <div class="lds-dual-ring hidden overlay"> </div> <div class="loadcontent"><div><strong>Working on your request...it may take up to 2 minutes.</strong></div></div> </div> Code below is the part where loader kicks upon submit button event. $('#submitBtn').click(function () { $('#loader').removeClass('hidden') // $('#loader').html('Loading').addClass('loadcontent') // $("#loading").html("Loading"); }) </script> Code below is one of the form fields that takes a value from user: <div class="form-group"> <div class="form-control"style="padding: 0;"> {% ifequal field.name 'Port' %} {% render_field field class="rowforinput marginforfields form-control" style="height: 23px; margin-left: 0; margin-right: 0" title=" For eg. 1/1/48 or 2/1/16" pattern="^[12]/1/(?:[1-3]\d|4[0-8]|[1-9])$" required=true %} {% endifequal %} </div> </div> -
how to extract data from the database and pass it to the function in Django
I`m beginner Django user, please help me. I have multiple records in a sqlite3 data table. Please tell me how to read this data from the database in Django and write it to the views.py function. This is my models.py class Value(models.Model): capacity = models.FloatField('Емкость конденсатора') amplitude = models.FloatField('Амплитуда') frequency = models.FloatField('Частота') This is my views.py def voltage(array, a, c, w, tim): t = 0 for i in range(100): array.append(c * a * math.sin(w * t - math.pi / 2)) tim.append(t) t = t + 0.1 someArray = [] tim = [] voltage(someArray, a, c, tim) in c I want to write capacity, in a - amplitude, in w - frequency. I hope I can get data from the database into the views.py function -
is it possible to avoid n+1 django query here? If so, how?
I have these models class Thing1(MyModel): thing2 = models.OneToOneField( Thing2, on_delete=models.PROTECT, related_name="super_pack" ) some_id = models.IntegerField() class Thing2(MyModel): name = models.CharField(max_length=50, primary_key=True) class Thing3(MyModel): name = models.CharField(max_length=255) thing2 = models.ForeignKey( Thing2, related_name="thing3s", ) class Thing4(MyModel): root_thing3 = models.OneToOneField( Thing3, on_delete=models.PROTECT, related_name="my_related_name" ) member_item_thing3s = models.ManyToManyField( Thing3, through="unimportant", related_name="important_related_name", ) is_default = models.BooleanField(default=False) I'm working with a Django serializer. Already defined I have a queryset with prefetching. As it stands, the following is performant: all_thing1s: QuerySet[Thing1] for thing1 in all_thing1s: first_thing3 = Thing1.thing2.thing3s.all()[0] (from now on assume we are in the loop body) which is not ideal, if there is always 1 thing3 the schema shouldn't allow for many, but I can't change the schema at this time.) At this point I believe the ability to pre-fetch further has been broken because we have returned a Thing3 (first_thing3) and no longer have a query set to work with At the start of this I thought Django magically used previous prefetches, I didn't realize that the filters etc. that you wanted to make use of the prefetches had to be chained to the prefetches. But now I want to do: thing4 = first_thing3.important_related_name.all()[0] return thing4.root_thing3 (note: first_thing3 and root_thing3 share the same … -
Django select from many-to-many
The basic model. class Game(models.Model): date = models.DateField() ... class Player(models.Model): user = models.OneToOneField(User, default=None, on_delete=models.CASCADE) games = models.ManyToManyField(Game, through='PlayerGame') ... class PlayerGame(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE) game = models.ForeignKey(Game, on_delete=models.CASCADE) score = models.IntegerField() ... Each game will have two players with their respective scores. When one player/user is logged in, I'd like to display all their games against other players. e.g. Player 1 logged in... Date Opponent Your Score Opponent Score 2022-01-01 Player 2 31 27 2021-06-02 Player 4 31 26 2021-06-02 Player 2 5 31 2021-05-27 Player 6 20 31 If Player 2 was logged in, they may see Date Opponent Your Score Opponent Score 2022-01-01 Player 1 27 31 2021-06-02 Player 1 31 5 Any ideas on how to write a query for this? -
Django and adding a static image
Good evening, I've just completed this tutorial: https://docs.djangoproject.com/en/4.1/intro/tutorial01/ and I need to add a new directory to display a dataset (unrelated to the polls app) I've set up my new directory as I did the first steps in the tutorial. My steps: ...\> py manage.py startapp newendpoint newendpoint/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py urls.py views.py path('newendpoint/', include('newendpoint.urls')) **Once this is setup I've tried these tutorials: ** https://youtu.be/u1FR1nZ6Ng4 I've tried this tutorial and had no luck https://adiramadhan17.medium.com/django-load-image-from-static-directory-27f002b1bdf1 I've also tried this one My server goes down or nothing displays. I could really use some help getting this figured out, before I tried the static image I was trying to add a csv via SQLite3 with no luck either. -
How do I overwrite Bootstrap SCSS variables for my django website using PyCharm?
I'm using PyCharm to manage my django files and for the front end I'm using Bootstrap. I'm currently using the CDN method to point to the bootstrap files in my base.html file. I've recently come to a point where I want to customize some of the SCSS variables that bootstrap provides, but I'm puzzled and can't find a guide anywhere to how to do this with my configuration. I used npm to install the bootstrap files to my outer project folder. I've tried installing django-sass-compiler using pip, and then adding the required setting to my settings.py, but when I ran the command "python manage.py sass-compiler" (as per the PyPi docs), I got "ModuleNotFoundError: No module named 'django_sass_compiler'" I'm assuming that if I were to get that working then it would compile my custom SCSS file into a CSS file that would overwrite my current 'main.css' (is that right?), however I can't even figure out that part. If someone could please point me in the right direction then that would be great, there really isn't a lot of help out there for sass, pycharm, django & bootstrap together. -
[ODBC Driver 17 for SQL Server][SQL Server]Cannot open server <server name> requested by the login. The login failed. (40532) (SQLDriverConnect)')
Using mssql-django package to connect to SQL server. It is working fine in Local Azure Virtual Machine. But when I deploy Django using Azure Function App, It is giving me the above error. Is anyone faced the same issue. I am not sure why it is not working when i deploy app in Azure function app. Is there any function app configuration that I need to change? -
Elastic beanstalk failed deployment
After deploying with Beanstalk, I have this error : Instance deployment failed. For details, see 'eb-engine.log'. It's just after this one : Added instance [i-0ca6b54779ee5d6ce] to your environment. Do you have any ideas?Error message I was trying to deploy a django web-app using elastic beanstalk. I expected a successful deployment but faced some error messages that i can not solve.