Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a date picker that does not select previous dates in Django
I want to make a date picker that does not select previous dates using Django. class DateInput(forms.DateInput): input_type = 'date' class TimeInput(forms.TimeInput): input_type = 'time' """class used for booking a time slot.""" class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ['check_in_date', 'check_in_time', 'check_out_time', 'person', 'no_of_rooms'] widgets = { 'check_in_date': DateInput(), 'check_in_time': TimeInput(), 'check_out_time': TimeInput(), } """Function to ensure that booking is done for future and check out is after check in""" def clean(self): cleaned_data = super().clean() normal_book_date = cleaned_data.get("check_in_date") normal_check_in = cleaned_data.get("check_in_time") normal_check_out_time = cleaned_data.get("check_out_time") str_check_in = str(normal_check_in) format = '%H:%M:%S' try: datetime.datetime.strptime(str_check_in, format).time() except Exception: raise ValidationError( _('Wrong time entered.'), code='Wrong time entered.', ) # now is the date and time on which the user is booking. now = timezone.now() if (normal_book_date < now.date() or (normal_book_date == now.date() and normal_check_in < now.time())): raise ValidationError( "You can only book for future.", code='only book for future' ) if normal_check_out_time <= normal_check_in: raise ValidationError( "Check out should be after check in.", code='check out after check in' ) The above code is written in forms.py file. As you can see, I made a date picker but the problem is that the user can select any date but I want him to select … -
Getting error when trying to run to server with Channels
I'm having a problem running python manage.py runserver, to better exemplify, see my code inspired by the book Django 3 by Example. settings.py: """ Django settings for educa project. Generated by 'django-admin startproject' using Django 4.1. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'channels', 'courses.apps.CoursesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'students.apps.StudentsConfig', 'embed_video', 'debug_toolbar', 'redisboard', 'chat.apps.ChatConfig', ] MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.cache.FetchFromCacheMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'educa.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ASGI_APPLICATION = 'educa.routing.application' WSGI_APPLICATION = 'educa.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } … -
Is there a way I can save user sign up details in a model depending on the data they've inputted?
I have a Student model and a Teacher model and I have created a custom user form that takes in an email field and whether the user is a student or a teacher. I would like to make it so that if the user selects that they are a teacher in the sign-up form, their new account details are stored in the Teacher model. If they don't, then their details are stored in the Student model. Is this possible to do directly or do I have to store the data initially in the User model and then transfer it to the Student and Teacher models? This is my code (I wasn't expecting it to work but I just tried it anyways and it didn't): class CustomSignUpForm(UserCreationForm): email = forms.EmailField() is_teacher = forms.BooleanField(label='I am a teacher') class Meta: if is_teacher == True: model = Teacher else: model = Student fields = ['username', 'email', 'password1', 'password2', 'is_teacher'] -
DJango 4.1 + Apache2 => Forbidden: You don't have permission to access this resource
I've followed example from the django documentation as well as various examples from googling, but can't get my django app to serve on apache. Please help. Looking at the apache error.log: AH00035: access to / denied (filesystem path '/home/ubuntu/django-apps') because search permissions are missing on a component of the path The django folders and files ownerships are set to ubuntu:www-data. My directories are: /home/ubuntu/django-apps | ---------------- | | /env /myapp | ----------------- | | /myapp /main | /static /home/ubuntu/django-apps/myapp/myapp/wsgi.py is below, I've tried various examples w/o result: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') application = get_wsgi_application() /etc/apache2/sites-available/000-default.conf <VirtualHost *:80> ServerName myapp.com Alias /static /home/ubuntu/djangle-apps/myapp/main/static <Directory /home/ubuntu/djangle-apps/myapp/main/static> Require all granted </Directory> <Directory /home/ubuntu/djangle-apps/myapp/myapp> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myapp python-path=/home/ubuntu/djangle-app/myapp:/home/ubuntu/djangle-app/env/lib/python3.10/site-packages WSGIProcessGroup myapp WSGIScriptAlias / /home/ubuntu/djangle-apps/myapp/myapp/wsgi.py </VirtualHost> -
Django timezone.now() giving the time when i started the server
I'm using timezone.now() (django.utils impor timezone) to set the initial date of my model. But, the timezone.now() is fixed to the time when i set the server up, and doesnt change. How can i fix this? I wanna that the timezone.now() return the datetime when the user is creating an object and not the time when i run the server. -
Django - Extend User Twice Using AbstractUser
I'd like to have both Teacher and Student Accounts in my Django WebApp. Now I have extended the base user using Student(AbstractUser) and AUTH_USER_MODEL='mainApp.Student'. Now I'd like to implement a Teacher Account, using the same approach. But before I wreck my project I wanted to ask for input. Do you think this can work or should I use a OneToOneField or maybe just a is_teacher / is_student boolean? I'd like to avoid using a OneToOneField, as that creates the need to first create a User and then also create a Student / Teacher. -
Cpanel Number of processes exceeds and Django App crashes
I am very new to deploying Python (Django=4.1) applications on Cpanel(Shared). I have successfully hosted one app with celery, redis, etc. The issue is, every time I start using the app, the total number of processes(Cpanel) exceeds(120/120) and the app stops working. I have been trying to learn about the number of processes and how to optimize the application. Yet no success. Can somebody describe the following? What is the number of processes at Cpanel? How is my app related to this? How can I optimize my application? How to keep the application working? This Python(Django, DRF, Celery, Redis, Requests) app is supposed to be used by 5,000 users. I tried to learn about 'number of processes and entry processes' online. No luck. Went through a few articles to learn how to optimize Django app. -
sql not installing
I am getting error while installing mysql in virtual environment.But why?If i run the command from cmd under env environment it installs.But from vs code showing fatal erroryour text I am getting error while installing mysql in virtual environment.But why?If i run the command from cmd under env environment it installs.But from vs code showing fatal error -
Django - Call variable on input user text
I have a excel data with multiple colums, inside the I have a name colum, now by HTML input the user can write a custom text. I need that the user can use something to call name variable when he like. If use f'User cutsom text {name}' or something like that not work, django keep input user text like a text. Do you know a possibility. I need that the user can use or call variables from the excel when he write his text -
creating new database entrys in django
i am new to django and i am currently setting up a new django app with an existing postgres db. fetching existing data from the database works fine but creating new entries in this database does not work. i have a javascript which sends json data to a view in django. i can access the data in the view but django models.create() and save() seem to do nothing and i dont know why. heres my code: **views.py** from django.shortcuts import render, redirect from django.http import HttpResponse, JsonResponse from notes.models import Profiledata from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def add_events(request): try: if request.method == 'POST': data = json.loads(request.body) print(data) occasion = data['occasion'] year = data['year'] month = data['month'] day = data['day'] print(occasion, day, year, month) new_note = Profiledata(notes = occasion, year = year, month = month, day = day) #print(new_note) new_note.save(force_insert=True) return redirect('') except Exception as e: return JsonResponse({"error": str(e)}) **models.py** class Profiledata(models.Model): id = models.IntegerField(primary_key=True) notes = models.CharField(max_length=500, blank=True, null=True) year = models.IntegerField(blank=True, null=True) month = models.IntegerField(blank=True, null=True) day = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'profiledata' the models.py is created with inspectdb does any one know what i am doing wrong? i tired new_note = … -
Can't set postgresql foreign key using django between two tables
Trying to find out the best way to model my data. I have one table for pokemon types: class PokemonTypesTest2(models.Model): name = models.CharField(max_length=25, unique=True) It just has an ID and name, it will have 18 rows in it. I want to be able to relate multiple tables to it, for example base Pokemon model below ( i cleared out most of the data to be easier to follow: class BasePokemonTest2(models.Model): #other data hidden # type1 = models.ForeignKey(PokemonTypesTest2, on_delete=models.CASCADE, default=1) type2 = models.ForeignKey(PokemonTypesTest2, on_delete=models.CASCADE, default=1) type3 = models.ForeignKey(PokemonTypesTest2, on_delete=models.CASCADE, default=1) weaknessResistanceImmune = models.ManyToManyField(PokemonTypesTest2, through='WeakResistImmune2') I want to be able to relate a pokemon typing to a pokemon from base pokemon table. The problem is I get this error from Django: ERRORS: battlefield.BasePokemonTest2.type1: (fields.E304) Reverse accessor 'PokemonTypesTest2.basepokemontest2_set' for 'battlefield.BasePokemonTest2.type1' clashes with reverse accessor for 'battlefield.BasePokemonTest2.type2'. HINT: Add or change a related_name argument to the definition for 'battlefield.BasePokemonTest2.type1' or 'battlefield.BasePokemonTest2.type2'. I see the hint but don't understand what it means? -
How to fetch data from database with django
Im trying to fetch data from django database. I want to display all the data as divs with different titles, images and description. views.py from .models import Links def all_links(request): links= Links.objects.all() return render(request, 'links.html', {'links' : links}) models.py class Links(models.Model): title = models.CharField(max_length = 30) desc = models.CharField(max_length = 30) link_redirect = models.CharField(max_length = 100) img = models.ImageField(upload_to = None,height_field=None, width_field=None, max_length=100) def __str__(self): return self.title output file: {% for link in link_list %} <div class="links--flex flex"> <div class="links--flex__link"> <div class="link__img"> <img src={% static '/img/links/Pexels.png' %} alt=""> </div> <div class="link__title"> <h2 class='colored'>{{link.title}}</h2> </div> <hr> <div class="link__short"> <p>{{link.desc}}</p> </div> </div> {% endfor %} But nothing is showing. I can see data in my admin panel. I did try to follow few tutorials but it still seems like something is wrong. My app is connected to project. -
My user password does not change, even though no errors occur when I use both password-reset views and password change views
I am pretty new in django. I am using an Abstract user, I have tried to change the password using both PasswordReset views, PasswordChangeViews and even on the admin account as well as with the command prompt. I do not get any errors, everytime everything seems to work well but when I try to login again I realize that the old password still remains the same. I don't know what else I can do I tried using the admin account, PasswordChangeViews, PasswordResetViews, and command line. I get no errors. Everything looks like it is working fine but when I login after changing the password, the password still does not change #User Model class User(AbstractUser): class Role(models.TextChoices): ADMIN="ADMIN",'Admin' STAFF="STAFF",'Staff' CUSTOMER="CUSTOMER",'Customer' CENTRAL="CENTRAL",'Central' MONITOR="MONITOR",'Monitor' username = models.CharField(max_length=200, null=True) name = models.CharField(max_length=200, null=True) email = models.EmailField(null=True, unique=True) role=models.CharField(max_length=50, choices=Role.choices, null=True) updated = models.DateTimeField(auto_now =True) created =models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS= ['username','role'] class Meta: ordering =['-updated','-created'] def save(self, *args, **kwargs): if not self.pk: self.role= self.base_role return super().save(*args,**kwargs) #Views def passwordChange(request): user=User.objects.get(username=request.user.username) if request.method == 'POST': form = ChangePasswordForm(user=user,data=request.POST) if form.is_valid(): form.save() userp=User.objects.get(email=request.user) userp.set_password(form.clean_new_password2()) userp.is_active=True userp.save() update_session_auth_hash(request, userp) print(userp.check_password('XXXXXXXX')) #(XXXXx is actually hardedcoded password to chack if password changed at this point and i get True) … -
How to Login with a Custom User Model Table in Django 4.1.1?
I'm making an educational website in Django 4.1.1, and i need students to be able to register and login, so i created a Custom User Model Table in my models.py file. from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import UserManager class Custom(UserManager): def create_user(self, username, email=None, password=None, **extra_fields): return self._create_user(username, email, password, **extra_fields) class Student(AbstractUser): objects = Custom() sex = models.CharField(max_length=50,default='male') is_superuser = None is_staff = None groups = None user_permissions = None class Meta: verbose_name = "Student" verbose_name_plural = "Students" def __str__(self): return self.username and then i created an HTML registration form to get data from the user {% load static %} <html> <link rel="stylesheet" href="{% static 'css/register.css' %}"> <form method="post"> {% csrf_token %} <input type="text" name="firstName" placeholder="First Name" required minlength="3" maxlength="30"> <input type="text" name="lastName" placeholder="Last Name" required minlength="3" maxlength="30"> <input type="text" name="username" placeholder="Username" required minlength="3" maxlength="30"> <small>{{error}}</small> <input type="email" name="email" placeholder="Email" required maxlength="64"> <small>{{error}}</small> <input type="password" name="password" placeholder="Password" required minlength="8" maxlength="32"> <input type="password" name="passwordAgain" placeholder="Confirm Password" required minlength="8" maxlength="32"> <small>{{paswword_error}}</small> <input type="radio" name="sex" value="male" checked>Male</input> <input type="radio" name="sex" value="female">Female</input> <button type="submit">Submit</button> </form> <script src="{% static 'js/register.js' %}"></script> </html> and then i set up my views.py file to get the data and store it the database … -
Django channels add object at wrong model
I am making a chat app with django channels and it has 2 consumers. One is for the team chat and the other for personal. I am adding history for the chat. There are two models. "Chat" and "Chat2". Chat is for team and Chat2 for personal. The history is working with the team chat and the messages are added to the "Chat" model. But with personal it is added to "Chat" instead of "Chat2". Here are the models: class Chat(models.Model): team_id = models.ForeignKey(Team,on_delete=models.CASCADE,null=True) username = models.CharField(max_length=200,null=True) message = models.CharField(max_length=200,null=True) profile_pic = models.ImageField(upload_to='chat/',null=True) class Chat2(models.Model): username = models.CharField(max_length=200,null=True) username2 = models.CharField(max_length=200,null=True) message = models.CharField(max_length=200,null=True) profile_pic = models.ImageField(upload_to='chat/',null=True) room_name1 = models.CharField(max_length=200,null=True) And here are the two consumers(The consumers are in the same file but I add it separately for cleaner code): class ChatConsumer(AsyncWebsocketConsumer): @sync_to_async def get_profile(self): return self.scope['user'].profile async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = text_data_json['profile_name'] team = text_data_json['team'] profile = await self.get_profile() profile_pic = profile.profile_pic.url … -
How can I connect to a locally hosted site within a docker container?
I'm trying to connect to a docker container's locally hosted address. I'm using Django to serve a website within the container, and I want to connect to it on my local machine. How can I access this site from my local machine? I've tried to inspect the container and found that the local IP address is 172.28.0.4. Even after specifying the correct port on my browser, it still won't connect. The port 8000 is exposed in the container already, and added to the list of ports in the compose file. What can I do to fix this issue? -
when submitting the form, it is showing an error when recording. exiting test is_valid
if form.is_valid(): Errors field: * Cover This field is required. print ( request.POST ) <QueryDict: {'csrfmiddlewaretoken': ['yrPm4Vywus5cMjDNm34zQ8FVyJLdphAK95ErrIhEabOO19ss5ObAhOQe2eM6KO1t'], 'Codigo': ['5'], 'Titulo': ['Reforma do Estado e administração pública gerencia'], 'Capa': ['092022 - G DA SILVA REGO (DAS-SIMPLES) (1).pdf'], 'Sinopse': ['092022 - G DA SILVA REGO (DAS-SIMPLES) (1).pdf'], 'Codigo_grupo': ['3'], 'Codigo_autor': ['2'], 'Data_Publicacao': ['17/10/2022'], 'Edicao': ['7 edição']}> contexto = {'form': form } print ( contexto ) {'form': } models.py `class Livros(models.Model): Codigo = models.IntegerField(blank=False, null=False, primary_key=True) Titulo = models.CharField(max_length=50, blank=False, null=False) Capa = models.FileField(upload_to='capas/') Sinopse = models.FileField(upload_to='sinopse/') Codigo_grupo = models.ForeignKey(Grupos, on_delete=models.CASCADE, db_index=True, blank=False, null=False) Codigo_autor = models.ForeignKey(Autor , on_delete=models.CASCADE, db_index=True, blank=False, null=False) Data_Publicacao = models.DateField(auto_now = False , auto_now_add = False) Edicao = models.CharField(max_length=20, blank=False, null=False) def __str__(self): return str(self.Codigo)+' - '+self.Titulo **forms.py** `class LivrosForm(ModelForm): class Meta: model = Livros fields = ('Codigo','Titulo','Capa','Sinopse','Codigo_grupo','Codigo_autor','Data_Publicacao','Edicao',) ` **views.py** ` def livro_novo(request): form = LivrosForm(request.POST or None) if form.is_valid(): form.save() else: # Added else statment msg = 'Errors: %s' % form.errors.as_text() print ( msg ) print ( request.POST ) contexto = {'form': form } print ( contexto ) print (form.errors) return redirect('core_lista_livros') ` The form fields are filled in according to the class. what could be missing -
Use API call of payment gateway to change order status from "Pending" to "Completed"
I am using Django python and this is my first year in python programming I am writing a program where the client places an order. So in models.py I have an order object with field "Payment Status" with field choices: Pending and Completed. The default for this field is "Pending" but I want to change it to "Completed" once an API call shows the payment collection event is "COMPLETED." How can I capture payload data from API to change my order status from "pending" to "completed" once the transaction is successful? This is what I have in my views.py so far: @csrf_exempt def test_api(request): url = "https://2a45-217-21-116-220.in.ngrok.io/webhooks/intasend" payload = request.body headers = { 'Content-Type': 'text/plain' } response = requests.request("GET", url, headers=headers, data=payload) return JsonResponse(response.text, safe=False) -
Does Django have functionality to restore scroll position after browser BACK button was clicked?
I have a list that doesn't fit the screen vertically. User scrolls the list, then selects an item. Then user returns by pressing BACK browser button. Is there a way to return same scroll position? -
How to launch empty django projects quickly
I was looking for some advice. It takes me a long time to deploy a django project, I have to setup the server, install libraries, configure NGINX and get all the django internals working. I was looking into Docker or Puppet as quick was to create a cookie cutter for Django so I can deploy quickly but I've not used them much and am not entirely sure it's the best approach. If you needed to deploy an empty, running django app frequently, how would you do it? Thanks -
Why is my django_framework so prone to assertion errors
As the title I use "VScode" for programming and the environment is built on "anaconda" I actually simulate a code execution according to the teaching video, but the following errors related to the ".is_valid()" method will appear. The original situation is that the "save" method cannot be called, but when I restart "VScode", sometimes the error occurs Back to normal, in other words, there is no problem with the programming itself. Just encountered another error about the ".is_valid()" method, but this time with the "errors" method... I'm really confused. After all, the code is fine. Where is the problem, the "IDE" or the environment setup...? The "Put" method is super prone to situations! Learning Resources :https://www.bilibili.com/video/BV1rU4y1C7Vi?p=12&vd_source=68c365c9dd4a2dc36b283c24e59f47cd -
How to use suiteQL to query Image field?
I had one image field with the id 'custitem_test_img' on the Item record, Item internal id is '1234', I made one SuiteQL like the below: SELECT Item.custitem_test_img FROM Item WHERE Item.id = 1234 And I got one error back with a message: Error: Search error occurred: Field 'custitem_test_img' for record 'item' was not found. Reason: UNSUITABLE - Unsupported data type 'IMAGE' Any idea how to query the Image type field by SuiteQL? -
how to avoid extra spacing in template while using if endif condition in template django
i am retrieving information from the database and using {%if%} and {%endif%} condition so if that field is blank it does not cause any problem but when that field does not have any value it creates a new blank line in place of that looks bad in styling I saw an answer use this {%if -%} {%- endif %}it doesn't work and throws the error all I want if field is blank do not create any new blank line and render second line below that without creating any whitespace any suggestion will be helpfull -
Adding new item to foreign key field when creating an item for which it is related
I have two models apartment and image defined as class Apartment(models.Model): name = models.CharField(...) price = models.DecimalField(...) class Image(models.Model): apartment = models.ForeignKey(to="Apartment") I have them set up this way so I can have Many Images to One Apartment ManyToOne Rel Is there a way to add new Images when adding a new Apartment? There is no field for Images in the Apartment admin section -
Serving static files after deployment with django 2.2
I deployed my site at the level of my host, but the imgaes are not displayed. I did python manage.py collectstatic and it copied the files to my STATIC_ROOT myprojet/settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ] STATIC_URL = 'static/' STATIC_ROOT='/home/www/mySite.com/static/' index.html {% extends 'layout/base.html' %} {% load staticfiles %} {% block content %} <img src="{% static 'images/icone.png' %}" style="width:350px;height:100"> {% endblock content %} I used {% load staticfiles %} as i am using django 2.2 but the images are not showing I don't know where the problem is.