Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django when a data is entered, write the data in the other model depending on the condition
Hello There is a data(text) in data b on app1. I want to write the data here on d on app2. how can I do that? app.model; class Post(models.Model): a=models.CharField() b=models.TextField() app2.model; class Post2(models.Model): c=models.CharField() d=models.TextField() -
The term 'telnet' is not recognized as the name of a cmdlet, function, script file, or operable program
I'm working on a, specifically sending emails in cmd that makes use of telnet. Unfortunately, I can't start it. I'm receiving the "The term 'telnet' is not recognized as the name of a cmdlet, function, script file, or operable program" from cmd when I type telnet. Can someone please tell me on what to install and its procedures for me to access telnet command in CMD. Thanks! -
Syntax Error when deploying django on apache2
I am trying to host a django application on a server using apache2 and mod_wsgi. The project itself is located at the path /usr/share/django-projects/mysite The virtual environment is located at the path /home/zakhar/django_test/env It's part of apache2 (2.4 version) conf file. In venv python version is 3.8.13 WSGIDaemonProcess mysite user=www-data group=www-data python-path=/usr/share/django-projects/mysite:/home/zakhar/django_test/env/lib/python3.8/site-packages python-home=/home/zakhar/django_test/env It's last error from apache arror.log File "/home/zakhar/django_test/env/lib/python3.8/site-packages/django/db/models/aggregates.py", in line 84 if (default := c.default) is None: ^ SyntaxError: invalid syntax I think apache use python 3.6.9 in global env, but not in venv I would be very grateful if someone could help me -
ERROR:: --system is intended to be used for pre-existing Pipfile installation, not installation of specific packages. Aborting
I finished my django project.And ı want to deploy my project on aws.I pulled from github my project and then on virtual computer on aws(ubuntu) run pipenv install,I am getting this error every time. ERROR:: --system is intended to be used for pre-existing Pipfile installation, not installation of specific packages. Aborting. How can I fix that -
How to bind a function to an html button without a form in Django
I'm new to Django and I need to bind a function from python to a button using onclick from a file views.py. I saw a lot of discussions where they do this with forms, but I want to do without them index.html: <div class="submit"> <button type="button" name="submit" onclick="">Get Info</button> </div> views.py: from django.shortcuts import render def index(request): return render(request, 'index.html') def get_info(): print("It works") Need to bind get_info() -
Is it able to resume downloading when the connection is lost in Django?
from django.http import FileResponse def send_file(): #some processes response = FileResponse(open(file_name, 'rb'),as_attachment=True) return response The connection sometimes lost. I want to resume downloading the file. How can I do that? Many thanks. -
how do I make a page only to be accessed through redirection from a stripe checkout session page, in django?
I want a page (view) to be only accessed through redirection from stripe checkout session page, and not accessible in any other way. Here is the page that I want to only be accessed through redirection from the stripe checkout session page: def successView(request): data = cartData(request) cartItems = data['cartItems'] context = {'cartItems':cartItems} return render(request, 'store/success.html', context) Here is the stripe checkout session page that redirects to the page: class CreateCheckoutSessionView(View): def post(self, request, *args, **kwargs): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] line_items_list=[] for item in items: quantity=item['quantity'] price_stripe=item['product']['stripe-price'] line_items_list.append( { 'price': price_stripe, 'quantity': quantity, } ) checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], shipping_address_collection={'allowed_countries': ['DK']}, line_items=line_items_list, automatic_tax={ 'enabled': True, }, mode="payment", success_url=YOUR_DOMAIN + 'success/', cancel_url=YOUR_DOMAIN + 'kurv/' ) return redirect(checkout_session.url) -
Default value in Django Model
I have a model named "Product" and it has an attribute like price, quantity, and remarks. Thru the models.py, if remarks has a property of "null=True", it will return a value "None" but I want it to be a dash(-). If you will be adding a "default='-'" into the remarks column in the model, once its form is created and loaded, it has a dash('-') on it but I want nothing on the form when it's loaded. Do you have any ideas if that's possible? -
Connecting to MSSQL from django 1.8 on Ubuntu
I need to connect to MSSQL database from Django 1.8 and preserve Django 1.8 (not upgrade to newer version od Django). I installed pip install django-mssql . ENGINE in settings.py is sqlserver_ado. It ended with error message ModuleNotFoundError: No module named pythoncom. Django 1.8 is running on Ubuntu 18.04 According to this page I see that django-mssql needs PyWin32. So I returned back to my snapshot in virtual machine and tried it with pip install django-mssql-backend and changed the ENGINE in settings.py to sql_server.pyodbc Now I have error message sql_server.pyodbc isn't an available database backend. So I returned back to my snapshot in virtual machine and tried it with pip install mssql-django and ENGINE is mssql. This upgraded Django to 3.4.1. So I returned to my snapshot of virtual machine. How can I connect to MSSQL from Django 1.8 without upgrading Django? Or is it impossible? Why? -
Create Dynamically table and save data in database on django
if i'm Create Dynamically table using jquery this is working This is my .html file code. <!DOCTYPE html> <html> <head> <title>test page</title> <link rel="stylesheet" href= "https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity= "sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <script> $(document).ready(function () { // Denotes total number of rows var rowIdx = 0; // jQuery button click event to add a row $('#addBtn').on('click', function () { // Adding a row inside the tbody. $('#tbody').append(`<tr id="R${++rowIdx}"> <td class="row-index text-center"> <p>${rowIdx}</p> </td> <td class="row-index text-center"> <input type="text" name="organization"> </td> <td class="row-index text-center"> <input type="text" name="designation"> </td> <td class="row-index text-center"> <input type="date" name="date_from"> </td> <td class="row-index text-center"> <input type="date" name="date_to"> </td> <td class="text-center"> <button class="btn btn-danger remove" type="button">Remove</button> </td> </tr>`); }); // jQuery button click event to remove a row. $('#tbody').on('click', '.remove', function () { // Getting all the rows next to the row // containing the clicked button var child = $(this).closest('tr').nextAll(); // Iterating across all the rows // obtained to change the index child.each(function () { // Getting <tr> id. var id = $(this).attr('id'); // Getting the <p> inside the .row-index class. var idx = $(this).children('.row-index').children('p'); // Gets the row number from <tr> id. var dig = parseInt(id.substring(1)); // … -
API takes longer to load first time opening my webpage
I have a Django app configured on AWS Lambda with zappa. In this app I created some basic APIs with DRF. On the otherside I have a ReactJS frontend that makes these GET requests to load in my data. On my frontend I make a call to get my ID's based on some condition, with this response I get max. 30 ID's where I loop through and make another call for every ID to get their data. The first time I do this, my api to get the ID's loads perfectly and fast enough, but then when it loops, some api's to get the data goes really fast and some just takes around 10-20 seconds to load. this only happens the FIRST time I load my page, after that, if I refresh my page, it is up and running in under 1s. I did some research and I know that AWS Lambda is serverless and shuts down when no one is using the application, so with that in mind, I thought this was why its always slower the first time. But then I found a setting on zappa "keep_warm" to keep my server running, I also made sure that "keep_warm_expression" … -
uwsgi /nginx/ setup on django on centos
i need second pair of eyes , i want to setup my theta.ini file , but uwsgi geta borted for an obscure permission denial in log # this my theta ini file located at /etc/uwsgi/vassals/theta.ini [uwsgi] http=:8000 socket=/opt/uwsgi/sock/theta.sock chdir=/home/tbricks/theta pythonpath=/home/tbricks/theta/django_project home=/home/tbricks/env virtualenv=/home/tbricks/env module = django_project.wsgi uid = uwsgi chmod-socket = 664 chown-socket = uwsgi the below result of running wsgi from log first issue my virtualenv is not getting selected , i don't understand why second the permission error which does make sense, whether env owner is root or uwsgi i get this error , i'm using django 3.0.8 and uwsgi 2.0.14 , python 3.6.8 *** Starting uWSGI 2.0.20 (64bit) on [Thu May 12 14:47:51 2022] *** compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-44) on 11 May 2022 19:17:58 os: Linux-3.10.0-1160.53.1.el7.x86_64 #1 SMP Fri Jan 14 13:59:45 UTC 2022 nodename: django-server machine: x86_64 clock source: unix detected number of CPU cores: 1 current working directory: / detected binary path: /home/tbricks/env/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! setgid() to 993 setuid() to 996 *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 3873 your memory page size is … -
how to change folder location to save file - DJANGO FileSystemStorage
so i want when i upload a file, the file will go to media/mp3 not media/txt. how to change save file location? views.py: def homepage(request): if request.method == 'POST' and request.FILES['upload']: upload = request.FILES['upload'] fss = FileSystemStorage() file = fss.save(upload.name, upload) file_url = fss.url(file) return render(request, 'homepage.html', {'file_url': file_url}) return render(request, 'homepage.html') -
How can I display data from django model and save at the same time using class based views?
I am creating a quiz app using Django. The requirements are: I need to first display all the topics available for the quiz on the homepage. Clicking on a particular page should redirect us to a new page where we will see the questions. Each time one question should be displayed. The next button should load the next question and the user cant go back to the previous question. After attempting all the questions, the user should be taken to another page that displays the score. For each question being attempted, the process should be displayed like 5/10 question, 6/10 question. If a user logs out before completing the quiz, he/she must be displayed the same question once he logs in. I am able to display the topics . The problem is I am not able to display one question at a time and store the user's answer using the class based view. Also I am confused how will I display progress and store the user record if he/she logs out without completing the quiz and redirect them to the very next question till where they had attempted. I am new to django and trying to develop this. Please HELP! … -
Save Form data to use on Request DJANGO Python
I have this pure code writing in Python and requests url = 'https://192.168.1.99/rest' username = 'admin' password = '2626' response = requests.get(url + '/interface', auth=HTTPBasicAuth(username,password), verify=False) When I print the Response, I receive what I expected. So the code is working. But I'm trying to do the same thing with Django, and I don't know how to proceed. On Django, I have a form to save data in to model. Working. But I don't know what's next. Also, the response is a JSON object, but if I use JsonResponse I get an error. -
How to disable "django login" hyperlink while accessing swagger ui in drf-yasg?
I'm using drf-yasg to add swagger auto schema to my endpoints. The swagger-ui is being visible at /api/v1/swagger/ At my local setup this link is working fine and I'm getting the proper schema as required. /api/v1/swagger at my local setup But while accessing the same link when my application is deployed at the server, It is showing a "django login" hyperlink as: /api/v1/swagger at server And this "django login" hyperlink is navigating to -> SERVER_IP/accounts/login/?next=/api/v1/swagger/ which is showing 404 Not found page as: 404 Not found page after clicking on django login hyperlink Even though the openAPI yaml file is being successfully generated of the endpoints at server, but the UI is not getting visible. There was one similar question at stackoverflow: Similar question at SO, but the solution mentioned there was not working for me. Thanks. -
how to set globally to ignore for cache pip packages in windows
Hey developer's I'm stuck in pip installation process.. 1.how can ignore pip cache 2.how can remove all packages for pip 3.can pip/cache folder deletion is safe 4.how to set globally to ignore for cache pip packages -
trouble showing desired checkbox validation state w/ bootstrap5 for django model form w/ m2m field and checkboxselectmultiple widget
I have a checkboxselectmultiple on an m2m model field in an ModelForm that is required - meaning at least one of the choices must be selected. I am using the boostrap5 was-validated class on my form: <form method="POST" action="{{ request.path }}" {% if attempt_submit %}class="was-validated"{% endif %}> This question is about how the validation shows up on my form with bootstrap5. Should be red border and red ! if not validated, green border and checkmark if so. However, for my checkboxes, if I don't have any selected (and everything else on the form validates), the form will show each checkbox option as green instead of red. Yet, it does know that it's invalid because the page focus will come back up the checkbox area to show the user what to correct (and it doesn't pass form.is_valid() in views.py. Why are these labels and boxes still showing green and how can I show them as red until I select one and it's now valid? Along the lines of this post, I have tried adding {% if form.sales_location.field.required %}required{% else %}form.sales_location.field.required=""{% endif %} to the checkbox <input>, but then each field is required and if I select one, the other remaining options … -
how to make custom form without database - DJANGO
So i want to upload file but only sent to locals storage NOT DATABASE too. But i don't know how to make custom forms. suddenly, here's my models.py : from django.db import models class Audio_store(models.Model): record=models.FileField(upload_to='mp3/') forms.py : from django import forms from .models import Audio_store class AudioForm(forms.ModelForm): class Meta: model = Audio_store urls.py : from django.contrib import admin from django.conf.urls import url from . import views from django.urls import path, re_path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^decode/$', views.decode), url(r'^$', views.homepage), path('audio', views.Audio_store), ] if settings.DEBUG: #add this urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) fields= ['record'] html: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{form}} <button type="submit" class="dsnupload"> <i class="large material-icons" style="font-size: 50pt; margin-top: 10px;">audiotrack</i> <p style="font-weight: bold; color: white;">Insert file audio (mp3)</p> </button> </form> -
How to fill form fields since HTML
I have been looking for information on the web about how set values in forms of django but it has been really difficult. I need to put "Inicio" in the field "Origen_del_Circuito" after pushing the button, I have this code: Forms.py class CargaElectricaForm(forms.Form): Circuito=forms.CharField(label='Circuito', max_length=200) Origen_del_Circuito=forms.CharField(label='Origen del Circuito', max_length=200 ) views.py def bajatension(request): if request.method=="POST": form=CargaElectricaForm(request.POST) if form.is_valid(): #form.save() c="Inicio" return render (request, 'SizingWires/lowvoltage.html',{'form':form,'c':c}) else: form=CargaElectricaForm() return render (request, 'SizingWires/lowvoltage.html',{'form':form})** lowvoltage.html <form method="post" > {% csrf_token %} <table> {{form.as_table}} </table> <input type="submit"> Calculator</button> <input type="text" value="{{c}}"> </form> It doesn't work because it creates a new input and I need to use the field "Origen_del_Circuito". How can I access to the fields of my form since HTML (file lowvoltage.html) to put the value of "c"? I know the method "initial" however I need to put the value after of pushing the button. -
Where can I deposit PayPal funds?
I'm developing an iOS application that allows the user to purchase coins with In-App Purchase and send them to other users. Users who receive coins can withdraw them (receive real money) by entering their PayPal email. I will associate my PayPal account as a system to receive the receipts from the App Store and I will use the PayPal Payouts API (connected to the same PayPal account that receives moneys) in a Django backend to allow withdrawals. Since PayPal is not a bank, I need a place to deposit money that could then be withdrawn fast without limits. The problem is that since I don't know how many users I will have I can't use a regular bank account/credit card since they have a limit in the number of transactions per day/week/month. I know there are services like Stripe but I wouldn't know how to integrate them with In-App Purchase and withdraws. Any advice on where/how to deposit money maybe through some service? -
How can I use Validator in perform_create to limit image upload size for Django Rest Framework?
In my view, I'm able to restrict an image's resolution to a specific range of width and height, but I don't know how to use this very method to also restrict an image's upload size. Is there a solution to this? My view: class WatchListAV(generics.ListCreateAPIView): permission_classes = [AdminOrReadOnly] parser_classes = [MultiPartParser, FormParser] # Support both image and text upload. queryset = WatchList.objects.all() serializer_class = WatchListSerializer pagination_class = WatchListLimitOffsetPagination filter_backends = [filters.SearchFilter, filters.OrderingFilter] search_fields = ['title', 'platform__name'] ordering_fields = ['avg_rating'] def perform_create(self, serializer): if not serializer.validated_data['image']: raise ValidationError('No image uploaded.') else: w, h = get_image_dimensions(serializer.validated_data['image']) if w > 8000: raise ValidationError(f"Image's width is too long.") if w < 500: raise ValidationError(f"Image's width is too short") if h > 8000: raise ValidationError(f"Image's height is too tall.") if h < 500: raise ValidationError(f"Image's height is too short.") serializer.save() -
positional argument error in sheduling task in python
I got a positional argument error when i tried running my code and the do() passes extra arguments to the job function take a look at the code below import schedule from schedule import Scheduler import threading import warnings import time def paystack_webhookS (request): user = request.user remail = payload.customer.email rfirst_name = payload.customer.first_name amount = payload.data.amount first_name = user.first_name last_name = user.last_name email = user.email with transaction.atomic(): account = Account.objects.select_for_update().get(email = remail) account.balance += amount asof = account.modified account.save(update_fields=[ 'balance', 'modified', ]) return HttpResponse(status=200) schedule.every(10).seconds.do(paystack_webhookS) schedule.every(10).minutes.do(paystack_webhookS) schedule.every().hour.do(paystack_webhookS) while True: schedule.run_pending() time.sleep(1) i got this error schedule.run_pending() return view_func(*args, **kwargs) TypeError: inner() missing 1 required positional argument: 'request' this error is gotten when trying to execute the while True: schedule.run_pending() time.sleep(1) kindly help me in rectifying this as the request is very important in this code -
Local Variable 'X' Referenced Before Assignment in Django Views
I am working with Django and trying to create two forms on one page which I am struggling with. It is for a simple online store, which needs a shipping and payment section on the checkout page. I am just following a youtube tutorial and trying some things out. I would like to know why I am getting the error "local variable 'street_address' referenced before assignment" originating from line 131 in views. If there are any other mistakes being made please let me know, as I am quite unsure how to go about Placing two forms into one page. Is the only way to do this feature to make a seperate page for payment? VIEWS.PY - CheckoutView Class def get(self, *args, **kwargs): form = AddressForm() form_2 = PaymentForm() order_items = OrderItem.objects.all() context = { 'form': form, 'form_2': form_2, 'items': order_items } return render(self.request,"Order_Management/checkout.html", context) def post(self, *args, **kwargs): form = AddressForm(self.request.POST or None) form_2 = PaymentForm(self.request.POST or None) # order, created = Order.objects.get_or_create(customer=customer, complete=False) # order = Order.objects.get(user=self.request.user, ordered=False) if all([form.is_valid(), form_2.is_valid()]): street_address = form.cleaned_data.get('street_address') city = form.cleaned_data.get('city') postcode = form.cleaned_data.get('postcode') country = form.cleaned_data.get('country') state = form.cleaned_data.get('state') shipping_method = form.cleaned_data.get('shipping_method') card_num = form.cleaned_data.get('card_num') cvc = form.cleaned_data.get('cvc') exp_date = form.cleaned_data.get('exp_date') address … -
django get the value enside formvalid
I am trying to obtain the value of the val variable that is inside form_valid but I cannot obtain it. Does anyone have any idea what I'm doing wrong? return reverse_lazy('cotizando', kwargs = {'pk': self.kwargs["pk"], 'num_cot':self.value}) class Cotizar(CreateView): template_name = "cotizar.html" model = Servicio fields = ['no_servicio', 'precio'] #success_url = '/Cotizar/48' def form_valid(self, form): value = 90 a = Cotizacion( numcot = "{}".format(numerocotizacion()) ,empresa_id = self.kwargs["pk"] ) a.save() form.instance.cotizacion_id = cotizacion_id = a.pk return super().form_valid(form) def get_context_data(self, **kwargs): contexto = super().get_context_data(**kwargs) contexto['productserv'] = Servicio.objects.all() contexto['empresa'] = Empresa.objects.get(pk = self.kwargs['pk']) return contexto def get_success_url(self, **kwargs): #slug = Empresa.objects.get(id=self.kwargs["pk"]).slug return reverse_lazy('cotizando', kwargs = {'pk': self.kwargs["pk"], 'num_cot':self.value}) # return reverse_lazy('v', kwargs={'pk': self.object["pk"]})