Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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"]}) -
I'm trying to do a CRUD with Python, and the data display is having a conflict between the tables
Ok, before anything I just want to make clear that english is not my first language and I've never posted a question here before, so I apologise beforehand if this all seems confusing, I'll try to be as direct and clear as possible here. I don't know what else to do at this point since I don't know anyone that deals with similar code, so I'm hoping someone here can maybe identify what I'm doing wrong here. T^T Basically, I'm doing this college assignment where I have to make a CRUD in Python for a motorcycle dealership (in my case I'm doing it with the django library, and using SQLite to manage the database). Everything is going well, except for the part where it displays the data (it's basically creating link to page on a local server on the computer. I'm not exactly sure how to describe it), and in the main page it displays a few tables, with data from the database tables (I have two, right now, one for client data and the other for the motorcycles). Problem is: the data input works just fine, but whenever I try to make the page display the data from the … -
How to run Django in Python?
I am trying to install django in python. This is my code. conda create -n djangoenv python=3.8.5 anaconda conda activate djangoenv conda install -c anaconda django django-admin startproject website python manage.py runserver when I run the last line of code I get the following error python: can't open file 'manage.py': [Errno 2] No such file or directory I am trying this code (djangoenv) C:\Users\Action>django_project\manage.py and this code (djangoenv) C:\Users\Action>djanago_project\manage.py runserver Both codes are opening the script file, but are not running the Django and giving me the URL Does anyone have any suggestions to amend the code? -
I'm trying to build Project Management API
actually i have many problems here I'm going to list a few of them I'm using django rest framework to build Project Management API I have 3 end points Projects, tasks, group my first problem is in group end point I want to list all groups that the loged user created and all groups that the loged user is member in . my second problem is I want the group members assign actions in the tasks of the project in the group . and last one in in my post form in task and groups project variable return all projects create in the server so I want only retun the project that the current user created . here is my model class Project(models.Model): """ here we have all projects data and the owner of the project we can add more fields . """ created = models.DateTimeField(auto_now_add=True,blank=False) #the time of creating the project title = models.CharField(max_length=100, blank=False, default='') # project title owner = models.ForeignKey('auth.User', related_name='projects', on_delete=models.CASCADE) # project owner class Meta: # we order with the new one ordering = ('-created', ) def __str__(self): return self.title class Task(models.Model): """ Task table here we create a relation '' """ title = models.CharField(max_length=100, … -
Channels django nginx 502
I ran into a problem once I install and add "channels" to the settings and after that to the asgi file. Server crashes, I get 502 and nginx won't start. How can I add these channels and start working already ASGI_APPLICATION = "mysite.asgi.application" application = ProtocolTypeRouter({ "http": get_asgi_application(), # Just HTTP for now. (We can add other protocols later.) # WebSocket chat handler "websocket": AuthMiddlewareStack( URLRouter([ ]) ), }) help, I'm sure a lot of people have come across this, thanks -
Auto reloading no longer working after Django 1.11 to 3.2 upgrade
After upgrading an old inherited codebase from Django 1.11 to 3.2.13, I've found that Django no longer automatically reloads the server whenever a file change occurs. I've looked at the logger and it does say the the reloader is watching for file changes. After performing one change in the codebase and hitting save, the logger does say that it has detected a file change; however, nothing actually happens and the changes aren't reflected anywhere until you manually restart the server. If I make any further changes, there are no further logger messages displayed about file changes. I've also noticed that any version of Django before 2.2 seems to work in terms of reloading properly. It was only after upgrading to 2.2 and 3.2 that I noticed any issues. Here is a snippet from the logs. Staring threads ['manage.py', 'runserver'] System check identified no issues (0 silenced). May 12, 2022 - 20:07:04 Django version 3.2.13, using settings 'api.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [none] 2022-05-12 20:07:21,827 django.utils.autoreload INFO /api/settings.py changed, reloading. Has anyone else run into this issue before? For reference, I'm currently testing on the following environment: MacOS Monterey (12.3.1, M1) Python 3.9.12 (have also … -
How to use bootstrap with xhtml2pdf?
I need to render PDF files dynamically in a Django web app. I understand there are 2 options : Render an html template file then convert it to a PDF file. I used xhtml2pdf Python library. The issue is that the template I want to use has bootstrap and it isn't supported by xhtml2pdf. Actually no javascript is supported and the generated PDFs are horrible. I have to write the html / css myself which I don't want to. How to solve this problem ? Is there an alternative library ? Convert a webpage into a PDF file directly -
How to login into a django backend in jest tests?
I have a django server that is running the graphQL backend. I need to authenticate a user so I can test against the /graphql endpoint. I have search and tried all the solutions for logging in. I keep getting status code 200 but if I read the html I am still on the login screen. If I subsequently try to hit the graphql endpoint I get a message that I need to be logged in to do it. I tried using withCredentials but it says that is not allowed. I have disabled CSRF for login for so that is not the issue. Any idea what is wrong with this code since it does not login and keep the session? import axios from 'axios'; import {wrapper} from 'axios-cookiejar-support'; import {CookieJar} from 'tough-cookie'; let f = new FormData() f.append('username','admin') f.append('password','password') const jar = new CookieJar(); const client = wrapper(axios.create({jar})); let login_resp = await client.post('http://localhost:3031/admin/login', f,{headers: {'Content-Type': 'application/json'}}); console.log(login_resp.status) console.log(login_resp.data) -
Django DateField validators are not running
I have a DateField as part of a form. date = forms.DateField( required=True, input_formats=[DATE_INPUT_FORMATS] ) When I view the form, on the front end, and I enter garbage in to the date field, Django doesn't throw a forms.ValidationError, and instead proceeds to execute the forms clean() method. I have tried adding my own custom validation method to the DateField: def validate_date_field(dateval): raise forms.ValidationError("date error...") date = forms.DateField( required=True, input_formats=[DATE_INPUT_FORMATS], validators=[validate_date_field] ) Even when my validate_date_field function is set up to always return a validation error, it does not execute. Instead, and again, Django proceeds to execute the code in the forms clean() method... What's going on ? -
Django class based custom error page handler
Is it possible to write a class based (not function) custom error page handler? for example this: def handler404(request, *args, **argv): response = render_to_response('404.html', {}, context_instance=RequestContext(request)) response.status_code = 404 return response but with class -
How to send JSON format data in postman to django models that have a foreign key to another model?
I have tried to send a POST request to django views.py file using postman. It was working when I sent a POST and GET request to django models that haven't ForeignKey field. However, when I tried to send a POST request to a django model that have a ForeignKey field, it wasn't working. My question is how to send a JSON format data using postman to django models that have a Foregin Key field. The models are as follows: class Article(models.Model): authorId=models.CharField(max_length=100) authorResidence=models.CharField(max_length=100) communtId=models.CharField(max_length=100) content=models.TextField() contentId=models.CharField(max_length=100) source=models.CharField(max_length=100) timestamp=models.IntegerField() title=models.CharField(max_length=100) class Interactions(models.Model): userId=models.CharField(max_length=100,unique=True) location=models.CharField(max_length=100) eventType=models.IntegerField(unique=True) articleId=models.ForeignKey(Article,on_delete=models.CASCADE) communityId=models.CharField(max_length=100) source=models.IntegerField() timestamp=models.IntegerField() I have tried in this way (in postman): { "userId":"153344", "location":"Ethiopia", "eventType":"1", "articleId":"67353536", "communityId":"1234567", "source":"1", "timestamp":"123456" } As you can see the articleId is a foreignKey field. Here is the output: { "articleId": [ "Invalid pk \"67353536\" - object does not exist." ] } -
file extentions in Django
I have created a file upload website where I want to allow users to upload files in pdf, ppt, doc, txt, and zip format. I am using the HTML form to upload files. model.py class Upload_Notes(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) uploadingdate = models.CharField(max_length=30) branch = models.CharField(max_length=30) subject = models.CharField(max_length=50) notesfile = models.FileField(null=True) filetype = models.CharField(max_length=30) description = models.CharField(max_length=200, null=True) status = models.CharField(max_length=15) def __str__(self): return f'{self.user} notes' view.py def upload_notes(request): if request.method=='POST': branch = request.POST['branch'] subject = request.POST['subject'] notes = request.FILES['notesfile'] filetype = request.POST['filetype'] description = request.POST['description'] user = User.objects.filter(username=request.user.username).first() Upload_Notes.objects.create(user=user,uploadingdate=date.today(),branch=branch,subject=subject,notesfile=notes, filetype=filetype,description=description,status='pending') messages.success(request,f"Notes uploaded from {request.user.username} successfully!") return redirect('/view_mynotes') return render(request,'user/upload_notes.html') I have tried to do it by following this tutorial but it doesn't work for me. please help me to achieve this -
data._mutable= True in Django rest framework
I have seen this many times and looked it everywhere but couldn't figure out what it actually means and is it mandatory? I have not used this data._mutable = True or False in my code before and I am not sure whether I should be using it or not. The code snippet looks somewhat like this. def update(self, request, *args, **kwargs): instance = self.get_object() data = request.data if data.get("something") == "null": data._mutable = True data["something"] = None data._mutable = False Why do we need to assign True or False to the private attribute _mutable of data object.?? -
Django: CSS File Not Loading
I have an app in Django, where I am creating a web page. When I go to the proper URL, the HTML page, with Bootstrap does load, but my CSS doesn't load. Below, I wanted to color the h1 Blue, but it doesn't appear, it's black. I have added the HTML file, CSS file, and File Tree, below. Thank you for helping and let me know if you need more information. HTML {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Amodh Dhakal | Portfolio</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <link rel="stylesheet" type="text/css" href="{% static 'mysite/style.css' %}"> </head> <body> <h1>Hello</h1> </body> </html> CSS h1 { color: blue; } File Tree -
Django sub-admin permissions
I am creating a project in which colleges can post notice for their students.That means colleges are my client. Right now every college is able to see the data of each other's students in admin panel. I want that college can see only their students in admin panel. I am new in django and don't know how to do it. Please help. -
django.db.utils.IntegrityError: NOT NULL constraint failed after reseting migrations
I need to save an object that contains a file and some other data. Although the file is stored on the /media folder, the entity is not saved in the database since saving it triggers an integration error. django.db.utils.IntegrityError: NOT NULL constraint failed: app_eeg.filename 'filename' was a field I deleted and I already deleted the migrations folder and did the following commands: python3 manage.py makemigrations app python3 manage.py migrate app Models.py class EEG(models.Model): file = models.FileField(null=False) status = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) report = models.ForeignKey(Report, verbose_name=('report'), on_delete=models.CASCADE, related_name='%(class)s_report', null=True) operator = models.ForeignKey(Operator, verbose_name=('operator'), on_delete=models.CASCADE, related_name='%(class)s_operator', null=False) patient = models.ForeignKey(Patient, verbose_name=('patient'), on_delete=models.CASCADE, related_name='%(class)s_patient', null=False) How can I fix this error from happening? -
A MultiSelectField with a select2 widget is not properly working for EDIT in Django
I have a form I am trying to understand its behaviour in Django. The form code looks like : class RequestForm(forms.ModelForm): TIMEPOINTS = ( ("1M" , "1M"), ("2M" , "2M"), ("4M" , "4M"), ("6M" , "6M"), ("9M" , "9M"), ("1Y" , "1Y"), ("2Y" , "2Y"), ("3Y" , "3Y"), ("4Y" , "4Y"), ("5Y" , "5Y"), ) timepoint = forms.MultipleChoiceField(choices=TIMEPOINTS) def __init__(self, *args, **kwargs): super(RequestForm, self).__init__(*args, **kwargs) self.fields['timepoint'].required = False class Meta: model = Request fields = '__all__' exclude = ('request_task_id', 'request_status',) widgets = { 'timepoint': forms.Select(attrs={'class': 'select2 timepoint form-control'}) } I have a classic view @login_required def edit_request(request, pk): data_request = Request.objects.get(id=pk) form = RequestForm(instance=data_request) if request.method == 'POST': form = RequestForm(request.POST, instance=data_request) if form.is_valid(): new_req = form.save(commit=False) new_req.created_by = request.user new_req.save() messages.success(request, ' Request Edited Successfully') return redirect("data-requests") else: form = RequestForm(instance=data_request) context = { 'form': form, 'data_request' : data_request, } return render(request, 'extractor/datarequest_edit.html', context) The problem with this code and the behaviour hat I dont undertant is this : 1- The form works fine when I select many timepoints in the form, it saves as a charfield 2- When I want to edit I cannot find my options on the field 3- When I pick only one opton, it …