Can't find a solution for my probelm online. error message I am receiving regarding problem ----- IntegrityError at /add_user_address/
UNIQUE constraint failed: users_useraddress.user_id ------ all help greatly appreciated!
views.py
import re
from django.urls import reverse
from django.shortcuts import render, redirect, Http404, HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .forms import UserRegisterForm, UserAddressForm
from .models import EmailConfirmed
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your registration has been successful! Please check your email to confirm account.')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
SHA1_RE = re.compile('^[a-f0-9]{40}$')
def activation_view(request, activation_key):
if SHA1_RE.search(activation_key):
print("activation key is real")
try:
instance = EmailConfirmed.objects.get(activation_key=activation_key)
except EmailConfirmed.DoesNotExist:
instance = None
messages.success(request, f'There was an error with your request.')
return HttpResponseRedirect("/")
if instance is not None and not instance.confirmed:
page_message = "Confirmation successful, welcome to Fuisce! "
instance.confirmed = True
instance.activation_key = "Confirmed"
instance.save()
elif instance is not None and instance.confirmed:
page_message = "Already Confirmed"
else:
page_message = ""
context = {"page_message": page_message}
return render(request, "users/activation_complete.html", context)
else:
raise Http404
#login_required
def profile(request):
return render(request, 'users/profile.html')
**def add_user_address(request):
print(request.GET)
try:
redirect = request.GET.get("redirect")
except:
redirect = None
if request.method == "POST":
form = UserAddressForm(request.POST)
if form.is_valid():
new_address = form.save(commit=False)
new_address.user = request.user
new_address.save()
if redirect is not None:
return HttpResponseRedirect(reverse(str(redirect)))
else:
raise Http404**
html file
{% extends "fuisce/base.html" %}
{% block content %}
<form method="POST" action='{% url "add_user_address" %}?redirect=checkout'>{% csrf_token %}
{{ address_form.as_p }}
<input type='submit' class='btn btn-primary' value='Add Address'/>
</form>
{% endblock content %}
My html and views file are attached, let me know if anything else is needed to solve the problem.
from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.models import User
from django.conf import settings
from django.template.loader import render_to_string
from django.urls import reverse
from localflavor.ie.ie_counties import IE_COUNTY_CHOICES
class UserAddress(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
address = models.CharField(max_length=150 )
address2 = models.CharField(max_length=150, null=True, blank=True)
city = models.CharField(max_length=100, null=True, blank=True)
county = models.CharField(max_length=100, choices=IE_COUNTY_CHOICES)
country = models.CharField(max_length=100)
postalcode = models.CharField(max_length=30)
phone = models.CharField(max_length=60)
shipping = models.BooleanField(default=True)
billing = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return str(self.user.username)
Add your models file - unique constrain is connected with your model for database. Probably you add for one field in your model attribute "unique=True".
Related
I am working on an Auction website using Django. I am trying to display data of the Last_bid field which is connected to Bid table with a foreign key. I tried many ways but nothing worked out.
The models.py file is:
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.db.models.base import Model
from django.db.models.deletion import CASCADE
from django.db.models.fields import CharField
from django.utils import timezone
class User(AbstractUser):
pass
class Category(models.Model):
category = models.CharField(max_length=64)
def __str__(self):
return f'{self.category}'
class AuctionListing(models.Model):
item_name = models.CharField(max_length=100)
item_image = models.ImageField(upload_to="products", null=True, blank=True)
detail = models.TextField()
price = models.IntegerField()
last_bid = models.ForeignKey('Bid', on_delete=models.CASCADE, blank=True, null=True, related_name='lst')
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='publisher_listing', null=True, blank=True)
watchers = models.ManyToManyField(User, blank=True, related_name='watched_list')
pub_date = models.DateTimeField(auto_now=True, null=True)
deadline = models.DateTimeField(null=True)
list_category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, related_name='sortion')
closed = models.BooleanField(default=False)
def __str__(self):
return f'{self.item_name} - {self.price}'
class Bid(models.Model):
bid = models.IntegerField()
user = models.ForeignKey(User, on_delete=CASCADE)
auction = models.ForeignKey(AuctionListing, on_delete=CASCADE)
bid_date = models.DateTimeField(auto_now=True)
def __str__(self):
return f'{self.bid}-{self.auction}'
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=CASCADE)
com = models.TextField()
pub_date = models.DateField()
com_item = models.ForeignKey(AuctionListing, on_delete=models.CASCADE, related_name='get_comment')
def __str__(self):
return f'{self.user} - {self.pub_date}'
Views.py:
from django.contrib.auth import authenticate, login, logout
# from django.contrib.auth.decorators import login_required
from django.db import IntegrityError, reset_queries
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, render
from django.urls import reverse
from django.forms import ModelForm
from .models import *
def index(request):
active_list = AuctionListing.objects.all().order_by('id').reverse()
return render(request, "auctions/index.html", {'active_list': active_list })
def login_view(request):
if request.method == "POST":
# Attempt to sign user in
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request, username=username, password=password)
# Check if authentication successful
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "auctions/login.html", {
"message": "Invalid username and/or password."
})
else:
return render(request, "auctions/login.html")
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse("index"))
def register(request):
if request.method == "POST":
username = request.POST["username"]
email = request.POST["email"]
# Ensure password matches confirmation
password = request.POST["password"]
confirmation = request.POST["confirmation"]
if password != confirmation:
return render(request, "auctions/register.html", {
"message": "Passwords must match."
})
# Attempt to create new user
try:
user = User.objects.create_user(username, email, password)
user.save()
except IntegrityError:
return render(request, "auctions/register.html", {
"message": "Username already taken."
})
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "auctions/register.html")
class CreateForm(ModelForm):
class Meta:
model = AuctionListing
fields = ['item_name', 'item_image', 'detail', 'price', 'deadline', 'list_category']
def create_listing(request):
user = request.user
if user.id is None:
return redirect('login')
if request.method == 'GET':
context = {
'form': CreateForm()
}
return render(request, 'auctions/create_listing.html', context)
else:
if request.method == 'POST':
form = CreateForm(request.POST or None, request.FILES or None)
if form.is_valid():
item_name = form.cleaned_data['item_name']
item_image = form.cleaned_data['item_image']
detail = form.cleaned_data['detail']
price = form.cleaned_data['price']
deadline = form.cleaned_data['deadline']
list_category = form.cleaned_data['list_category']
listing_created = AuctionListing.objects.create(
item_name = item_name,
item_image = item_image,
detail = detail,
price = price,
deadline = deadline,
list_category = list_category,
user = request.user,
)
listing_created.save()
return redirect('index')
def listing(request, pk):
user = request.user
list = AuctionListing.objects.get(id=pk)
if request.method == 'POST':
bid = request.POST.get('placebid')
user = request.user
form = Bid(bid=bid, user=user, auction=list)
form.save()
return render(request, 'auctions/listing.html', {'list': list})
The index.html is:
{% extends "auctions/layout.html" %}
{% block body %}
<h2>Active Listings</h2>
{% for each in active_list %}
<div class="back">
<div class="imag">
<img src="{{ each.item_image.url }}" alt="">
</div>
<div class="detail">
<h1>{{ each.item_name }}</h1>
<h6>Published by: <span>{{ each.user }}</span></h6>
{% if each.last_bid %}
<p>Current Bid: <span>{{ each.last_bid.bid }} </span></p>
{% else %}
<p>Current Bid: <span>{{ each.price }} </span></p>
{% endif %}
<p>Published date: <span>{{ each.pub_date }}</span></p>
<p>DeadLine: <span>{{ each.deadline }}</span></p>
<div class="bid-detail">
<p>Initial Price: {{ each.price }}</p>
<p>Watchers: 10</p>
</div>
</div>
</div>
{% endfor %}
{% endblock %}
I want to display the last_bid in index.html but I was not able to. Please help me with this problem. I will be thankful to you.
I need to display the details of the user on the profilepage. But in the following situation, I am unable to render phone number and flag(attributes of SpecialUser model) on my profile page. I was asked to implement an extended model for the User model in Django auth for an application. I introduced 2 new fields i.e, phonenumber(charfield), flag(booleanfield). My form is able to take both the inputs. But I couldn't render these values again into my HTML file. Could someone help me out!
models.py
# accounts.models.py
from django.db import models
from django.contrib.auth.models import User
class SpecialUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
flag = models.BooleanField(verbose_name="Special User", default=False)
phonenumber = models.CharField(max_length=10, verbose_name="phonenumber")
def __str__(self):
return self.user.username
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import SpecialUser
class RegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ["username", "email", "password1", "password2"]
class SuperUserForm(forms.ModelForm):
class Meta:
model = SpecialUser
fields = ["flag", "phonenumber"]
views.py
from accounts.models import SpecialUser
from django.shortcuts import render, redirect
from .forms import RegisterForm, SuperUserForm
from django.contrib import messages
from django.contrib.auth.models import auth
def register(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
sp_form = SuperUserForm(request.POST)
if form.is_valid() and sp_form.is_valid():
user = form.save()
sp_form = sp_form.save(commit=False)
sp_form.user = user
sp_form.save()
messages.success(request, 'Account created!')
return redirect('login')
else:
form = RegisterForm(request.POST)
sp_form = SuperUserForm(request.POST)
messages.warning(request, 'Your account cannot be created.')
return render(request, 'register.html', {'form': form, 'sp_form': sp_form})
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
data = SpecialUser.objects.all()
dt = {"all": data}
return render(request, "profilepage.html", dt)
else:
messages.info(request, 'invalid credentials')
return redirect('login')
else:
return render(request, 'login.html')
def logout(request):
auth.logout(request)
return redirect('login')
profilepage.html
<h1>{{user.username}}</h1>
<h4>Email : {{user.email}}</h4>
<h5>Phone Number : {{all.phonenumber}}</h5>
{%if user.flag %}
<button>Special User</button>
{%endif%}
here is the correct html you need to see your data
{%for d in all%}
{%ifequal d.user user%}
<h1>{{d.user.username}}</h1>
<h4>Email : {{d.user.email}}</h4>
<h5>Phone Number : {{d.phonenumber}}</h5>
{%if d.flag %}
<button>Special User</button>
{%endif%}
{%endifequal%}
{%endfor%}
I get ValueError when i try and save an object, The error is related to User being assigned to a model. When i use without string method (only user=request.user) it says TypeError at /cart/
str returned non-string (type User)
when i apply string method (user=str(request.user)) it gives me ValueError at /cart/ Cannot assign "'admin'": "CartItem.user" must be a "User" instance.
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from django.contrib.auth import login, logout, authenticate
from django.db import IntegrityError
from .models import Book, CartItem
from django.contrib.auth.decorators import login_required
from .forms import BookForm
# Create your views here.
def signupuser(request):
if request.user.is_authenticated:
return render(request, 'main/alreadyloggedin.html')
elif request.user != request.user.is_authenticated:
if request.method == "GET":
return render(request, 'main/signupuser.html', {'form':UserCreationForm()})
elif request.method == "POST":
if request.POST['password1'] == request.POST['password2']:
try:
user = User.objects.create_user(request.POST['username'], password=request.POST['password1'])
user.save()
login(request, user)
return render(request, 'main/UserCreated.html')
except IntegrityError:
return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'That username has already been taken. Please choose a new username'})
else:
return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'Passwords did not match'})
def signinuser(request):
if request.user.is_authenticated:
return render(request, 'main/alreadyloggedin.html', {'error':'You are already logged in'})
elif request.user != request.user.is_authenticated:
if request.method == "GET":
return render(request, 'main/signinuser.html', {'form':AuthenticationForm()})
elif request.method == "POST":
user = authenticate(request, username=request.POST['username'], password=request.POST['password'])
if user is None:
return render(request, 'main/signinuser.html', {'form':AuthenticationForm(), 'error':'Username and password did not match'})
else:
login(request, user)
return render(request, 'main/loggedin.html', {'error':'You are now logged in!'})
def logoutuser(request):
if request.user.is_authenticated:
if request.method == "GET":
return render(request, 'main/logoutuser.html')
elif request.method == "POST":
logout(request)
return render(request, 'main/loggedin.html', {'error':'You are now logged out!'})
elif request.user != request.user.is_authenticated:
return render(request, 'main/alreadyloggedin.html', {'error':'You are not logged in'})
def home(request):
books = Book.objects.all()
return render(request, 'main/home.html', {'books':books})
#login_required
def addtocart(request):
if request.method == 'POST':
bookid = CartItem.objects.get(pk=request.POST['bookid'])
form = CartItem.objects.create(book=bookid, user=str(request.user), commit=False)
newCartItem = form.save(commit=False)
newCartItem.user = request.user
newCartItem.save()
return redirect('home')
elif request.method == 'GET':
return render(request, 'main/signinuser.html', {'form':BookForm})
home.html
<h1>Here are products</h1>
{% for book in books %}
<h3>{{ book.name }}</h3>
<img src= "/media/{{ book.image }}" alt="">
<p>{{ book.description }}</p>
<form method="POST" action="/cart/">
{% csrf_token %}
<button type="submit" name="bookid" value="{{ book.id }}">Add to cart</button>
</form>
{% endfor %}
urls.py
"""EBook URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from core import views
urlpatterns = [
path('admin/', admin.site.urls),
path('signup/', views.signupuser, name='signupuser'),
path('login/', views.signinuser, name='signinuser'),
path('logout/', views.logoutuser, name='logoutuser'),
path('', views.home, name='home'),
path('cart/', views.addtocart, name='cart'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Meta:
verbose_name = 'Category'
verbose_name_plural = 'Categories'
class Book(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
image = models.ImageField()
price = models.IntegerField()
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.name
class Order(models.Model):
order_id = models.CharField(max_length=500)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.user
class CartItem(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.user
forms.py
from django.forms import ModelForm
from .models import CartItem
class BookForm(ModelForm):
class Meta:
model = CartItem
fields = ['book', 'user']
It appears that you were using a form and then after changing the code used the Models create method like it was a form and also using the books id to get a CartItem? Change your view like so:
#login_required
def addtocart(request):
if request.method == 'POST':
try:
book = Book.objects.get(pk=request.POST['bookid'])
except Book.DoesNotExist:
return redirect('home')
cart_item = CartItem.objects.create(book=book, user=request.user)
return redirect('home')
elif request.method == 'GET':
return render(request, 'main/signinuser.html', {})
I removed the form from the context because it looked like you didn't use it.
I made a web app where the user can submit a form. I want the user to be able to view his submission but I can't figure out how to access the previously submitted data.
I keep getting an error related to failing to reverse match failure.
The error says
Reverse for 'submission' with no arguments not found. 1 pattern(s) tried: ['submission/(?P<application_id>[0-9]+)/$']
Views.py
#login_required
def apply(request):
"""Submit application"""
if request.method != 'POST':
form = ApplicationForm()
else:
form = ApplicationForm(data=request.POST)
if form.is_valid():
new_application = form.save(commit=False)
new_application.owner = request.user
new_application.save()
return redirect('credit_apply:submitted')
context = {'form': form}
return render(request, 'credit_apply/apply.html', context)
def submission(request, application_id):
"""View and maybe? edit application"""
application = Application.objects.get(id=application_id)
owner = application.owner
if request.method != 'POST':
form = ApplicationForm(instance=application)
else:
form = ApplicationForm(instance=application, data=request.POST)
if form.is_valid():
form.save()
return redirect('credit_apply:submitted', owner_id=owner.id)
context = {'application': application, 'owner': owner, 'form': form}
return render(request, 'credit_apply/submission.html', context)
models.py
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
from django.contrib.auth import get_user_model as user_model
User = user_model()
# Create your models here.
class Application(models.Model):
"""App para las aplicacions de credito"""
first_name = models.CharField(max_length=40)
last_name = models.CharField(max_length=40)
business = models.CharField(max_length=100)
m_number = PhoneNumberField(max_length=16)
email = models.EmailField(max_length=254, unique=True)
date_added = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return f"{self.first_name} {self.last_name} {self.business}"
url pattern
path('submission/<int:application_id>/', views.submission, name='submission')
base template line that is causing the error to pop up
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="{% url 'credit_apply:submission' application.id%}">
Edita!</a></li>
....
changed my view to:
def submission(request):
"""View and maybe? edit application"""
model = Application
application = Application.objects.get(owner=request.user)
if request.method != 'POST':
form = ApplicationForm(instance=application)
else:
form = ApplicationForm(instance=application, data=request.POST)
if form.is_valid():
form.save()
return redirect('credit_apply:submitted')
context = {'application': application, 'form': form}
return render(request, 'credit_apply/submission.html', context)
removed the application_id pattern and application.id tag in template since no longer needed
This is a project that user/employee requests for a leave and the admin can see it.
models.py
from django.db import models
from django.contrib.auth.models import User
CHOICES = (('1','Earned Leave'),('2','Casual Leave'),('3','Sick Leave'),('4','Paid Leave'))
class Leave(models.Model):
user = models.ForeignKey(User, on_delete = models.CASCADE, null =True)
name = models.CharField(max_length = 50)
employee_ID = models.CharField(max_length = 20)
department = models.CharField(max_length = 15)
designation = models.CharField(max_length = 15)
type_of_leave = models.CharField(max_length = 15, choices = CHOICES, default = None)
from_date = models.DateField()
to_date = models.DateField()
reporting_manager = models.CharField(max_length = 50, default = None)
reason = models.CharField(max_length= 180)
def __str__(self):
return self.name
forms.py
from django import forms
from lrequests import models
CHOICES = (('1','Earned Leave'),('2','Casual Leave'),('3','Sick Leave'),('4','Paid Leave'))
class LeaveRequestForm(forms.ModelForm):
class Meta:
fields = ("name", "employee_ID", "department", "designation", "type_of_leave", "from_date", "to_date", "reporting_manager", "reason")
model = models.Leave
admin.py
from django.contrib import admin
from . import models, forms
class LeaveAdmin(admin.ModelAdmin):
form = forms.LeaveRequestForm
admin.site.register(models.Leave, LeaveAdmin)
In the views.py file I'm not sure how to code to store data in the
database. So that the admin can see the data that's acquired from the forms.
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import LeaveRequestForm
from django.views.generic import TemplateView
def leaveRequest(request):
form_class = LeaveRequestForm
if request.method == "POST":
form = LeaveRequestForm(request.POST)
if form.is_valid():
leave = form.save(commit = False)
return HttpResponse("Sucessfully submitted")
else:
return render(request, "request_form.html", {'form' : form_class})
And this is my template.
{% extends "base.html" %}
{% block content %}
<div class="container">
<h4>
<form role="form", method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type = "submit">Submit</button>
</form>
</h4>
</div>
{% endblock %}
This is a basic question but here's what you're supposed to do
def leaveRequest(request):
form_class = LeaveRequestForm
if request.method=='POST': #executes when you submit the form
form = LeaveRequestForm(request.POST) #gets the form's data
if form.is_valid(): #checks if the data is valid
lvreq = form.save() #saves the data
return HttpResponse('Saved')
else:
return HttpResponse('invalid data entered') #error message
return render(request, "request_form.html", {'form' : form_class})
Here's the answer !!!
from django.shortcuts import render
from django.http import HttpResponse
from .forms import LeaveRequestForm
def leaveRequest(request):
form_class = LeaveRequestForm
if request.method == "POST":
form = LeaveRequestForm(request.POST)
if form.is_valid():
leave = form.save(commit = False)
leave.user = request.user
form.save()
return HttpResponse("Sucessfully submitted")
else:
form = LeaveRequestForm()
return render(request, "request_form.html", {'form' : form_class})
Make the following changes in your forms.py and views.py and you will get the desired results.
forms.py
from django import forms
from lrequests import models
CHOICES = (('1','Earned Leave'),('2','Casual Leave'),('3','Sick Leave'),('4','Paid Leave'))
class LeaveRequestForm(forms.ModelForm):
name = forms.CharField(max_length=30)
employee_ID = forms.CharField(max_length=30)
department = forms.CharField(max_length=30)
designation = forms.CharField(max_length=15)
type_of_leave = forms.CharField(max_length=15)
from_date = forms.CharField(max_length=30)
to_date = forms.CharField(max_length=30)
reporting_manager = forms.CharField(max_length=30)
reason = forms.CharFieldforms.CharField(max_length=200)
class Meta:
fields = ("name", "employee_ID", "department", "designation", "type_of_leave", "from_date", "to_date", "reporting_manager", "reason")
model = models.Leave
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import LeaveRequestForm
from django.views.generic import TemplateView
from .models import Leave
def leaveRequest(request):
form_class = LeaveRequestForm
if request.method == "POST":
form = LeaveRequestForm(request.POST)
if form.is_valid():
leave = Leave(
user = request.user
name = request.POST.get('name','')
employee_ID = request.POST.get('employee_ID','')
department = request.POST.get('department','')
designation = request.POST.get('designation','')
type_of_leave = request.POST.get('type_of_leave','')
from_date = request.POST.get('from_date','')
to_date = request.POST.get('to_date','')
reporting_manager =request.POST.get('reporting_time','')
reason = request.POST.get('reason','')
)
leave.save()
return HttpResponse("Sucessfully submitted")
else:
return render(request, "request_form.html", {'form' : form_class})