Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
if select2 is null, make input field required
I have a text field and a select2 field. The user can input something in the input field, but can also select a predefined choice from the select2 field. I want to do the following: if the select2 is selected, then the form goes through, if not, the input field will be required and the form cannot pass through. I already made a logic in the backend (Django) that copies the value of the select2 to the text field just to make sure all data is valid, but if I leave the frontend without validation, the user could leave everything empty and submit an empty form. Here's my html: <table id="myTable" class="table order-list"> <thead> <tr> <td>Médicament</td> <td>Dosage</td> <td>Posologie</td> <td>Durée</td> <td></td> </tr> </thead> <tbody> <tr> <td class="col-5"> <div class="row"> <div class="col-6"> <input class="form-control mb-4" placeholder="Nom du médicament" type="text" name="medicament0"> </div> <div class="col-6"> <div class="form-group"> <select class="form-control select2-show-search form-select" id="medicament-id0" name="listemedicament0"> <option value="0">Ou choisir de la liste</option> {% for d in drugs %} <option value="{{ d.id }}">{{ d }}</option> {% endfor %} </select> </div> </div> </div> </td> <td> <input class="form-control mb-4" placeholder="20mg" type="text" name="dosage0"> </td> <td> <input class="form-control mb-4" placeholder="2 / j avant repas" type="text" name="posologie0"> </td> <td> <input class="form-control mb-4" placeholder="7 … -
2 models for html in Django
I want to list some data into my html file, below is my 2 models files and My question is how to show products_name in my html ? class ProductsDescription(models.Model): products_id = models.ForeignKey(to='Products', to_field='products_id', on_delete=models.CASCADE, unique=True) products_name = models.CharField(max_length=255, blank=True, null=True) class Products(models.Model): products_id = models.AutoField(primary_key=True) products_type = models.IntegerField(blank=True, null=True) manufacturers_id = models.IntegerField(blank=True, null=True) brand_id = models.IntegerField(blank=True, null=True) products.py from myadmin.models import Products as products from myadmin.models import ProductsDescription def index(request, pIndex=1): mainproducts = products.objects umproducts = mainproducts.filter(products_type=1) pIndex = int(pIndex) page = Paginator(umproducts, 25) maxpages = page.num_pages if pIndex > maxpages: pIndex = maxpages if pIndex < 1: pIndex = 1 list2 = page.page(pIndex) plist = page.page_range context = {"umproducts": list2, 'plist': plist, 'pIndex': pIndex, 'maxpages': maxpages } return render(request, "index.html", context) in my html <table class="table table-hover"> <tr> <th>ID</th> <th>TYPE</th> <th>Products Name</th> <th>MANUFACTORES</th> <th>BRAND</th> </tr> {% for vo in umproducts %} <tr> <td>{{ vo.products_id}}</td> <td>{{ vo.products_type }}</td> <td>{{ vo.products_name }}</td> <td>{{vo.products_manufacturers}}</td> <td>{{ vo.products_brand}}</td> </tr> The problem maybe is I cann't put the product_name from ProductsDescription into umproducts tuple,and my question is how to connect 2 models and namea new tuple then I can use it in html? -
Django save model everyday
I have a model and a signal in models.py and this model sends message to discord webhook with how many days left to something. I want to refresh it everyday at 12:00 AM everyday automatically without using django-celery cause it doesnt work for me. My plan is do something like this time_set = 12 if time_set == timezone.now().hour: ...save model instances... but i have totally no idea how to do it And i want to do it this way cause when model instance are saved signal runs -
can you use python random module inside django models to create unique id
i'm building an invoicing web app, so I want to be able to create a unique id of every invoice but also I want to control how the id looks eg "",BU236718N from random import randint, choice from django.db import models def myID(): my_id = "BU" + randint(1,100000) + choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ") return(my_id) class Invoice(models.Model): invoice_number = models.CharField(myID) def __str__(self): return (self.invoice_number) -
Django to catch all invalid logins and unauthorized access like 401s and 403s
I want to capture all invalid logins/unauthorized access such as 401s and 403s returned from the site so I can log them to a security logging service, investigating if there is an easy way to catch all of these without putting in much custom logic. I have tried using middleware approach: def simple_middleware(get_response): # One-time configuration and initialization. def middleware(request): response = get_response(request) if response.status_code in [403, 401]: log.warning('invalid login') return response return middleware Unfortunately an incorrect login to the /admin/ login, it returns status 200, however I think this would work for custom login that explicitly throws 401/403. I have also tried using the signal approach using request_finished but all I get is just the handler class. So... looking for ideas. -
Django Attribute Error when using serializer
I would like to fetch the entire table. My model and serializer seems to be correct but I am getting the below error Got AttributeError when attempting to get a value for field symbol on serializer CompanySerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'symbol'. Below is my Model models.py from django.db import models class Companies(models.Model): symbol = models.CharField(max_length=100) name = models.CharField(max_length=255) isin = models.CharField(max_length=255) serializers.py from rest_framework import serializers from .models import Companies class CompanySerializer(serializers.ModelSerializer): class Meta: fields = ['symbol', 'name', 'isin',] # fields = '__all__' model = Companies Below is my view views.py from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from .models import Companies from .serializers import CompanySerializer from django.core.serializers import json class companiesView(APIView): def get(self, request): companies = Companies.objects.filter(id=1) serializer = CompanySerializer(companies) # json_serializer = json.Serializer() # json_serialized = json_serializer.serialize(companies) response = Response() response.data = { 'named' : serializer.data, } return response I am not sure what is causing this issue. Thanks in Advance. -
React Native Django authentication
Are there any simple react native django authentication projects that have simple login, logout, password change with django rest framework tutorials. API already set up and fully functional, need to intergrate it with react native, tried axios but system did not sucessfully post rather gave a forbidden error "POST /api/login/ HTTP/1.1" 403 45 Forbidden: /api/login/ Any assistance will be appreciated -
Django 1000 error code on Web socket while sending data to the socket(AsyncJsonWebSocketConsumer)
Can anyone explain it to me the reason behind this error. The socket gets connected, the moment I send data into it, it gives back WebSocket HANDSHAKING /physiochat/ [192.168.43.159:57270] WebSocket CONNECT /physiochat/ [192.168.43.159:57270] WebSocket DISCONNECT /physiochat/ [192.168.43.159:57270] disconnected :- 1000 Here is my code , Also the print commands are not working, nothing gets printed on the terminal. I used the another consumer with same code but its working fine. Kind of new to the web sockets so pardon my question. Any help will be appreciated. Thanks 🙏🏻. class PhysioChatConsumer(AsyncJsonWebsocketConsumer): user = None participant_info_obj = None async def connect(self): print("CONNECTED") await self.accept() async def disconnect(self, code): print('disconnected :- ', code) async def receive_json(self, data): print("Receiving Json") try: print(self.user) if self.user and self.user.id: if 'text' in data.keys() and 'token' in data.keys(): data = await self.add_mssg_to_db(data) await self.channel_layer.group_send( self.room_name, { 'type':'broadcast_message', 'data': data, } ) else: print("NOT GETTING USER") await self.close() else: if 'token' in data.keys() and 'room_id' in data.keys() : self.token = data['token'] self.room_id = data['room_id'] self.is_kiosk = data.get('kiosk', None) if self.is_kiosk: self.profile_id = data['profile_id'] authenticated = await self.authenticate_user() if authenticated: check = await self.check_user_info() if check: self.room_name = f'chat-under-{self.room_id}' await self.channel_layer.group_add( self.room_name, self.channel_name ) else: print("Unable to get the user … -
Django Rest Framework Passing Parameters post
I'm using django rest framework and I want to pass parameters through the POST method, but I'm getting through the url only, is there any way to send information as a body? For example in react pass like this: fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', body: JSON.stringify({ title: 'foo', body: 'bar', userId: 1, }), headers: { 'Content-type': 'application/json; charset=UTF-8', }, }) .then((response) => response.json()) .then((json) => console.log(json)); As it currently stands: angra\urls.py # imports from django.urls import path from . import views as views # if urls.py and views.py are in same dir urlpatterns = [ path('login/<str:email>/<str:password>/', views.login, name="login"), path('hello/', views.hello_world, name="hello_word"), path('calculate/<int:a>/<int:b>/', views.calculate, name="calculate"), path('teste', views.some_view, name="some_view"), ] angra\views.py @api_view(['POST']) def login(request, email, password): return Response({"email":email, "password":password, "nivel":1}) -
Adding a django variable to css
I'm generating a PDF, with django. In my css I use @bottom-left to show the pages, and I would like @bottom-right to show the date and hour when the pdf was generated. I would like to pass this date that I have in a variable to this "content: datetime". Does anyone know if it's possible, and if not, any other alternatives? @page { size: letter; @bottom-left { content: counter(page) " of " counter(pages); font-family: 'Prompt', sans-serif; font-weight: 300; font-size: 9px; color: #868484; } @bottom-right { content: 'datetime'; font-family: 'Prompt', sans-serif; font-weight: 300; font-size: 9px; color: #868484; } } -
How to take multiple value from multiple drop downs in the same POST form in Django
Hello I am creating a cinema book system in Django, and the user must select a film and its date/time from two drop down menus. My issue is that it only takes the film and not date/time. I was wondering how I would be able to add these two in the same form. Thanks the html file: <form action="/booking" method="post"> {% csrf_token %} <div class="movie-container"> <label>Pick a film:</label> <select name="selectedFilm"> {% for showing in showings %} <option value="{{ showing.film }}" name="film">{{ showing.film }}</option> {% endfor %} </select> <br> <br> <label>Pick a time:</label> <select id="selectedDate"> {% for showing in showings %} <option value="{{ showing.date_time }}" name="date">{{ showing.date_time }}</option> {% endfor %} </select> <br> <div class="btn-layer"> <input type="submit" value="Select"> </div> </div> </form> the form file class SelectedFilmForm(forms.Form): selectedFilm = forms.CharField(required=True) selectedDate = forms.DateTimeField(required=True, input_formats=["%Y-%m-%dT%H:%M", ]) enter code here the models file class Film(models.Model): name = models.CharField(verbose_name='Film name', max_length=30) age_rating = models.CharField(verbose_name='Age rating', max_length=5, choices=AgeRatings, default='U') duration = models.DecimalField(verbose_name='Duration (minutes)', max_digits=4, decimal_places=1, blank=True, null=True) description = models.CharField(verbose_name='Description', max_length=500, blank=True, null=True) image = models.ImageField(upload_to='films',default='null') def __str__(self): return self.nameclass Screen(models.Model): screen_id = models.CharField(verbose_name='Screen ID', max_length=30) capacity = models.IntegerField(verbose_name='Capacity') def __str__(self): return self.screen_id class Showing(models.Model): film = models.ForeignKey(Film, on_delete=models.CASCADE, verbose_name='Film', blank=True, null=True) date_time = models.DateTimeField() screen … -
Query through Django tables via switchboard
I have a database structure and solved it with a switchboard instead of ManyToMany. However, decryption is a problem ... class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) class Company(models.Model): name = models.CharField(max_length=60) class CompanyEnrollment(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) company_position = models.ForeignKey( CompanyPosition, on_delete=models.CASCADE) company_enrollment_start = models.DateField(blank=True, null=True) status = models.BooleanField(default=True) class Meta: unique_together = [['person', 'company']] Query the required data: This works, but I don't think Person items that don't have a Company assigned to them appear ... datas = CompanyEnrollment.objects.all().select_related('company') so far I'm fine, I'm listing the people, but I'd like to add the Company_name field next to it. Is it possible to do this in a query? Thanks for the help, I want to understand this, to learn. -
Setting up and activating virtual environment
So, I've been trying to activate my virtual environment in VScode so I could open my Django manage.py and run the server, but for some reason it doesn't seem to activate in my bash terminal. And after running it, I get a "did you forget to activate your virtual environment?". What am I missing here? -
Django ModelForm with extra fields
So I have this ModelForm in my django project: class DateForm(ModelForm): image = forms.ImageField() class Meta: model = Date exclude = ('user',) the Photo model: class Photo(models.Model): date = models.ForeignKey(Date, on_delete=models.CASCADE) image = models.ImageField(verbose_name='Photos', upload_to='media/date/photos/') the form: <p class="p-form">Title</p> {{ form.title }} <p class="p-form">Description</p> {{ form.description }} <p class="p-form">Place</p> {{ form.place }} <p class="p-form">Rating</p> {{ form.rating }} <p class="p-form">Photos</p> {{ form.image }} Whenever I try to save my form, its form_invalid method is being called and it doesn't save the form. What is the matter? How do I save extra field of ForeignKey model? How can I get that images sent via form? Thanks! -
Customize text and style in messages from a Django app
I have a form in django, and when submitting I get a message "Complete this field", how can I customize the text and style of it. forms.py: class ClientesForm(forms.ModelForm): class Meta: model = Clientes fields = 'all' widgets = { 'id':forms.TextInput(), 'identificacion':forms.TextInput(attrs={'placeholder': 'Identificación'}), 'nombre':forms.TextInput(attrs={'placeholder': 'Nombre'}), 'direccion':forms.TextInput(attrs={'placeholder': 'Dirección'}), 'email':forms.EmailInput(attrs={'placeholder': 'EMail'}), 'telefono':forms.TextInput(attrs={'placeholder': 'Teléfono'}), } error_messages = { 'identificacion': {'required':'Custom message'} } The message that appears when submitting is enter image description here -
How to make two requests and continue displaying data from the first request in Django?
I'm new to Django and I'm uploading a file and displaying, on the file view page, I'd like to type a word and display that word. I'm having difficulty in requests to display this word, because when I click to display the word, the file that was being displayed is no longer displayed. #view.py def upload(request): if request.method == 'POST' and request.FILES.get('myfile'): ... return render(request, 'show_file.html', { 'path': path, 'fileName': fileName, }) count = None word = None if request.method == 'POST' and request.POST.get('word'): word = request.POST['word'] return render(request, 'show_file.html', { 'word': word, 'count': count, }) return render(request, 'upload.html') #upload.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> #show_file.html <div> <div> <embed src="{% static 'files/' %}{{ fileName }}" type="application/pdf" style="width:718px; height:1000px;"> </div> <div> <form method="POST"> {% csrf_token %} <label for="word">Write a word:</label> <input id="word" type="text" name="word" value="" /> <input type="submit"> {% if count != None %} Word: {{ word }} {% endif %} </form> </div> </div> -
Module object has no attribute "DatabaseError" after upgrading from Django 1.9 to 1.11
I have a project that I want to slowly migrate to a newer version of Django & Python. I changed my Django version to 1.11 from 1.9 and now I get an error. For this code: import psycopg2 ORIGINAL_BACKEND = getattr(settings, 'ORIGINAL_BACKEND', 'django.db.backends.postgresql_psycopg2') original_backend = import_module(ORIGINAL_BACKEND + '.base') DatabaseError = original_backend.DatabaseError I get AttributeError: 'module' object has no attribute 'DatabaseError' for some reason. I don't really understand why, because I've only changed the Django version - but the error seems to be related to psycopg2. Why is this happening and how can I fix it? -
Displaying a model based on anoyher model
I need some help with setting up the view of a model based on another model. Essentially I have one model called Dataset and another one called DatasetReview, where DatasetReview has a foreign key connection to Dataset. I would like to display all of the DatasetReview models that are tied to a specific Dataset in a separate page. I can currently view each Dataset like so: http://127.0.0.1:8000/dataset/3/ and would like to see all of the DatasetReview models for Dataset 3 like so: http://127.0.0.1:8000/dataset/3/reviews But I am unsure how to set this up. I can show my code in the thread to keep everything contained. Any tips would be super helpful, very new to django. As such, I am not sure how to phrase this question well so I had difficulty finding other posts discussing how to do something like this. urls.py: from django.urls import path from .views import ( DatasetListView, DatasetDetailView, DatasetCreateView, DatasetUpdateView, DatasetDeleteView, DatasetReviewsView ) from . import views urlpatterns = [ path('', DatasetListView.as_view(), name='argo-home'), path('dataset/<int:pk>/', DatasetDetailView.as_view(), name='dataset-detail'), path('dataset/new/', DatasetCreateView.as_view(), name='dataset-create'), path('dataset/<int:pk>/update', DatasetUpdateView.as_view(), name='dataset-update'), path('dataset/<int:pk>/delete', DatasetDeleteView.as_view(), name='dataset-delete'), path('dataset/<int:pk>/reviews', DatasetReviewsView.as_view(), name='dataset-review'), path('about/', views.about, name='argo-about'), ] views.py: from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ( ListView, … -
Django - accessing a count of a queryset filtered by specific value in my template
I had problems even formulating the title to this question :) I am very much a beginner in everything coding but am enjoying learning through a Django project. Usually I can go bit by bit solving my problems by searching around, but I have failed in the below and am stuck although I am certain there is an easy solution… In the below I am doing the following in my html code: step 1. from my views I am getting the context ‘programmes’ sorted by field ‘region’ and use that to list for each region with a list of programmes belonging to the region using a for loop. step 2. In the second column in the table for each programme I show count of total partners in database for that particular programme (using related_name ‘PartofProgramme’ for a foreignkey). So far so good and everyhting works fine. step 3. When I check at this stage the ‘programme.Partof Programme.all’ contains a queryset as follows: “<QuerySet [<Partner: examplepartner1>, <Partner: examplepartner2>, etc etc. listing all partners belonging to the filtered programme. For the third column in the table I want to show a count of these partners with status__code value = ‘active’. How do … -
Vue JS Syntax error: "Unexpected Token, expected ,
I am working on a Django aplication that has VueJS in it. I am new to Django and even newer to VueJS. I am getting this error when I try to run my code: ERROR Failed to compile with 1 errors 2:11:51 PM error in ./src/router/index.js Syntax Error: Unexpected token, expected , (51:0) 49 | } 50 | 51 | }) | ^ 52 | 53 | export default router 54 | @ ./src/main.js 5:0-30 @ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/main.js here is my router/index.js file contents: import Vue from 'vue' import Router from 'vue-router' import Chat from '@/components/Chat' import UserAuth from '@/components/UserAuth' Vue.use(Router) const router = new Router({ routes: [ { path: '/chats', name: 'Chat', component: Chat }, { path: '/auth', name: 'UserAuth', component: UserAuth } ] }) router.beforeEach((to, from, next) => { if (sessionStorage.getItem('authToken') !== null || to.path === '/auth') { next() } else { next('/auth') } } }) export default router What is the reason for the syntax error and how do I correct it? -
Problem authorizing client with django-oAuth-toolkit Authorization Code flow
I have been following the django-oAuth-toolkit documentation. In the Authorization Code step, I have registered an application as shown in the screenshot. But then the next step is given like this: To start the Authorization code flow go to this URL which is the same as shown below: http://127.0.0.1:8000/o/authorize/?response_type=code&client_id=vW1RcAl7Mb0d5gyHNQIAcH110lWoOW2BmWJIero8&redirect_uri=http://127.0.0.1:8000/noexist/callback But when I replace my client id and ping that URL it redirects me to the following URL: http://localhost:8000/noexist/callback?error=invalid_request&error_description=Code+challenge+required. I have tried to google that error but it's such a common keyword that I am unable to find anything that is related to my issue. I am probably missing something obvious, I am new to Python and Django. Note: In the documentation screenshot there is one form field missing which is there in my local environment. It's the algorithm field. -
CI/CD implementation Django application in cpanel
Hello everyone i am trying to upload my django project into cpannel automatially. I am able to upload my project from github to my cpannel using git version control, but i am not able to run my project into cpannel using git version control. I hope i will get the solulation over here and the you in advance. -
In Django {{user.username}} and {{request.user.username}} return the wrong username in template
I'm fairly new to programming in general and am working on a Django Web-App. I am using a ChangeUserData form to update a user's account data (I am using the standard django.contrib.auth User model). When a user's attempt to change their username fails because the new username is already in use, the template is displayed again, alongside the relevant error message. However, the "username" input in the form displays the "new" username, i.e. the one that was rejected for already being in use. I am surprised/confused by this, since in the template I am using {{ request.user.get_username }} to fill in this input. Shouldn't this insert the current user's actual - unchanged - username? I have also tried {{ user.username }} and {{ user.get_username }} but they yield the same result. Below are excerpts from the relevant files: views.py def MyAccount(request): if request.method == 'POST': form = forms.ChangeUserData(request.POST, instance=request.user) if form.is_valid(): form.save(commit=True) return redirect('home') else: return render(request, 'accounts/myAccount.html', { 'form' : form }) else: return render(request, 'accounts/myAccount.html') myAccount.html <input type="text" class="inputLocked" name="username" required autocapitalize="none" value="{{user.get_username}}" id="id_username" readonly> -
Django - have multiple MEDIA_ROOT and MEDIA_URL
I've configured both MEDIA_ROOT and MEDIA_URL and this works perfectly fine. My MEDIA files stored in a directory named /media/, now I want to store newly uploaded files to a new directory (for ex. /media2/) without breaking previous files. For example I had a Book model like this: class Book(models.Model): # name # author cover = models.ImageField() Now imagine I have 500 objects of Book model, so each cover has a path and url like this: url: http://example.com/media/books/thumb.jpg path: /home/myproj/media/books/thumb.jpg Now, I want to store covers for my newly created books in another directory, for ex. : url: http://example.com/media2/books/thumb.jpg path: /home/myproj/media2/books/thumb.jpg without breaking previous 500 books! How can I achieve this ?! (Django 3.1.2) -
Django error while use when using inherit models
I have 2 models that affect 2 tables in my database, Gen_Persona and Ven_Vendedor. The Ven_Vendedor table has the Gen_Persona primary key as its primary key. I have investigated and managed to make the representation through abstract models, however, when I try to make a query I get the following error: django.db.utils.ProgrammingError: column vendedor.gen_persona_ptr_id does not exist LINE 1: ...M "ven"."vendedor" INNER JOIN "gen"."persona" ON ("ven"."ven... I understand that the "ptr_id" refers to a pointer, but since I'm new to Django, I don't understand what change I should make. I hope you can give me feedback on it. Model Gen_Persona: class Gen_Persona(models.Model): prs_id = models.BigAutoField(primary_key=True,db_column='prs_id') prs_identificacion = models.CharField(max_length=16) prs_nombres = models.CharField(max_length=128) prs_apellidos = models.CharField(max_length=128) prs_razonsocial = models.CharField(max_length=256) prs_fechanac = models.DateField(blank=True, null=True) prs_email = models.CharField(max_length=64, blank=True, null=True) prs_telef1 = models.CharField(max_length=16, blank=True, null=True) prs_numtlf2 = models.CharField(max_length=16, blank=True, null=True) prs_numcel = models.CharField(max_length=16, blank=True, null=True) prs_img = models.CharField(max_length=256, blank=True, null=True) prs_dirprinc = models.CharField(max_length=128, blank=True, null=True) prs_dirsecun = models.CharField(max_length=128, blank=True, null=True) prs_dirnum = models.CharField(max_length=32, blank=True, null=True) emp_id = models.ForeignKey(Adm_Empresa, models.DO_NOTHING, verbose_name=Adm_Empresa._meta.verbose_name) prs_estado = models.SmallIntegerField(default=True) tid_id = models.BigIntegerField() class Meta: verbose_name='Persona' managed = False db_table = 'gen\".\"persona' unique_together = (('prs_id', 'emp_id'),) Model Ven_Vendedor : class Ven_Vendedor(Gen_Persona): prs_id_ven = models.OneToOneField(Gen_Persona, models.DO_NOTHING, db_column='prs_id_ven',related_name='fk_genpersona_venvendedor') ven_codigov = models.CharField(max_length=32,verbose_name='Código') ven_comision = …