Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle multiple forms in django
Here i have two forms within my single page.I have a list of categories info in some table and i have two different action with POST request.One is to delete the single category object and another is to delete the checked objects. But deleting the single object is not working after placing two forms together.Before there was no form for deleting selected categories so the deleting the single object was working fine with the modal but when i used two form then even if i click the delete single category link then it is performing the delete selected category view and says no category selected. How can i handle two forms here.I have given two different names in a submit button and two different actions also. def delete_category(request, pk): category = get_object_or_404(Category, pk=pk) if request.method == 'POST' and 'single-delete' in request.POST: category.delete() messages.success(request, '{} category deleted.'.format(category.title)) return redirect('view_categories') else: messages.error(request,'Invalid request') def delete_selected_categories(request): selected_categories = Category.objects.filter(id__in=request.POST.getlist('categories')) if selected_categories: if 'delete_selected' in request.POST: count = selected_categories.count() selected_categories.delete() messages.success(request, '{} categories deleted.'.format(count)) return redirect('view_categories') else: messages.info(request, 'No categories selected.') return redirect('view_categories') template <div class="table-responsive"> <form action ="{% url 'delete_selected_categories' %}" method="post"> {% csrf_token %} <table> {% for category in categories %} <tr> … -
Django: bulk update from a list of dicts without constructing the whole query set
I have a list which contains dicts. Something like: [{'id': 0, 'price': 20}, {'id': 1, 'price': 10}] # a few thousands of elements how can I update corresponding models without constructing the whole QuerySet? -
django app deployment in apache not working from an anaconda3 environment in windows
Hello guys I was trying to deploy my django app in apache and configured an ssl license. I cannot get any rest framework apis from django only the wampserver main page. I think my issue is that I am using a conda environment and not a virtualenvironment and I couldn't find any links to configure it for windows. Can someone guide me through this? httpd.conf # # This is the main Apache HTTP server configuration file. It contains the # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> # for a discussion of each configuration directive. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot is prepended -- so "logs/access_log" # with ServerRoot set … -
How to run wsgi along the side of the daphne for django channels
i am using django channels in my project using using official django channels v2, my simple channels app is completed and working fine if run python manage.pr runserver but i want to run django channels in different port so i am now using daphne using daphne my_project.asgi:application --port 8001 it working fine in 8001 port and i also run python manage.py runserver in another terminal parallely working fine. now my both channels in 8001 and django in 8000 port working correctly but my runserver command running ASGI/Channels instead of wsgi development server, Starting ASGI/Channels version 2.2.0 development server at http://127.0.0.1:8000/ settings.py ASGI_APPLICATION = 'my_project.routing.application' WSGI_APPLICATION = 'my_project.wsgi.application' if i debug any function in views.py request, it is ASGI request instead of django wsgi request my question is: how to get django request instead of ASGI or if we install django channels every request become ASGI request? what is the use of the python mange.py runworker command -
how can I fix"is not recognized as an internal or external command, operable program or batch file" in windows10
hi I created a django project on desktop after that I cut it's file and paste it in :C but when I want to activate my virtualenv in cmd I get the bellow error. ('hyperDesign' is not recognized as an internal or external command, operable program or batch file) 'hyperDesign' is the name of my virtualenv file. -
Django MEDIA_URL is not serving the file on the local server
I have MEDIA_ROOT and MEDIA_URL in my settings.py. MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I am uploading files to uploaded_files = models.FileField(upload_to='uploads/%Y/%m/%d/') I also have defined this in my url.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The files are getting saved correctly but while accessing them I am getting 404. Any idea, what might be going wrong here. Thanks. Using the URLconf defined in assemblyautomation.urls, Django tried these URL patterns, in this order: admin/ genplansheet/ ^static/(?P<path>.*)$ The current path, media/uploads/2019/09/05/1125sft_sold.xlsx, didn't match any of these. -
You are trying to add a non-nullable field stock without a default
I have added a new field in my model but after that I have deleted db.sqlite3 (to ensure I don't get error below) agrawalo@:~/myapp> ls README.md config core manage.py requirements.txt But still I get this error when I run makemigrations agrawalo@:~/myapp> ./manage.py makemigrations You are trying to add a non-nullable field 'high52' to stock without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py -
Sending multiple get requests to multiple hosts simultaneous
Checked many questions here and can't find proper answer. What i have now, works. Just need to speed it up. What i have now is one function in views.py that a) gets list of hosts b) sends get request to hosts from the list one by one and if connection is successful it adds host to array. c) takes new array (with online hosts) and send requests to all "online hosts". I would like to focus on b) point def host_tst_online(request): abc_hosts = Host.objects.all() tsthost = Host.objects.filter(abcenv='tst').order_by('abchostname') tsthostonline = [] arr = [] ######################################## ######Check which hosts are online###### ######################################## for xyz in tsthost: try: response1 = requests.get( 'https://{}:6666/abc/api/v1/about'.format(xyz), verify='/cert/cacerts.pem', headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxx'}, timeout=1 ) if not response1.status_code == 401: tsthostonline.append(xyz) else: print('all ok') except (ConnectionError, ConnectTimeout) as e: print(e) response = "No response" ########################################################################### ##########Send request to all hosts from tsthostonline array############### ########################################################################### if request.method == 'POST': send_form = SendersFormO(request.POST) if send_form.is_valid(): abcsend = send_form.cleaned_data.get('abcsend') send_form = SendersFormO() for eee in tsthostonline: response = requests.get( 'https://{}:6666/abc/api/v1/objects/abcsend?id={}'.format(eee, abcsend), verify='/cert/cacerts.pem', headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxxx'}, ).json() for key in response['data']: arr.append(key) context = {'response': response, 'arr': arr, 'send_form': send_form, 'tsthostonline': tsthostonline} return render(request, 'app/json_nest_send_online.html', context) else: send_form = SendersFormO() … -
Deploying django site
I want to deploy my first django site. Which will likely have 100 visitors a day ( just starting ). Database requirements are also very low ( like 100 user information ). Is there any way I can deploy it for free if not then please suggest something with low price without subdomain? (I have been thinking about heroku or python anywhere but I don't want to include subdomain and aws or google cloud pricing is not efficient for low traffic if I want cheap pricing ) -
custom dynamic list_filter with Django SimpleListFilter
According to Django document it is possible to write custom list filter by creating "a class inheriting from django.contrib.admin.SimpleListFilter, which you need to provide the title and parameter_name attributes to and override the lookups and queryset methods, e.g." some thing like this: from datetime import date from django.contrib import admin from django.utils.translation import gettext_lazy as _ class DecadeBornListFilter(admin.SimpleListFilter): title = _('filendName_amount') parameter_name = 'amount' filed_name = 'filed_name' compare_value = 100000 def lookups(self, request, model_admin): return ( ('mt', _('more than ') + str(self.compare_value)), ('lt', _('less than ') + str(self.compare_value)), ) def queryset(self, request, queryset): kwargs = {} if self.value() == 'mt': kwargs = { '{0}__{1}'.format(self.filed_name, 'gte'): self.compare_value, } if self.value() == 'lt': kwargs = { '{0}__{1}'.format(self.filed_name, 'lte'): self.compare_value, } return queryset.filter(**kwargs) It works fine. But is it possible to pass the filed_name and the compare_value to create more dynamic list filter? -
I cannot fetch data
views.py def home_page(request): context = Add.objects.aggregate( bud=Sum('budget'), exp=Sum('expense'), budexp=Sum('budget')-Sum('expense')) return render(request, 'home.html', context,) def list_page(request): qs = Add.objects.all() context = {'qs':qs} return render(request, 'list.html', context,) when i remove qs = Add.objects.all() and context if this page at that time my list_page work fine other wise indention error that happens because of def home_page code. How to solve this problem i just want to see all data on list_page. -
DRF: data is not passing to kwargs in patch method
I am creating a update comment view for my app. This is my code: serializer.py class CommentSerializer(serializers.ModelSerializer): class Meta: model = FitnessRecord fields = ('comment', 'id') views.py class AddCommentView(APIView): permission_classes = [IsAuthenticated] def patch(self, request, *args, **kwargs): print(kwargs) # this is printing {} instance = get_object_or_404(FitnessRecord, pk=kwargs.get('id')) # error line print(22222) # not printing serializer = CommentSerializer(instance, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(CommentSerializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I am using postman to send data. this is the error: { "detail": "Not found." } This may be because kwargs is blank. I am passing this data. { "comment": "gotham#bw9", "id": 14 } This is DRF setting if required. REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DATE_INPUT_FORMATS': ['%d-%m-%Y'], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'TEST_REQUEST_DEFAULT_FORMAT': 'json' } -
Get only text in RichTextField in CKEditor?
I'm a newbie. I'm using Django to write a personal blog. I'm using CKEditor to be able to insert images into my blog post. However, I want to show some first words of the posts on the homepage which does not include the images in the posts. I want to know if there is a way that I can get text only from RichTextField in CKEditor. I don't have enough reputation to post images. This is my current preview content: https://i.imgur.com/XJR13pH.png I want it to be like this (no images): https://i.imgur.com/eRaIWzy.png This is my current code: https://i.imgur.com/54IV7s3.png -
In select tag values passing as value="<ul id=" id_process" in django
Using CheckboxSelectMultiple widget in the forms, The select tag value attribute is automatically not generating properly the Inspect(F12) code is given below <select name="process" required="" class="valid"> <option value="<ul id=" id_process"></option> </select> How can I pass id in the value attribute -
I need to crop a pdf file and get the dimention in web page
I'm creating a web application for getting the dimension of pdf in Points(measurement), where i need to crop our require area using rectangular and get those dimension I tried to get create a pdf cropper but mostly there is only image cropper existing -
Problem with getting the select option data
I am having problem to get the selected data from a form. Here is my form <form action="#" method="GET"> {% csrf_token %} <select name="country" id="selectcountries" class="custom-select"> <option>Select country</option> {% for item in countries %} <option val="{{ item.name }}"> {{ item.name }} </option> {% endfor %} </select> <select name ="city" id="selectcities" class="custom-select"> <option>Select city</option> </select> <select class="custom-select" name="option" > <option selected> Tourist Spot </option> <option> Hotel </option> <option> Restaurent </option> </select> <button type="submit" class="btn tour-btn"><i class="fa fa-search pr-2" aria-hidden="true"></i> <a href="{% url 'advanceSearch' %}"> Search </a></button> </form> And my views.py is def advanceSearch(request): country = request.GET.get('country') city = request.GET.get('city') option = request.GET.get('option') if request.method == "GET" : if country: message = 'q= %s' % country else: message = 'Empty' else: message = 'fucking sheet' return HttpResponse(message) HTTPResponse always give me empty message even after with passing values by the form. I want to get the data from this form but i cant. -
how to show foreign key value instead of its ID
i'm try to display foreign key value , but it instead return the id , in template models.py class Product(models.Model): product_name = models.CharField(unique=True, max_length=50) pass def __str__(self): return self.product_name class Order(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') pass def __str__(self): return str(self.products.all()) class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True) pass def __str__(self): return str(self.product) this is my views.py class ListOfOrder(ListView): template_name = 'order/product_group.html' context_object_name = 'productss' def get_queryset(self): return ProductOrder.objects.all() template.html {% for product in productss %} <tr class=""> <td style="text-align: center;">{{ product.product }}</td> {% endfor %} i expected to display the product name but it instead displayed the ID of the product thanks for your answer -
Django Serializer access json data from post string indices must be integers
I'm trying to create Serializer for a register post request's validation The json that send to the API with the POST request: { "username": "dat@icts.vn", "password": "123456", "confirm_password": "123456" } My serializer for validation: class RegisterSerializer(serializers.Serializer): username = serializers.EmailField(required=True) password = serializers.CharField(required=True) confirm_password = serializers.CharField(required=True) def validate_username(self, username): existing_email = User.objects.filter(email=username).first() if existing_email: raise serializers.ValidationError("Email already registered") return username def validate_confirm_password(self, data): if data['password']: if data['confirm_password'] != data['password']: raise serializers.ValidationError("Confirm password not match password") return data['confirm_password'] My view register function: @csrf_exempt @require_http_methods(["POST"]) def register(request): received_json_data=json.loads(request.body) valid_ser = RegisterSerializer(data=received_json_data) if valid_ser.is_valid(): post_username = received_json_data["username"] post_password = received_json_data["password"] user = User.objects.create_user(username=post_username,password=post_password) user.save() refresh = RefreshToken.for_user(user) content = { 'refresh': str(refresh), 'access': str(refresh.access_token), } return JsonResponse(content) else: return JsonResponse({'code':'400','errors':valid_ser.errors}, status=400) When i send the POST request i get the following error: File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner web_1 | response = get_response(request) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response web_1 | response = self.process_exception_by_middleware(e, request) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response web_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) web_1 | File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view web_1 | return view_func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.6/site-packages/django/views/decorators/http.py", line 40, in inner web_1 | return func(request, *args, **kwargs) web_1 | File "/app/api/views.py", line … -
Bullet points from model
I have a "Product" model. I want to have a <ul> in my product detail template to list product features. How can I list features of a certain product in a <ul>? product_detail.html <ul class="mb-0"> <li class="mb-2">lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li> <li class="mb-2">donec pede justo, fringilla vel, aliquet nec.</li> <li class="mb-2">phasellus ullamcorper ipsum rutrum nunc. </li> </ul> -
Django Mailing failure: Connection to rabbitmq broker lost
I am trying to integrate a mailing feature in my shopping app which would mail to users notifying their order has been placed. I am using Celery for asynchronous tasks, rabbitmq as my message broker and Flower to monitor the tasks. But after placing the orders, the mail is not being sent and Flower Dashboard shows that the task has failed. I marked an error which I got into my Celery terminal: File "c:\users\acer\appdata\local\programs\python\python36\lib\site-packages\amqp\transport.py", line 438, in _read s = recv(n - len(rbuf)) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host and finally it shows: [2019-09-05 09:57:40,404: WARNING/MainProcess] consumer: Connection to broker lost. Trying to re-establish the connection.. my tasks.py file: from celery import task from django.core.mail import send_mail from .models import Order @task def order_created(order_id): """ Task to send an e-mail notification when an order is successfully created. """ order = Order.objects.get(id=order_id) subject = 'Order nr. {}'.format(order.id) message = 'Dear {},\n\nYou have successfully placed an order.\ Your order id is {}.'.format(order.first_name, order.id) mail_sent = send_mail(subject, message, 'seller@admin.com', [order.email]) return mail_sent I am not able to figure out what's wrong. Any help would be appreciated :) -
How to find which item of table is selected?
I have a table like this in my UI. <table> <thead> <tr> <th>DELETE</th> <th>EDIT</th> <th>No</th> <th>Name</th> </tr> </thead> <tbody id="bodyTable"> {% for item in person_list %} <tr> <td> <a href="#"> Delete </a> </td> <td> <a href=""> EDIT </a> </td> <td>{{item.person_no}}</td> <td>{{item.person_name}}</td> </tr> </tbody> </table> and there is to option "EDIT" and "DELETE" for my tables items. and I want to know how to find with an item that is clicked for DELETE or EDIT? that item should be removed from database or edited, so i need find which item is clicked and send that id to my views. -
Login after successful registration Doesn't work in Django
I have a problem when I register in the site with a new user does not log in the site after registration as in the following code if formRegister.is_valid(): username = formRegister.cleaned_data.get('username') password = formRegister.cleaned_data.get('password') user=formRegister.save() #u= User.objects.get(username=request.POST.get('username')) userAthen = authenticate(request,username=user.username, password=user.password) if userAthen is not None: login(request, userAthen) return redirect('/') -
Display nested many-to-many fields in template as checkboxes
Im new to django and Im working on a website to generate engineering change documentation to support product design activity. I have three models with nested 'many to many' fields. when starting document generation, I ask the user to select the chassis for which the document will be generated, once the chassis is selected I want to display a form with all the fields from "DocDetials" model and a table showing all the boards available for the selected chassis as checkboxes, so that the user can select which board to apply the changes to. I can display most of DocDetails fields in a template using views, and get the data after summit. I just need to be able to display and select the boards for corresponding chassis. knowing which 'chassis' the user selected is done, lets asume the form sent to the view has the selected 'chassis' as default. I have been looking for a way to do this for days, have tried several approaches but haven't been able to do this. there are a lot of answers about how to display one tier many-to-many files, but nothing about NESTED many-to-many fields. I have not found a related solution here … -
Django Raw SQL Query - How to pull value via column (instead of tuple index) from SELECT query
I'm executing a fetchall() raw SQL query in Django (1.11) with a PostgreSQL data source. The result returns a tuple. My concern is that I can only seem to fetch a row's field via the tuple index i.e. row[2] (or in template I would do {{row.2}}). But I want to be able to use the actual field name instead of index i.e. row.itemno (or in template I would do {{row.itemno}}) I tried doing row.first_name but it says 'list' object has no attribute 'itemno' Is it or isn't it possible to use field names with this result? Here's a sample in python shell: P.S. You might be wondering why I'm still using Django 1.11... It's because we are using DjangoCMS and unfortunately, it supports up to 1.11 only... -
How to add views to the Browsable API Root?
When working with the Browsable API in Django Rest Framework the API root only appears to list responses for ViewSets registered via a router. For example, in the code below users and accounts would show, but not forgot-password: router = routers.SimpleRouter() router.register(r'users', UserViewSet) router.register(r'accounts', AccountViewSet) urlpatterns = [ url(r'^forgot-password/$', ForgotPasswordFormView.as_view()), ] urlpatterns += router.urls How can I add a hyperlink for forgot-password to the base API root?