I'm learning django now, and i'm facing a problem, I create a form to submite data in my database, but the problem is when i click on submit button, postgres isn't receiving data, I cant understand the problem.
This is my contact form
This is my database
This is my html code
<form action="." method='post' class="p-5 bg-white">
<h2 class="h4 text-black mb-5">Contact Form</h2>
{% csrf_token %}
<div class="row form-group">
<div class="col-md-6 mb-3 mb-md-0">
<label class="text-black" for="fname">First Name</label>
<input type="text" id="fname" class="form-control rounded-0">
</div>
<div class="col-md-6">
<label class="text-black" for="lname">Last Name</label>
<input type="text" id="lname" class="form-control rounded-0">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="text-black" for="email">Email</label>
<input type="email" id="email" class="form-control rounded-0">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="text-black" for="subject">Subject</label>
<input type="subject" id="subject" class="form-control rounded-0">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="text-black" for="message">Message</label>
<textarea name="message" id="message" cols="30" rows="7" class="form-control rounded-0" placeholder="Leave your message here..."></textarea>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<input type="submit" value="Send Message" class="btn btn-primary mr-2 mb-2">
</div>
</div>
</form>
This is my models.py
from django.db import models
class Form(models.Model):
fname=models.CharField(max_length=300)
lname=models.CharField(max_length=300)
email=models.EmailField()
subject=models.CharField(max_length=300)
message=models.TextField()
This is my views.py
from django.shortcuts import render
from .models import Form
def test(request):
if request.method == 'POST':
request.POST.get('fname')
request.POST.get('lname')
request.POST.get('email')
request.POST.get('subject')
request.POST.get('message')
post=Form()
post.fname= request.POST.get('fname')
post.lname= request.POST.get('lname')
post.email= request.POST.get('email')
post.subject= request.POST.get('subject')
post.message= request.POST.get('message')
post.save()
else:
return render(request,'test.html')
1st. In the form action="." is not necessary as if action is empty it will be sent to the current view itself.
2nd. I suggest using Model Forms which are a lot easier.
Let's say the model name is M1.
models.py
from django.db import models
class M1(models.Model):
fname = models.CharField(max_length=300)
lname = models.CharField(max_length=300)
email = models.EmailField()
subject = models.CharField(max_length=300)
message = models.TextField()
forms.py
from django import forms
M1Form(forms.modelForm):
class Meta:
model = M1
views.py
from django.shortcuts import render
from .models import M1
from .forms import M1Form
def test(request):
if request.method == "POST":
form = M1Form(request.POST)
if form.is_valid():
form.save()
else:
return render(request, "test.html")
else:
return render(request, "test.html")
3rd. If you look at the Templates:
<input type="email" id="email" class="form-control rounded-0">
it does not have an attribute "name" in it. If you want email in request.POST It should be written like
<input type="email" id="email" name="email" class="form-control rounded-0">
Please keep in mind that the name should be the same as the model name (Since we are not overwitting the Form).
For more Documentation:
https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/
Related
I am trying to create a login and signup feature on my website but for some reason, I can't create a user. and it's not showing any error.
I have done these before in another code but I don't know why it is not working in this one.
And also when I refresh the website, it asks if it should resubmit the form.
These are the codes below
index.html
<div class="main-register">
<div class="close-reg"><i class="fal fa-times"></i></div>
<ul class="tabs-menu fl-wrap no-list-style">
<li class="current"><i class="fal fa-sign-in-alt"></i> Login</li>
<li><i class="fal fa-user-plus"></i> Register</li>
</ul>
<!--tabs -->
<div class="tabs-container">
<div class="tab">
<!--tab -->
<div id="tab-1" class="tab-content first-tab">
<div class="custom-form">
<form method="post" action="" name="registerform">
{% csrf_token %}
{% for message in messages %}
<h4 style="color: red;">{{message}}</h4>
{% endfor %}
<label>Email Address * <span class="dec-icon"><i class="fal fa-user"></i></span></label>
<input name="email" type="email" placeholder="Your Mail" onClick="this.select()" value="">
<div class="pass-input-wrap fl-wrap">
<label >Password * <span class="dec-icon"><i class="fal fa-key"></i></span></label>
<input name="password" placeholder="Your Password" type="password" autocomplete="off" onClick="this.select()" value="" >
<span class="eye"><i class="fal fa-eye"></i> </span>
</div>
<div class="lost_password">
Lost Your Password?
</div>
<div class="filter-tags">
<input id="check-a3" type="checkbox" name="check">
<label for="check-a3">Remember me</label>
</div>
<div class="clearfix"></div>
<button type="submit" class="log_btn color-bg"> LogIn </button>
</form>
</div>
</div>
<!--tab end -->
<!--tab -->
<div class="tab">
<div id="tab-2" class="tab-content">
<div class="custom-form">
<form method="POST" id="registerform" class="main-register-form" name="registerform">
{% csrf_token %}
{% for message in messages %}
<h4 style="color: red;">{{message}}</h4>
{% endfor %}
<label >Full Name * <span class="dec-icon"><i class="fal fa-user"></i></span></label>
<input name="full_name" type="text" placeholder="Your Name" onClick="this.select()" value="">
<label>Email Address * <span class="dec-icon"><i class="fal fa-envelope"></i></span></label>
<input name="email" type="text" placeholder="Your Mail" onClick="this.select()" value="">
<div class="pass-input-wrap fl-wrap">
<label >Password * <span class="dec-icon"><i class="fal fa-key"></i></span></label>
<input name="password" type="password" placeholder="Your Password" autocomplete="off" onClick="this.select()" value="" >
<span class="eye"><i class="fal fa-eye"></i> </span>
</div>
<div class="filter-tags ft-list">
<input id="check-a2" type="checkbox" name="check">
<label for="check-a2">I agree to the Privacy Policy and Terms and Conditions</label>
</div>
<div class="clearfix"></div>
<button type="submit" class="log_btn color-bg"> Register </button>
</form>
</div>
</div>
</div>
<!--tab end -->
</div>
views.py
def index(request):
return render(request, 'index.html')
def signup(request):
if request.method == 'POST':
full_name = request.POST['full_name']
email = request.POST['email']
password = request.POST['password']
if User.objects.filter(email=email).exists():
messages.info(request, 'Email is taken')
return redirect('index.html')
else:
user = User.objects.create_user(full_name=full_name, email=email, password=password)
user.save()
user_model = User.objects.get(full_name=full_name)
new_profile = user_profile.objects.create(user=user_model, id_user=user_model.id)
new_profile.save()
return redirect('index.html')
else:
return render(request, 'index.html')
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
models.py
from django.db import models
from django.contrib.auth import get_user_model
User =get_user_model()
# Create your models here.
class user_profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
id_user = models.IntegerField()
location = models.CharField(max_length=120, blank=True)
def __str__(self):
return self.user.full_name
I have a model onlinebooking and I am trying to save the data the user inputs. However I am getting the error TypeError at /onlinebooking/
onlinebooking() got an unexpected keyword argument 'name'. I get this error after clicking the register button.
Here is my model:
class onlinebooking(models.Model):
name = models.CharField(max_length=30)
email = models.CharField(max_length=30)
phone_number = models.IntegerField()
room_type = models.CharField(max_length=10)
booking_date = models.DateField()
views.py
from django.shortcuts import render,redirect
from .models import onlinebooking
def onlinebooking(request):
if request.method == "POST":
name = request.POST['Name']
email = request.POST['email']
phone_number = request.POST['phone_no']
room_type = request.POST['room_type']
booking_date = request.POST['booking_date']
online = onlinebooking(name=name,email=email,phone_number=phone_number,room_type=room_type,booking_date=booking_date)
online.save()
return redirect('/')
else:
return render(request,'hotel/onlinebooking.html')
form used:
<form action="/onlinebooking/" method="post">
{% csrf_token %}
<div class="text-primary">
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Name</label>
<input type="text" class="form-control" id="inputEmail4" name="Name" required>
</div>
<!-- <div class="form-group col-md-6">
<label for="lastname">Last name</label>
<input type="text" class="form-control" id="lastname"
name="lastname" required>
</div> -->
<div class="form-group col-md-6">
<label for="inputPassword4">Email</label>
<input type="text" class="form-control" id="inputPassword4" name="email" required>
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Phone no</label>
<input type="text" class="form-control" id="inputPassword4" name="phone_no" required>
</div>
<div class="form-group col-md-6">
<label for="inputState">Room Type</label>
<select id="inputState" class="form-control" name="room_type">
<option selected>Standard</option>
<option>Delux</option>
<option>Premium</option>
</select>
</div>
<div class="form-group col-md-6">
<label for="bookingtime">Booking Date</label>
<input type="date" id="bookingtime" name="booking_date" required>
</div>
<div class="text-center">
<input type="submit" value="Register" name="submit-emp" class="btn btn-primary col-sm-3 btn-user ">
</div>`
I guess there is some error with my models as I can access all the entries of the user. i think its some silly mistake from my side. Please help me out here. :)
You are overriding the import name with the class name in this file itself.
Try this:
from django.shortcuts import render,redirect
from . import models
def onlinebooking(request):
if request.method == "POST":
name = request.POST['Name']
email = request.POST['email']
phone_number = request.POST['phone_no']
room_type = request.POST['room_type']
booking_date = request.POST['booking_date']
online = models.onlinebooking(name=name,email=email,phone_number=phone_number,room_type=room_type,booking_date=booking_date)
online.save()
return redirect('/')
else:
return render(request,'hotel/onlinebooking.html')
I have added two new columns 1.gender, 2.pinCode in PostgreSQL auth_user table and now I trying to post data in the table through Sign Up form to create a new user
Please let me know how to fix this issue, I'm stuck at this from last few days.
error - User() got an unexpected keyword argument 'gender'
views.py
from django.shortcuts import render, HttpResponse, redirect
from django.contrib.auth.models import User
def login(request):
pass
def signup(request):
if request.method == 'POST':
firstName = request.POST['firstName']
lastName = request.POST['lastName']
mobileNum = request.POST['mobileNum']
emailID = request.POST['emailID']
passFld1 = request.POST['passFld1']
passFld2 = request.POST['passFld2']
gender = request.POST['gender']
pinCode = request.POST['pinCode']
myUser = User.objects.create_user(username=mobileNum, password=passFld1, first_name=firstName, last_name=lastName, email=emailID, gender=gender, pinCode=pinCode)
myUser.save()
print('User Created Successfully')
return redirect('/')
else:
return HttpResponse('Not Allowed')
# return render(request, 'index.html')
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('login', views.login, name="login"),
path('signup', views.signup, name="signup"),
]
HTML
<form method="POST" action="signup" id="signUpForm" class="login100-form validate-form">
{% csrf_token %}
<div class="login-title mb-5">Create an Account</div>
<div class="row">
<div class="col-md-6">
<div class="wrap-input100" data-validate="Invalid Name">
<input class="input100 text-capitalize" onkeypress="return isAlphabet(event)" type="text" maxlength="15" name="firstName" required>
<span class="focus-input100" data-placeholder="First Name"></span>
</div>
</div>
<div class="col-md-6">
<div class="wrap-input100" data-validate="Invalid Name">
<input class="input100 text-capitalize" onkeypress="return isAlphabet(event)" type="text" maxlength="15" name="lastName" required>
<span class="focus-input100" data-placeholder="Last Name"></span>
</div>
</div>
<div class="col-md-6">
<div class="wrap-input100" data-validate="Invalid Mobile">
<input class="input100" onkeypress="return isNumber(event)" onchange="isMobileNumber(this,'Invalid Mobile Number');" type="text" maxlength="10" name="mobileNum" required>
<span class="focus-input100" data-placeholder="Mobile Number"></span>
</div>
</div>
<div class="col-md-6">
<div class="wrap-input100" data-validate="Invalid Email">
<input class="input100" type="email" maxlength="30" name="emailID" required>
<span class="focus-input100" data-placeholder="Email"></span>
</div>
</div>
<div class="col-md-6">
<div class="wrap-input100" data-validate="Invalid Password">
<input class="input100" type="password" maxlength="20" name="passFld1" required>
<span class="focus-input100" data-placeholder="Password"></span>
</div>
</div>
<div class="col-md-6">
<div class="wrap-input100" data-validate="Invalid Password">
<input class="input100" type="password" maxlength="20" name="passFld2" required>
<span class="focus-input100" data-placeholder="Password"></span>
</div>
</div>
<div class="col-md-6">
<select class="input100" required name="gender" id="gender">
<option value="Hidden" hidden selected disabled>Hidden</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Others">Others</option>
</select>
</div>
<div class="col-md-6">
<div class="wrap-input100" data-validate="Invalid PIN Code">
<input class="input100" onkeypress="return isNumber(event)" type="text" maxlength="6" name="pinCode" required>
<span class="focus-input100" data-placeholder="PIN Code"></span>
</div>
</div>
</div>
<div class="container-login100-form-btn">
<div class="wrap-login100-form-btn w-50">
<div class="login100-form-bgbtn"></div>
<button type="submit" id="signUpSubmit" class="login100-form-btn">Sign Up</button>
</div>
<button onclick="submit();" class="btn btn-info">Sign Up</button>
</div>
<div class="newAccount mt-5">
Already have an account? <span id="LogInBtn">Login</span>
</div>
</form>
models.py
from django.db import models
from django.contrib.auth.models import User
class NewUserModel(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
new_field_name = models.CharField(max_length=100)
Error
TypeError at /signup
User() got an unexpected keyword argument 'gender'
Request Method: POST
Request URL: http://127.0.0.1:8000/signup
Django Version: 3.0.8
Exception Type: TypeError
Exception Value:
User() got an unexpected keyword argument 'gender'
Exception Location: C:\Users\Vipin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py in _init_, line 500
Python Executable: C:\Users\Vipin\AppData\Local\Programs\Python\Python38\python.exe
Python Version: 3.8.4
Python Path:
['C:\\Users\\Vipin\\Desktop\\Modifyz',
'C:\\Users\\Vipin\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
'C:\\Users\\Vipin\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
'C:\\Users\\Vipin\\AppData\\Local\\Programs\\Python\\Python38\\lib',
'C:\\Users\\Vipin\\AppData\\Local\\Programs\\Python\\Python38',
'C:\\Users\\Vipin\\AppData\\Roaming\\Python\\Python38\\site-packages',
'C:\\Users\\Vipin\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages']
Server time: Sat, 22 Aug 2020 07:19:28 +0000
```[enter image description here][1]
**Error Screenshot**
https://i.stack.imgur.com/soz0s.png
Since you are importing User model from django.contrib.auth.models, we can be 100 % sure that the model does not have a field named gender.
You can see here which fields are available and gender is not one of them. If you'd like to add a gender field to your User model, then you need to customize this model. Here is the documentation describing different approaches.
Generally it is smart to customize it when you start a new project. The documentation linked above gives and example how do to this.
Create custom model in one of your apps models.py
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
pass
Override AUTH_USER_MODEL in settings.py
AUTH_USER_MODEL = 'myapp.MyUser'
Register the model in app's admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User
admin.site.register(User, UserAdmin)
I am trying to make a website's contact page using django where client enters data and it gets submitted in database, the form gets submitted the project runs without errors and yet no data gets added in the db.
Here's my views.py file
from datetime import datetime
from firstapp.models import Contact
# Create your views here.
def index(request):
return render(request,'index.html',)
def apply(request):
return render(request,'apply.html')
def about(request):
return render(request,'about.html')
def socials(request):
return render(request,'social.html')
def contact(request):
if request.method == "POST":
name = request.POST.get("name")
email = request.POST.get("email")
subject = request.POST.get("subject")
message= request.POST.get("message")
contact=Contact(name=name,email=email,subject=subject,message=message,date=datetime.today())
contact.save
return render(request,'contact.html')
here is my contact.html
{% block title %}Contact {% endblock title %}
{% block body %}
<h2 align="center">CONTACT US </h2>
<div class="container-md">
<form method="POST" action="/contact/">
{% csrf_token %}
<div class="form-group">
<label for="exampleFormControlInput1">Name</label>
<input type="text" class="form-control" id="exampleFormControlInput1" name="name" placeholder="John Smith">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Email address</label>
<input type="email" class="form-control" id="exampleFormControlInput1" name="email" placeholder="name#example.com">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Subject</label>
<input type="text" class="form-control" id="exampleFormControlInput1" name="subject" placeholder="Business
| Suggestions | Query | Complaint | Other">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Message</label>
<textarea class="form-control" name="message" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
{% endblock body%}
And here's my models.py
from django.db import models
# Create your models here.
class Contact(models.Model):
name = models.CharField(max_length=50)
email =models.EmailField(max_length=254)
subject=models.CharField(max_length=10)
message=models.CharField(max_length=1000)
date=models.DateField()
As I wrote at the comments before, you have forgotten to type brackets following the save: contact.save() instead of contact.save.
It would be better and more beautiful if you do it like this:
def contact(request):
if request.method == "POST":
Contact.objects.create(**request.POST)
return render(request,'contact.html')
So I wanna be able to update information of a router in the database using a form, I wanna have a form pre-populated with that specific router details. The problem is that form.is_valid() is not working
I tried using {{ form.errors }} {{ form.non_field_errors }} and print(form.errors) but none of them worked
views.py (incomplete)
def info_router(request, pk):
rout = Routers.objects.get(sn=pk)
if request.method == 'GET': # Insert the info in forms
form = UpdateRouter()
rout = Routers.objects.get(sn=pk)
args = {'router': rout}
return render(request, "router_info.html", args)
if request.POST.get('delete'):
# Delete router
rout.delete()
messages.warning(request, 'Router was deleted from the database!')
return redirect("db_router")
if request.method == 'POST':
#Updating the form
form = UpdateRouter(instance=Routers.objects.get(sn=pk))
print(form)
print(form.errors)
if form.is_valid():
data = UpdateRouter.cleaned_data
mac = data['mac']
print(mac)
return HttpResponseRedirect('db_router')
else:
print("Invalid form")
return render(request, "db_router.html", {'form': form})
forms.py
class UpdateRouter(ModelForm):
class Meta:
model = Routers
fields = ['model', 'ip_addr', 'name', 'sn', 'mac']
template
<form class="form-horizontal" action="" method="post">
{% csrf_token %}
<div class="form-group"> <!-- Form with the router details -->
<label class="control-label col-sm-2" for="text">Serial number:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" name="sn" value="{{ router.sn }}" readonly>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Model:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" value="{{ router.model }}" name="model" readonly>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Ip address:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" value="{{ router.ip_addr }}" name="ip_addr">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" value="{{ router.name }}" name="name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Mac address:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" value="{{ router.mac }}" name="mac">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Extra info:</label>
<div class="col-sm-10">
<textarea class="form-control" name="extra_info" id="FormControlTextarea" rows="3">Example of some info</textarea>
</div>
</div>
<div class="form-group" style="margin-top: 20px;">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">Update</button> <!-- Responsible for updating the router -->
Cancel
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#myModal" style="float: right"> <!-- Responsible for the delete modal to open -->
Delete
</button>
</div>
</div>
</form>
You never passed request.POST and rquest.FILES. If you want to update the fields and files, you need to form.save() your form:
if request.method == 'POST':
#Updating the form
form = UpdateRouter(request.POST, request.FILES, instance=Routers.objects.get(sn=pk))
print(form)
print(form.errors)
if form.is_valid():
data = form.cleaned_data
mac = data['mac']
form.save()
print(mac)
return redirect('db_router')
else:
print("Invalid form")
If you do not pass request.POST and/or request.FILES, then Django does not consider the form filled in, and it is never considered valid.
If you pass both files and data, then you need to add the enctype="multipart/form-data" to your <form> tag:
<form enctype="multipart/form-data" class="form-horizontal" action="" method="post">
<!-- -->
</form>
you need to create a bound_form
form = UpdateRouter(request.POST)
form = UpdateRouter(request.POST) binds the data to the form class. then validate
the inputs using is_valid().