Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Really need help for this django formset
To all the pros out there, i really need help with this. 2 days ago my code work. Now its haywire. This line '$('#id_form-TOTAL_FORMS').attr('value', (parseInt (totalForms))-1);' is the issue. 2 days ago, without this line, everything works. The button to control the number of formset and its saved the number of data accordingly. But now without the same line, it cannot even control the counting properly. And to make it worst, it delete the last row of data whenever i saved. Here's what happen in detail: Upon loading the page, user can clone up to additional 3 formsets to key in data. So with the original one. Theres 4 rows in total. If user clicks save, all 4 rows get saved properly. If user never click save but instead click the '-' button on one of the row to remove the one of the row. It becomes 2 additional formsets and the original remaining. Total 3 rows of data. But if at this time user clicks save, it somehow delete one more additional formsets due to the line $('#id_form-TOTAL_FORMS').attr('value', (parseInt (totalForms))-1); But this morning, without using this line everything works perfectly let changeFlag=0; let maxrow = $('#id_form-MAX_NUM_FORMS').attr('value'); let totalForms = … -
How to implement filter and basic authentication in django rest framework?
In my project I use django rest framework. To filter the results I use django_filters backend. There is my code: models.py class Robot(models.Model): robot = models.CharField(max_length=100) short_Description = models.CharField(max_length=200) status = models.CharField(max_length=20) parameter = models.CharField(max_length=200) jenkins_job = models.CharField(max_length=100, default='JenkinsJobName') jenkins_token = models.CharField(max_length=100, default='JenkinsToken') def __str__(self): return self.robot class assignParameter(models.Model): parameterName = models.CharField(max_length=100, blank=True) assignRobot= models.ForeignKey(Robot, on_delete=models.CASCADE, related_name='param', blank=True, null=True) class jenkinsHistory(models.Model): jenkinsJobName = models.ForeignKey(Robot, on_delete=models.CASCADE, related_name='JenkinJobName', blank=True, null=True) jenkinsBuildNumber = models.CharField(max_length=100,blank=True) jenkinsBuildStatus = models.CharField(max_length=200,blank=True) errorMsg = models.CharField(max_length=500,blank=True) Param = models.CharField(max_length=500,blank=True, null=True) Serializers.py from hello.models import Robot,assignParameter,jenkinsHistory from rest_framework import serializers class assignParameterSerializer(serializers.ModelSerializer): class Meta: model = assignParameter fields = ['id', 'parameterName', 'assignRobot'] class jenkinsHistorySerializer(serializers.ModelSerializer): jenkinsJobName = serializers.SlugRelatedField(read_only=True, slug_field='robot') class Meta: model = jenkinsHistory # list_serializer_class = FilteredAssessmentsSerializer fields = ['id','jenkinsJobName','jenkinsBuildNumber','jenkinsBuildStatus','errorMsg','Param'] class RobotSerializer(serializers.ModelSerializer): param = assignParameterSerializer(many=True, read_only=True) # JenkinJobName = jenkinsHistorySerializer(many=True, read_only=True) class Meta: model = Robot fields = ['id', 'robot', 'short_Description', 'status', 'parameter', 'jenkins_job', 'jenkins_token', 'param'] and here's my view.py: from requests import api from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.filters import SearchFilter from django_filters.rest_framework import DjangoFilterBackend from django_filters import rest_framework as filters from hello.models import Robot,jenkinsHistory from hello.api.serializers import RobotSerializer, jenkinsHistorySerializer @api_view(["GET", "POST"]) def robot_list_api_view(request): if request.method == "GET": rb = Robot.objects.all() … -
django views.py IP recorder append not working
In my https://fr0gs.pythonanywhere.com site, I've created an IP address recorder to record the IP addresses of people coming into the site. But the log file is blank! from django.shortcuts import render from datetime import datetime # Create your views here. from django.http import HttpResponse def get_ip_address(request): """ use requestobject to fetch client machine's IP Address """ x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') ### Real IP address of client Machine return ip def homePageView(request): try: alip = open('alip.txt', 'a') alip.write(f'''{datetime.now()} : {get_ip_address(request)} ''') alip.close() except: alip.close() return HttpResponse(f'''{get_ip_address(request)} : {datetime.now()} Hello, World!''') -
how to take input field from django auth login form for javascript validation
Can I Create a custom user signup form with my own custom fields and do performing signup and signin without taking UserCreationForm? Plz. suggest me -
how to concatenation django query set with And & OR operator
This is my concatenation code but its not working ,how to concatenation django queryset with AND & OR operator enter code here sales_by_branch = OrderItems.objects.values('order__entity__id').order_by('order__entity__id').annotate(total_amount=Sum('total_price')).filter(order__is_approved=True).filter(order__is_success=True) v=0 subset=[] for product_id in product_id: product_id = int(product_id) product_code = ProductCodes.objects.values('flavour_id','product_id','quantity_id').filter(id=product_id) if product_code: for item in product_code: flavour_id =item['flavour_id'] product_id =item['product_id'] quantity_id =item['quantity_id'] if v==0: sales_by_branch = sales_by_branch.filter(flavour_id=flavour_id,product_id=product_id,quantity_id=quantity_id) else: subset = OrderItems.objects.filter(flavour_id=flavour_id,product_id=product_id,quantity_id=quantity_id) ales_by_branch = sales_by_branch | subset v=v+1 -
Wagtail - adding CSS class or placeholder to form builder fields
I'm trying to add css classes (for column width) and placeholder text to my Wagtail form fields via the Wagtail admin form builder. I've tried using wagtail.contrib.forms and also the wagtailstreamforms package to no avail. I know it says here that the Wagtail forms aren't a replacement for Django forms. However, without such basic functionality it's limited in its usefulness. -
DoesNotExist at /cart/ OrderStatus matching query does not exist
[Screenshot of the webpage showing error][1] It is showing that the urls path is not correct despite all the corrections made in the code. [1]: https://i.stack.imgur.com/sAoyV.png`from django.contrib import admin from django.urls import path from django.conf.urls import url, include from .import views from django.contrib.auth import views as auth_views from django.views.generic import RedirectView urlpatterns = [ url(r"^admin/admin_update_quantities/$", views.adminUploadQuantities, name="adminUploadQuantities"), url(r"^accounts?/login/$", views.LoginView.as_view(), name="account_login"), url(r"^accounts?/signup/$", views.SignupView.as_view(), name="account_signup"), url(r"^accounts?/password_change", auth_views.PasswordChangeView.as_view( template_name='account/password_change.html'), name="password_change"), url(r"^password_change_done", auth_views.PasswordChangeView.as_view( template_name='account/password_change_done.html'), name="password_change_done"), url(r"^accounts?/", include("account.urls")), url(r'^$', views.itemList, name='itemlist'), url(r'^getitems$', views.getItems, name='getItems'), url(r'^getitemarray$', views.getItemArray, name='getItemArray'), url(r'^addtocart$', views.addToCart, name='addToCart'), url(r'^setincart$', views.setInCart, name='setInCart'), url(r'^getitemprices$', views.getItemPrices, name='getItemPrices'), url(r'^getcartsum$', views.getCartSum, name='getCartSum'), url(r'^getcart$', views.getCart, name='getCart'), url(r'^getinvoicepdf$', views.getInvoicePdf, name='getInvoicePdf'), url(r'^invoice/$', views.getInvoicePdf, name='getInvoicePdf'), url(r'^getinvoice', views.getInvoice, name='getInvoice'), url(r'^getdelivery', views.getDelivery, name='getDelivery'), url(r'^gettotal', views.getTotal, name='getTotal'), url(r'^getminordersum', views.getMinOrderSum, name='getMinOrderSum'), url(r'^endoforder/', views.endOfOrder, name='endOfOrder'), url(r'^myorders/', views.orderList, name='orderList'), url(r'^cart/$', views.cart, name='cart'), url(r'^item/(?P<itemSlug>\w+)', views.itemPage, name='item'), url(r'^itemlist/$', views.itemList, name='itemlist'), url(r'^itemlist/(?P<cls>\w+)', views.itemListSelection, name='itemlistselection'), url(r'^login/$', RedirectView.as_view(pattern_name='account/login')), url(r'^order/$', views.makeOrder, name='order'), url(r'^about/$', views.about, name='about') ] ` -
Page not found (404) The current path, firstapp/about/, didn’t match any of these
Sorry if there is any problem with my language my English is very bad when i goto http://127.0.0.1:8000/firstapp/about/ page showing this error enter image description here This is my code views.py from django.shortcuts import render from django.http import HttpResponse from . models import * def home(request): student = Student.objects.all() return render(request, 'index.html',{'student':student}) def about(request): student = Student.objects.all() return render(request, 'demo.html',{'student':student}) def service(request): return HttpResponse("<h3>hai this is service page</h3>") firstapp/urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='next'), path('about/', views.about, name='about'), path('service/', views.service, name='service'), ] urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('firstapp', include('firstapp.urls')), ] what am missing or whats the error -
Model instances are not rendering into template
Orders and OrderItems are successfully added to the table, but the products are not being shown to the template. If i use print(order_item.objects.all()) , it gives an error saying : AttributeError: Manager isn't accessible via OrderItem instances. In django-admin database, the products are being nicely added and removed from the cart. Currently, these are my order items: Order item 3 of Saregama Carvaan Earphones GX01 with Mic 5 of JBL Flip 5 3 of Puma Unisex-Adult BMW MMS R-cat Mid Sneaker 4 of Adidas Men's Astound M Running Shoe 4 order items These order items are from admin user. html: {% block content %} <main> <div class="container"> <div class="table-responsive text-nowrap"> <h2>Order Summary</h2> <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">Item title</th> <th scope="col">Price(₹)</th> <th scope="col">Quantity</th> <th scope="col">Total Item Price</th> </tr> </thead> <tbody> {% for order_item in order.items.all %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{ order_item.item.product_title }}</td> <td>₹{{ order_item.item.sale_price }}</td> <td> <a href="{% url 'remove-single-item-from-cart' order_item.item.slug %}"><i class="fas fa-minus mr-2"></i></a> {{ order_item.quantity }} <a href="{% url 'add-to-cart' order_item.item.slug %}"><i class="fas fa-plus ml-2"></i></a> </td> <td> {% if order_item.item.discount %} ₹{{ order_item.get_total_discount_item_price }} <span class="badge badge-primary">Saving ₹{{ order_item.get_amount_saved }}</span> {% else %} ₹{{ order_item.get_total_item_price }} {% endif %} <a style='color: red;' href="{% url … -
Display MultipleChoiceField in template of django
I have a charField with MultipleChoiceField formfield ! And its perfectly opens a dropdown by which we go do multiple select options. And the problem is that it stores the value as array like ['option1','option2'] When i display this on template, it display the whole array but i want to get the option1 and option2 and display horizontally like option1, option2 ! How to do this ? My code : class Univ(models.Model): education_level = models.CharField(max_length=20) & in form: class Univform(ModelForm): education_level = forms.MultipleChoiceField(choices=EDU_LEVEL) How to deal this and display ? -
Which back-end language I should choose PHP or nodeJS for API creation and for back-end solutions
I am a mobile application developer and I want to learn any back end language for the creation of API. I am in doubt, which language I should learn ? Please give your reviews and suggestions because I am in confusion. -
how to handle message in on_message mqtt paho if multiple message came at same time
return_message = "" def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe(topic) def on_message(client, userdata, message): global return_message print("received data is :") return_message = message.payload client = mqtt.Client("user") client.on_connect=on_connect client.on_message=on_message client.connect(broker,port,60) client.loop_start() the return_message is a global variable. getting the message when there is only one message at a time. but i need to handle multiple messages at a time. how to handle this. if i declared return_message as an array then also i think there will be data loss . is there any better way to do this. i need to pass the return message value to other files also. how to do this -
django 'QuerySet' object has no attribute '_set'
I'm working on the code using the django framework. I want to solve this. workspaces = Workspace.objects.get(id=workspace_id) athenbs = workspaces.athenb_set.all().filter(id=athenb_id) alerts = athenbs.alert_set.all().filter(id=athenb_id) But there's this error. alerts = athenbs.alert_set.filter(id=athenb_id) AttributeError: 'QuerySet' object has no attribute 'alert_set' What should I do??? -
Django localhost returns ok but curl localhost returns the 404 error
The localhost of a Django app runs normal on an AWS server like the following: (env) manage.py runserver 0.0.0.0:8000 Performing system checks... System check identified no issues (0 silenced). Django version 2.2, using settings 'xyz.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. The curl -i localhost is returning the 404 error. (env) $ curl -i localhost HTTP/1.1 404 Not Found Server: nginx/1.14.0 (Ubuntu) Content-Type: text/html Content-Length: 178 Connection: keep-alive <html> <head><title>404 Not Found</title></head> <body bgcolor="white"> <center><h1>404 Not Found</h1></center> <hr><center>nginx/1.14.0 (Ubuntu)</center> </body> </html> What does this mean? Does it mean the Django app was installed ok but the Nginx is not working properly? What do I check them out? The tech stack is Django/Python/gunicon/Nginx on Ubuntu 18. -
Django value too long for type character varying(50)
I am trying to create a Site object. http://test-ecommerce-project-dev.us-west-1.elasticbeanstalk.com/ And when I try to create a new Site with the above domain, I got this error value too long for type character varying(50) i think this is caused because my domain is too long. But I don't know how to solve it. I thought of overriding Site class, but i don't know how to do it either. Any ideas appreciated. -
account/register not found in django project
I am new to django and started with a basic. The problem is while following a tutorial I created an account app that has a register page. For some reason whenever I am trying to go to my register page, django tells me that it doesn't match any of the paths. below is the given code: accounts app url.py from django.urls import path from . import views urlpatterns = [ path('register', views.register, name="register") ] accounts app's views from django.shortcuts import render def register(request): return render(request, 'register.html') register.html is: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Registeration</title> </head> <body> <form action="register" method = "post"> {% csrf_token %} <input type= "text" name="first_name" placeholder="First Name"><br> <input type= "text" name="last_name" placeholder="Last Name"><br> <input type= "text" name="username" placeholder="UserName"><br> <input type= "text" name="password1" placeholder="Password"><br> <input type= "text" name="password2" placeholder="Verify Password"><br> <input type= "submit"> </form> </head> <body> </body> </html> ``` web_project urls.py ``` from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("", include('travello.urls')), path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), ] urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) the error I am getting is given below: Page not found (404) Request Method: … -
How to create a customized filter search function in Django?
I am trying to create a filter search bar that I can customize. For example, if I type a value into a search bar, then it will query a model and retrieve a list of instances that match the value. For example, here is a view: class StudentListView(FilterView): template_name = "leads/student_list.html" context_object_name = "leads" filterset_class = StudentFilter def get_queryset(self): return Lead.objects.all() and here is my filters.py: class StudentFilter(django_filters.FilterSet): class Meta: model = Lead fields = { 'first_name': ['icontains'], 'email': ['exact'], } Until now, I can only create a filter search bar that can provide a list of instances that match first_name or email(which are fields in the Lead model). However, this does now allow me to do more complicated tasks. Lets say I added time to the filter fields, and I would like to not only filter the Lead model with the time value I submitted, but also other Lead instances that have a time value that is near the one I submitted. Basically, I want something like the def form_valid() used in the views where I can query, calculate, and even alter the values submitted. Moreover, if possible, I would like to create a filter field that is not … -
TypeError while running Python manage.py runserver command
I'm new to Python/Django and trying to launch a virtual environment in this project for the first time. When entering the final command - 'python manage.py runserver'- I am getting a TypeError: (myenv) C:\Users\katie\bounty>python manage.py runserver Traceback (most recent call last): File "C:\Users\katie\bounty\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\katie\bounty\myenv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\katie\bounty\myenv\lib\site-packages\django\core\management\__init__.py", line 345, in execute settings.INSTALLED_APPS File "C:\Users\katie\bounty\myenv\lib\site-packages\django\conf\__init__.py", line 83, in __getattr__ self._setup(name) File "C:\Users\katie\bounty\myenv\lib\site-packages\django\conf\__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "C:\Users\katie\bounty\myenv\lib\site-packages\django\conf\__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "c:\users\katie\appdata\local\programs\python\python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\katie\bounty\bounty\settings.py", line 173, in <module> AWS_S3_CUSTOM_DOMAIN = AWS_STORAGE_BUCKET_NAME + '.s3.us-east-2.amazonaws.com' TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' I'm not sure how I could have caused the error since I haven't done anything other than clone the repository and work to launch the virtual environment in command prompt. I also tried python3 manage.py runserver but then received the error: … -
How to create multiple directory in django template folder?
I want to change php website into django. In php, we have controller and view folder. Inside view, I have many folder in view. View --- Users --- user1.ctp --- user2.ctp --- Layouts --- layout1.ctp --- layout2.ctp Now I am using django this is how my directory looks MyProject --- myapp --- views.py --- urls.py --- migrations --- __pycache__ --- static --- myapp --- mycss.css --- templates --- myapp --- Users --- user1.html --- user2.html --- Layouts --- layout1.html --- layout2.html --- MyProject Whenever I am putting user1.html inside /templates/myapp, I am able to render but I want to put Users related file in Users folder. I am getting template does not exist urls.py (Inside myapp) from django.contrib import admin from django.urls import path from django.urls.conf import include from . import views,login urlpatterns = [ path("",views.index), ] urls.py (Inside MyProject) urlpatterns = [ path('admin/', admin.site.urls), path('',include('myapp.urls')), ] -
How do i ensure I have unique ids within a loop in a template
I have the queryset from a formset which is something like this {[Item 1],[Item 2]}. To display them, i loop thru them in the template. But due to the loop, i have warning that my div have same ids. Can anyone suggest what to do? I can just leave it like that if my page purpose is to display the data only. But the page purpose is to view and update the data and correct me if im wrong, the div with identical ids will affect the update to the database. -
How to fix the error: 'This XML file does not appear to have any style information associated with it'
I hosted a small django project on virtual machine on digital ocean. Before I started using digital ocean to serve static files everything worked fine. But immediately I created a storage space and push my static files there the static files are not being served on the webpage, including django admin page (the project pages are showing net::ERR_ABORTED 403 (Forbidden). I have already installed django_storages and boto3. I got some hint as to the possible cause of the problem when I clicked on digital ocean aws bucket url that looks like https://django-space-storage.nyc3.digitaloceanspaces.com. When I cliked on it I got the following error: This XML file does not appear to have any style information associated with it. The document tree is shown below. It seems the browser is rendering my django pages as xml instead of html. I might be wrong with this assumption because I'm finding a hard time trying to understand what is actually going on. My question is, how do I cause the browser to render my django pages as html instead of xml? -
Python script to web page
I’ve done some research about turning a python script that I have written into an HTML web page. My experience with HTML is somewhat limited, but from what I can tell, I would have an HTML file, and would incorporate Django into said HTML file. Is it as simple as putting something in the HTML file like <p> The function call is: <> myFunctionCall() </><> Or is there a lot more to it than that? -
You're accessing the development server over HTTPS, but it only supports HTTP. code 400, message Bad request syntax
I just started learning Django framework, and I tried to deploy my first project on the server from DigitalOcean. If I run python3 manage.py rumserver 0.0.0.0:8000 The server launches. However, once I try to access it from (my-rent-ip):8000 I get this: [25/Aug/2021 01:49:01] code 400, message Bad request syntax ('\x16\x03\x01\x02\x00\x01\x00\x01ü\x03\x03GÛî}ز\x921\x0e\x94\x17\x9cÏe¹\x88ñÿÃ\x16\x01éÖRÝ\x00\x95F\x8aG\tÉ 8¯,úÂ\x93´ù\x06Ý\x14¾z\x13Âe4[\x9a,.æ\x96+$<~\x8eq<´\t\x00"ZZ\x13\x01\x13\x02\x13\x03À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x00') [25/Aug/2021 01:49:01] You're accessing the development server over HTTPS, but it only supports HTTP How is this possible if I run production server, not a development one? I might be doing something wrong with the setting.py since it had to be changed a lot for the production purposes. I made a production branch, changed settings.py file, and cloned to the server using GitHub. Here it is: from pathlib import Path from dotenv import load_dotenv #for python-dotenv method load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! import os SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False' ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ … -
Run celery inside a docker container in production (plesk)
I am trying to use celery with docker in plesk, plesk (no support for using docker-compose) can i run celery inside my container for production use? -
How do I return a value from database to template?
I have a database which uses formset to help store data. How do i get the ‘value’ of the numbers of data in the template. Like example i got a queryset of {[Item 1],[ Item 2]}. How do i get the value of 2 in the template to tell me theres 2 items? I want to use this value to control the amount of stuff i can clone with a click of the button. Im using django for the web