Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to do an inner join statement in django?
A little confused on how to do join's in Django. For example I have the following 3 tables: battlefield_weakresistimmune; id | weakResistanceImmune | multiplier | pokemon_id | typing_id ----+----------------------+------------+------------+----------- battlefield_basepokemontest; id | name | base_hp | base_atk | base_def | base_spatk | base_spdef | base_speed | ability1 | ability2 | hidden_ability | pokemon_id | type1_id | type2_id | type3_id ----+---------------+---------+----------+----------+------------+------------+------------+------------+-----------+----------------+------------+----------+----------+---------- 1 | Bulbasaur | 45 | 49 | 49 | 65 | 65 | 45 | Overgrowth | n/a | Chlorophyll | 1 | 12 | 4 | 2 | Ivysaur | 60 | 62 | 63 | 80 | 80 | 60 | Overgrowth | n/a | Chlorophyll | 2 | 12 | 4 | battlefield_pokemontypestest; id | name ----+---------- 1 | Normal 2 | Fighting 3 | Flying 4 | Poison I want to get the name of the Pokemon from basepokemontest, the condition and multiplier from weakresistimmune and the type name from pokemontypestest. I can easily do that in SQL via: SELECT poke.name, con.weak_resist_immune, type.name, con.multiplier FROM battlefield_basepokemontest poke INNER JOIN battlefield_weakresistimmune con ON poke.id = con.pokemon_id INNER JOIN battlefield_pokemontypestest type ON type.id = con.typing_id; name | weak_resist_immune | name | multiplier -----------+--------------------+--------+------------ Bulbasaur | Weak | … -
I have a query that checks if BVN or Phone _number exist in my db but I am trying to add a third item which is the channel used by user
I am working on an API that that takes BVN or Phone number and Channel from user. When they call the API I am to return a message based on the channel(If they used used, I will return text and if they used mobile banking, I will return html). What I have built so far will check pick any of BVN or PHone number supplied and check the channel.If user has been saved before I return "user exist" if not I will save. I have achieved this so far but I want to take if further to check for channel too. if the user with phone number "X" hits the API twice with different channel I want it to pass. I want to deny access only if the (phone number or bvn) and channel correspond with wants in the db. Serializer.py ` class SaveTermsSerializer(serializers.ModelSerializer): channel=serializers.CharField(required=True) bvn= serializers.CharField(max_length=15,allow_blank=True, required=False) phone_number=PhoneNumberField(allow_blank=True, required=False) # terms_status=serializers.CharField(max_length=25) class Meta: model = Consent fields = ['channel','phone_number', 'bvn', 'consent_status'] def validate(self, data): bvn = data.get('bvn') channel = data.get('channel') phone_number = data.get('phone_number') if channel.lower() not in ['ussd','mobile_banking','online_banking']: raise serializers.ValidationError("Invalid channel detected") if not (bvn or phone_number): raise serializers.ValidationError("BVN and Phone Number cannot be empty") if bvn and not … -
Field 'activity_id' expected a number but got <QueryDict: Django
I'm creating a small django CRUD project and working on creating the create functionality, however everytime I try to create an activity through teh sites frontend I get the following error Field 'activity_id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['DnM8yrfIrvYgvN6rShEOtR9DFwjpryNtHHs6ytHK1CSAYg3G9sm7YjkcHlpejJDt'], 'host': ['1'], 'name': ['testing testing'], 'date': ['2022-06-28'], 'start_time': ['19:20:58'], 'end_time': ['19:52:50'], 'location': ['test Location'], 'description': ['ewerwerwerwe']}>. When I create somethign through the /admin panel, it works as expected. here is my forms.py file: from django import forms from .models import Activity class ActivityForm(forms.ModelForm): class Meta: model = Activity fields = ('host', 'name', 'date', 'start_time', 'end_time', 'location', 'description') def __init__(self, *args, **kwargs): """ Add placeholders and classes, remove auto-generated labels and set autofocus on first field """ super().__init__(*args, **kwargs) placeholders = { 'name': 'Activity Type', 'date': 'Date of Activity', 'start_time': 'Start Time', 'end_time': 'End Time', 'location': 'Location', 'description': 'Description', 'host': 'Host', } for field in self.fields: if self.fields[field].required: placeholder = f'{placeholders[field]} *' else: placeholder = placeholders[field] self.fields[field].widget.attrs['placeholder'] = placeholder self.fields[field].label = False this is the models.py file class Activity(models.Model): class Meta: verbose_name_plural = 'Activities' activity_id = models.AutoField(primary_key=True) host = models.ForeignKey(UserProfile, on_delete=models.CASCADE) name = models.CharField(max_length=254, null=False, blank=False) date = models.DateField() start_time =models.TimeField() end_time = models.TimeField() location = models.CharField(max_length=40, null=False, blank=False) description … -
Define a @property and @classproperty with the same name (Python, Django)
Background The Django LiveServerTestCase class has a live_server_url method with a @classproperty decorator. (django.utils.functional.classproperty.) The class starts its test server before any tests run, and thus knows the test server's URL before any tests run. I have a similar MyTestCase class that has a live_server_url @property. It starts a new test server before each test, and thus its live_server_url property can't be a @classproperty because it doesn't know its port until it is instantiated. To make the API for both consistent, so that all the test utility functions etc. in the code base can be used with both classes, the tests could be written to never reference live_server_url in setUpClass(), before all the tests run. But this would slow down many tests. Instead, I want MyTestCase.live_server_url to raise a helpful error if it is referenced from the class object rather than an instance object. Since MyTestCase.live_server_url is a @property, MyTestCase().live_server_url returns a string, but MyTestCase.live_server_url returns a property object. This causes cryptic errors like "TypeError: unsupported operand type(s) for +: 'property' and 'str'". Actual question If I could define a @classproperty and @property on the same class, then I would define a MyTestCase.live_server_url @classproperty that raises an error with a … -
Currency store in shorted form Python
enter code here write a program If we have gorcery store .. one customer come in shop and purchase some item and give 180$ our program automatically all cuurency notes store in shorted form an other customer come and purchse one item nad give 20$ alrady we have array in shorted form this 20$ automaticalyy store in shorted form """ import random import matplotlib.pyplot as plt import matplotlib.animation as anim # install matplotlib using (pip install matplotlib) # if you are using linux run this # sudo apt-get install --reinstall libxcb-xinerama0 def swap(A, i, j): a = A[j] A[j] = A[i] A[i] = a # this is buble sort algo def sort_buble(arr): if (len(arr) == 1): return for i in range(len(arr) - 1): for j in range(len(arr) - 1 - i): if (arr[j] > arr[j + 1]): swap(arr, j, j + 1) yield arr def insertion_sort(arr): if(len(arr)==1): return for i in range(1,len(arr)): j = i while(j>0 and arr[j-1]>arr[j]): swap(arr,j,j-1) j-=1 yield arr def quick_Sort(arr,p,q): if(p>=q): return piv = arr[q] pivindx = p for i in range(p,q): if(arr[i]<piv): swap(arr,i,pivindx) pivindx+=1 yield arr swap(arr,q,pivindx) yield arr yield from quick_Sort(arr,p,pivindx-1) yield from quick_Sort(arr,pivindx+1,q) def selection_sort(arr): for i in range(len(arr)-1): min = i for … -
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