Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send OTP to mobile number in Django for free, without using any 3rd party access
I am working on the backend part of the app using Djangorestframework. I am searching for free mobile number verification by sending OTP to the registered mobile number. -
How to merge two different querysets with one commin field in to one in django?
I have 2 Querysets Sales_order and Proc_order. The only common field in both is the product_id. I want to merge both these query sets to one with all fields. sales_order has fields product_id,sales_qty,sales_price. proc_order has fields product_id, proc_qty, proc_price. I want to merge both these to get a queryset which looks like. combined_report which has fields product_id,sales_qty,sales_price,proc_qty, proc_price. My final aim is to calculate the difference between the number of products. I'm using Django 2.1 -
Get the local file path of the modelfield django
I have a question regarding to the django models. I have a model 'model1' class model1(models.Model): dataset = models.FileField(upload_to='estimate/') def column(self): arr = os.listdir('uploads/estimate') try: dframe = pd.read_csv(f'uploads/estimate/{arr[0]}') columns = dframe.columns columns_tuple = [tuple([x,x]) for x in columns] return columns_tuple except: return [('---','---')] this model1 is mainly used to upload the csv file and I want to get the column names for the drop down list options for another model 'model2'. class model2(models.Model): column = estimate() columns = column.column() open_column = models.CharField(max_length=50, choices = columns) high_column = models.CharField(max_length=50, choices = columns) low_column = models.CharField(max_length=50, choices = columns) close_column = models.CharField(max_length=50, choices = columns) volume_column = models.CharField(max_length=50, choices = columns) Initially the directory uploads/estimate is empty, hence the model1.column() will return columns = [('---','---')], but when I upload the csv file into model1, model2 will not update the drop down list option. I am not sure any other way that can read the csv file so I use the pd.read_csv, it's because I don't know how to use the object dataset, I tried using self.dataset.name or self.dataset.path to get the local file path but system said that it does not have these attributes. So I eventually used os.listdir to locate the … -
Get the polymorphic instance of the parent class from child in Django
I am inheriting a parent model to a child model this way: class ModelA(PolymorphicModel): name = models.CharField(max_length=255) class ModelB(ModelA): category = models.CharField(max_length=255) For specific reasons, I have to fetch the base class instance with the parent model ContentType. I tried this: ModelA.objects.non_polymorphic().get(pk=id) It returns the instance of ModelA but the ContentType is still ModelB Is there any way I can execute this? -
mypy and django: error: Library stubs not installed for "six" (or incompatible with Python 3.9)
I have setup mypy for a django project [mypy] # The mypy configurations: https://mypy.readthedocs.io/en/latest/config_file.html python_version = 3.9 check_untyped_defs = True # disallow_any_explicit = True disallow_any_generics = True disallow_untyped_calls = True disallow_untyped_decorators = True ignore_errors = False ignore_missing_imports = True implicit_reexport = False strict_optional = True strict_equality = True no_implicit_optional = True warn_unused_ignores = True warn_redundant_casts = True warn_unused_configs = True warn_unreachable = True warn_no_return = True mypy_path = /home/user/app/backend_django/src plugins = mypy_django_plugin.main, mypy_drf_plugin.main [mypy.plugins.django-stubs] django_settings_module = project.settings Now I get settings.py:21: error: Library stubs not installed for "six" (or incompatible with Python 3.9) In settings.py I am importing six So how to get this error resolved. I have django-stubs installed -
Get queryset object from child to append to parent queryset
I have the below models class Order(models.MOdel): order_id = models.AutoField(primary_key=True) ... class OrderLink(models.Model): link_type = models.CharField(max_length=255, db_index=True) linked_order = models.ForeignKey(Order, related_name='linked_order_links', on_delete=models.CASCADE) original_order = models.ForeignKey( Order, related_name='original_order_links', on_delete=models.CASCADE, null=True, blank=True, default=None ) orders = order_models.Order.objects.filter() I have orders queryset. Lets say I have got a parent order I need to find all the child orders from OrderLink and append to the orders queryset. How can I achieve that? linked_order is the parent order and original_order is the child. So it will be in the format, P1C1, P1C2 etc. So finally in the orders I need [P1, C1, C2]. All orders whether it is parent or child refers to Order table. -
Loop list of list item dynamically in Django templates
I have list in a list that look like this : clientList = [['Client 1', 'Yes', 'No', 'Yes', 'Yes'], ['Client 2', 'No', 'No', 'Yes', 'Yes'], ['Client 3', 'Yes', 'Yes', 'Yes', 'Yes']] I need to call the list in the template dynamically as below <table> <tr> {% for c in clientList %} <td>{{c}}</td> {% endfor %} <tr> <table> But it doesn't work cos it looks like this And I also can't loop it using the method {{c.0}}, {{c.1}}, {{c.3}}, {{c.4}} because the list will change according to how many client are selected. So I need to loop it dynamically. I tried to use the method in this link but it didn't work cos I kept getting the error "list indices must be integers or slices, not str" Is there any way I can do this ? -
django not accessible from another computer
followed instructions here to create my first django web sever. Haven't done any major customization yet, except. Setup settings.py: ALLOWED_HOSTS = ['192.168.1.111', 'localhost', '127.0.0.1'] Started django from cmd prompt python manage.py runserver 0.0.0.0:8080 All the three url link works on this local machine where django is installed: http://127.0.0.1:8080/, http://localhost:8080/, http://192.168.1.111:8080/ I then went onto Windows Firewall settings to include 8080 as an inbound rule: My problem is http://192.168.1.111:8080/ does throw an exception when accessed from another computer (in the same network, IP being 192.168.1.77). Error is "Site cannot be reached, took too long to respond". I am not able to figure out what am I doing wrong. I am certain its a firewall issue. My python version is 3.9 and django version is 3.2. FYI - I moved to 8080 just for kicks. I had same issue with 8000. Two things worth noticing: (1) 192.168.1.111:8080 does throw a "Not secure connection" warning on the primary machine (where django is installed) (2) Only 0.0.0.0:8080 shows up as open port when I run this: C:\Windows\system32>netstat -ab Active Connections . . [postgres.exe] TCP 0.0.0.0:7680 DEVSERVER:0 LISTENING Can not obtain ownership information TCP 0.0.0.0:8080 DEVSERVER:0 LISTENING [python3.9.exe] TCP 0.0.0.0:49664 DEVSERVER:0 LISTENING . . Can … -
Django | can't see form {{form.username}}
forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] views.py from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm My views from .forms import CreateUserForm Registration def regPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() context = {'form':form} return render(request, 'web/car-finder-home.html') html <form class="needs-validation" method="POST" action=""> {% csrf_token %} <div class="mb-4"> <label class="form-label text-light" for="signup-name">Username</label> {{ form.username }} </div> <div class="mb-4"> <label class="form-label text-light" for="signup-email">Email address</label> <input class="form-control form-control-light" type="email" id="signup-email" placeholder="Enter your email" required /> </div> <div class="mb-4"> <label class="form-label text-light" for="signup-password">Password <span class="fs-sm opacity-50">min. 8 char</span></label> <div class="password-toggle"> <input class="form-control form-control-light" type="password" id="signup-password" minlength="8" required /> <label class="password-toggle-btn" aria-label="Show/hide password"> <input class="password-toggle-check" type="checkbox" /><span class="password-toggle-indicator"></span> </label> </div> </div> <div class="mb-4"> <label class="form-label text-light" for="signup-password-confirm">Confirm password</label> <div class="password-toggle"> <input class="form-control form-control-light" type="password" id="signup-password-confirm" minlength="8" required /> <label class="password-toggle-btn" aria-label="Show/hide password"> <input class="password-toggle-check" type="checkbox" /><span class="password-toggle-indicator"></span> </label> </div> </div> <div class="form-check form-check-light mb-4"> <input class="form-check-input" type="checkbox" id="agree-to-terms" required /> <label class="form-check-label" for="agree-to-terms"> <span class="opacity-70">By joining, I agree to the</span> <a href="#" class="text-light">Terms of use</a> <span class="opacity-70">and</span> <a href="#" class="text-light">Privacy policy</a> </label> </div> <button class="btn btn-primary btn-lg w-100" type="submit">Sign up</button> </form> -
insufficient output in Traceback of python execution
How to further troubleshoot Django issue where only built-in package files are listed in traceback output, instead of those user-created files, which does not tell what is wrong in the *.py files I created. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 393, in execute self.check() File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 423, in check databases=databases, File "/usr/local/lib/python3.7/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/usr/local/lib/python3.7/site-packages/wagtail/admin/checks.py", line 83, in inline_panel_model_panels_check errors.extend(check_panels_in_model(cls)) File "/usr/local/lib/python3.7/site-packages/wagtail/admin/checks.py", line 110, in check_panels_in_model context='InlinePanel model', File "/usr/local/lib/python3.7/site-packages/wagtail/admin/checks.py", line 110, in check_panels_in_model context='InlinePanel model', File "/usr/local/lib/python3.7/site-packages/wagtail/admin/checks.py", line 110, in check_panels_in_model context='InlinePanel model', [Previous line repeated 984 more times] File "/usr/local/lib/python3.7/site-packages/wagtail/admin/checks.py", line 100, in check_panels_in_model if hasattr(cls, 'get_edit_handler'): File "/usr/local/lib/python3.7/site-packages/wagtail/utils/decorators.py", line 29, in __get__ return self[owner] RecursionError: maximum recursion depth exceeded while calling a Python object Any thoughts on how to further troubleshoot? -
Javascript-django Getting element by classname
I am trying to build a cart module where on button click the id of the rendered product is passed ( currently just trying to print on console) .... When I console print the elements, I get a HTML Collection with the proper elements... but then when I try to print the length I get length is zero and so I am not able to loop through the elements in the collection... HTML: {% for food in foods %} <div class="row"> <div class="col-md-4"> <a style="color:#ffffff; " href="https://en.wikipedia.org/wiki/{{food.name}}"><h2 style="text-align: center;">{{food.name}}</h2></a> </div> <div class="col-md-4"> <h2 style="text-align: center;">{{food.price}}</h2> </div> <div class="col-md-4"> <input type="text" style="color: black;"> <button data-product={{product.id}} data-action="add" class="update-cart">Add</button> <!--this is the button I am trying to select--> <!-- <button style="height: 30px; width: 50px; margin-bottom:0px; color: black;" id="add_to_cart" data-product={{food.id}} data-action="add" class="btn btn-secondary update-cart"> Add </button> --> <br> <br> </div> </div> {% endfor %} JS file : console.log('TEST CONSOLE') var updateBtns = document.getElementsByClassName('update-cart') console.log(updateBtns) console.log(updateBtns.length) console.log('First element' , updateBtns[1]) for(var i = 0; i < updateBtns.length; i++){ console.log(updateBtns[i]) updateBtns[i].addEventListener('click', function(){ console.log('inside fn'); var productID = this.dataset.product; var action = this.dataset.action; console.log('productId:',productID,'Action:',action); }) console.log('over') } CONSOLE: TEST CONSOLE base.js:3 HTMLCollection(3)0: button.update-cart1: button.update-cart2: button.update-cartlength: 3[[Prototype]]: HTMLCollection base.js:4 0 base.js:5 First element undefined :8000/favicon.ico:1 Failed to load … -
FieldError trying to delete Django instances with generic foreign key
While fixing some errors, I made two test instances. Now that I finished that, I wanted to delete those two tests: nj.delete() raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword 'content_type' into field. Choices are: awards, career_highlights, content_object_org, content_object_pc, content_type_org, content_type_org_id, content_type_pc, content_type_pc_id, date_updated, daterange, end_date, honors, object_id_org, object_id_pc, org_history_updated, publications, role, significant_event, start_date, title, uniqid, updated_Vitae_bio_and_org_history This error is not on the model I was deleting from, but an intermediate model which also has a generic foreign key. Django can’t find the field ‘content_type’ because there is no such field, so I don’t know why it is looking for it. There is a content_type_org and a content_type_pc. From the context I assume Django wants the content_type_org. But how do I tell Django to look for that instead? I also tried going to the superclass and deleting the same object from there, jn.delete() but got the same error. -
docker-compose with Django and Postgresql: Password does not match for user "postgres"
I am following exactly the django, psql, docker tutorial https://docs.docker.com/samples/django/ and I keep getting the error: Password does not match for user "postgres" and from django I am getting: web_1 | File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect web_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web_1 | django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" docker-compose.yml version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db Dockerfile # syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ Django database settings ALLOWED_HOSTS = ['*'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } } I think the only thing that is stopping it from working is the psql password not working from django side -
embed django login in an iframe
I need to run a study on Amazon MTurk, and I want to create a one-time django user and login for them (so we don't need the user themselves to signup and log in, this is a one-time study so they don't need to remember their username or password). I used a chain of jquery ajax calls to achieve this goal: <consent.html> function startGame() { $.ajax({ url:'https://comphcithree.eecs.umich.edu:8030/chess1/create_user/', dataType: 'json', type: 'POST', success: function(data) { console.log('username:', data.username); console.log('password:', data.password); $.ajax({ url:'https://comphcithree.eecs.umich.edu:8030/login/', data: { 'username': data.username, 'password': data.password, 'csrfmiddlewaretoken': csrftoken }, dataType: 'json', type: 'POST', error: function() { console.log('logged in successfully'); window.location.href = 'https://comphcithree.eecs.umich.edu:8030/start/'; } }); } }); this worked fine when I access the page via a django URL. But since I need to deploy it on MTurk, I need to put the page in an HTML iframe, and it stopped working. Here is how I access the page (consent.html): <iframe width="1000px" height="600px" src="https://comphcithree.eecs.umich.edu:8030/chess1/consent"></iframe> I got an status of 403 forbidden, and the User object (should be) becomes an AnonymousUser: enter image description here I checked that the user is successfully created in our database. Then I thought that the problem is caused by CORS, and I tried to add django-cors-header … -
How to get the multiple value from request for Django-restful-framework
How to get the multiple value from request @api_view(['POST', 'GET']) def getParamAjax(request): print("{0}".format(request.query_params.get('genre'))) localhost/api/genre=test it shows test, ....ok localhost/api/genre=test&genre=cool It shows only cool .... Why multiple value is not obtained?? I want to get the value list like this below genres = list(request.query_params.get("genre")) And it doesn't work as Post. Does anyone help??? -
Can't match regex for django url (methods described earlier on stackowerflow don't work)
Can't match regex for django url you need to process an incoming request from the frontend "GET /api/city_list/9/?q=test HTTP/1.0" 404 Not Found "GET /api/city_list/9/?q=tt HTTP/1.0" 404 Not Found I tried several options path('api/city_list/<int:id>/?q=<str:q>', api_city_list, name='api_city_list'), does not work re_path(r'^api/city_list/\d+/\?|&q=\w', api_city_list, name='api_city_list'), does not work re_path(r'^api/city_list/<int:id>/(?P<q>\D+)', api_city_list, name='api_city_list'), does not work views.py does not reach the debugger. url checker fails Friends, tell me how to do it, otherwise I'm already confused with regular expressions for Django (Django 3.1) -
How to access collections in MongoDB Atlas database when using djongo?
It's straightforward to directly access collections in a MongoDB database by using pymongo. However, it's not clear how to do so when using djongo. Can anyone show me how this can be done? -
How to display the ArrayField as a list of elements instead of a comma separated string inside the admin panel?
My model contains a field like this: from django.contrib.postgres.fields import ArrayField text_list = ArrayField(models.CharField(max_length=255), null=True) This is what I'm hoping to achieve: How can I display the ArrayField as a list of elements instead of a comma separated string inside the admin panel? -
I want to connect djano-rest-framework with MSSQL could anyone guide me. Can find only Django+MSSQL
I am new to FullStack/microservices. I am building an app where the frontend is React Native and the backend is Django or Django-rest-framework, the database is MSSQL and this will be deployed on AWS. I am fairly new in this tech stack need help. -
Static image isn't showing in template for html email in django
It's probably something simple, but I can't get the image to display in an email template in django. I've tried using protocol and domain from something I read online, but this isn't working. Can anyone tell me what I'm missing? I have a suspicion it's not calling the static at all ... /templates/contact/contact.html {% extends 'email.html' %} {% load static %} {% block email_content %} <table style="margin: 0px auto; background-color: white;width: 100%;"> <tbody> <tr><td><img src="{{ protocol }}://{{ domain }}{% static 'img/MaffsGuruEmailHeader.jpg' %}" alt="MaffsGuru Logo" style="width: 100%;"></td></tr> I am calling it using the following: context = ( {'sender_name': sender_name, 'sender_email': sender_email, 'message': message, 'contact_number': contact_number} ) text_content = render_to_string('contact/contact.txt', context, request=request) html_content = render_to_string('contact/contact.html', context, request=request) msg = EmailMultiAlternatives( subject=subject, body=text_content, from_email=from_email, to=to_email, reply_to=[sender_email, ] ) msg.attach_alternative(html_content, "text/html") msg.send(fail_silently=False) Thanks in advance for any help pointing me in the right direction. -
Can't match regex for django url
Can't match regex for django url you need to process an incoming request from the frontend "GET /api/city_list/9/?q=test HTTP/1.0" 404 Not Found "GET /api/city_list/9/?q=tt HTTP/1.0" 404 Not Found I tried several options path('api/city_list/<int:id>/?q=<str:q>', api_city_list, name='api_city_list'), does not work re_path(r'^api/city_list/\d+/\?|&q=\w', api_city_list, name='api_city_list'), does not work re_path(r'^api/city_list/<int:id>/(?P<q>\D+)', api_city_list, name='api_city_list'), does not work Friends, tell me how to do it, otherwise I'm already confused with regular expressions for Django (Django 3.1) -
Complains about missing list_display when using TabularInline
Complains about missing list_display when using TabularInline. I want to add sorting for my sub-model. I use the SortableAdminMixin class and admin.TabularInline, but admin.TabularInline doesn't have the right field for SortableAdminMixin. When I try to write list_display = "all" nothing happens Complains about missing list_display when using TabularInline from adminsortable2.admin import SortableAdminMixin class ProjectStepInline(SortableAdminMixin, admin.TabularInline): model = ProjectStep min_num = 1 extra = 0 class ProjectAdmin(admin.ModelAdmin): inlines = [ProjectStepInline] console: if isinstance(self.list_display_links, (list, tuple)) and len(self.list_display_links) == 0: AttributeError: 'ProjectStepInline' object has no attribute 'list_display_links' -
Django custom queryset on django_filters.FilterSet
I made a recipe building django app. I want to search recipes that have a specific ingredient. Here is my model. class Recipe(models.Model): recipe_name = models.CharField(max_length=100) recipe_category = models.ForeignKey('components.RecipeCategory', on_delete=models.CASCADE,related_name='recipe_category') recipe_image = models.ImageField(blank=True, null=True, default="default.jpg", upload_to="recipe_pics/") recipe_instructions = models.TextField(blank=True, null=True) recipe_location = models.ForeignKey('components.RecipeBook', on_delete=models.CASCADE, related_name='recipe_location', blank=True, null=True) location_page_number = models.IntegerField(blank=True, null=True) ingredients = models.ManyToManyField('Ingredient', blank=True) recipe_rating = models.CharField(blank=True, null=True, default='good', choices=RECIPE_RATING, max_length=50) comments = models.TextField(blank=True, null=True) class Ingredient(models.Model): ingredient_name = models.ForeignKey('components.Food', on_delete=models.CASCADE, related_name='ingredient_name') ingredient_quantity = models.FloatField() quantity_unit = models.ForeignKey('components.MeasuringUnit', on_delete=models.CASCADE, related_name='quantity_unit') class Food(models.Model): food_name = models.CharField(max_length=100) food_category = models.ForeignKey('FoodCategory', on_delete=models.CASCADE, related_name='food_category') food_aisle = models.ForeignKey('Aisle', on_delete=models.CASCADE, related_name='food_aisle', blank=True, null=True, default=Aisle.get_default_pk) Here is my filterset form right now. I am currently only searching by recipe category. class RecipeFilter(django_filters.FilterSet): # The below code changes the default filter label to "ALL" recipe_category = django_filters.ModelChoiceFilter(queryset=RecipeCategory.objects.all(), empty_label="All") Here is my view class RecipeFilterList(FilterView): model = Recipe filterset_class = RecipeFilter context_object_name = 'recipes' template_name = 'recipe_filter' paginate_by = 10 def get_context_data(self, **kwargs): kwargs['current_page'] = self.request.GET.get('page', 1) return super().get_context_data(**kwargs) If I try and simply add ingredients to a Meta class in the FilterSet form, it displays every 'Ingredient' object which makes perfect sense. That only returns the single recipe that contains that exact Ingredient object. What I want … -
How to post data of checkbox by ajax Django?
How can i submit the is_read checkbox field into database using ajax? when i try to chick the checkbox field i am getting this error core.models.Article.DoesNotExist: Article matching query does not exist. models.py class Article(models.Model): title = models.CharField(max_length=300) is_read = models.BooleanField(default=False) views.py @csrf_exempt def Story_status_update(request): if request.method == 'POST': pk = request.POST.get('pk') item = Article.objects.get(id=pk) print(item) item.is_read = True item.save() return JsonResponse({'succes': True}, status=200) else: return JsonResponse({'succes': False, 'errors': []}, status=400) Html <tbody> {% for object in articles %} <tr data-pk="{{ object.id }}"> <td>{{ object.title }}</td> <td><input type="checkbox" data-id="{{ object.id }}" name="is_read" id="id_is_read" /></td> </tr> {% endfor %} </tbody> ajax.js $("#id_is_read").click(function () { var pk = $('tr').attr("data-pk"); $.ajax({ type: "Post", contentType: "application/json;", url: "{% url 'status-update' %}", data: { pk: pk }, dataType: "json", success: function (response) { console.log(response) }, }); }); -
How to monitor memory and abort python application?
I'm implementing a python application that curates data in datasheets. If these datasheets contain too many errors, the memory usage can reach the limit causing damage to the system. I want to know if there is a way to monitor the memory used by application and if it reaches a limit, for example, 45%, abort the application.