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)
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 am making a personal training website and am having trouble getting the profile pic to upload
my form looks like this:
<form class="form-horizontal" action="updateProfile" method="post" enctype= "multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label class="control-label col-sm-2" for="gym">Main Gym</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="gym" placeholder="Enter gym name" name="gym" id="gym">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="last name">Qualifications</label>
<div class="col-sm-10">
<textarea name="qualifications" rows="10" cols="130" name="qualifications" id="qualifications"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="last name">About Me</label>
<div class="col-sm-10">
<textarea name="aboutme" rows="10" cols="130" id="aboutme"></textarea>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="servicedetails">Service Details</label>
<div class="col-sm-10">
<textarea name="servicedetails" rows="10" cols="130" id="servicedetails"></textarea>
</div>
<div class="form-group">
<label for="avatar">Choose a profile picture:</label>
<div class="form-group">
<input type="file"
id="avatar" name="avatar"
accept="image/png, image/jpeg">
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
models.py:
class trainerabout(models.Model):
userID = models.IntegerField()
gym = models.TextField(max_length=30)
qualifications = models.TextField()
aboutme = models.TextField()
servicedetails = models.TextField()
profilepic = models.ImageField(upload_to='images/')
added this to urls.py
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py:
def updateProfile(request):
if request.method == 'POST':
gym = request.POST['gym']
qualifications = request.POST['qualifications']
aboutme = request.POST['aboutme']
servicedetails = request.POST['servicedetails']
avatar = request.POST['avatar']
trainer = trainerabout(gym=gym, qualifications=qualifications, aboutme=aboutme, servicedetails=servicedetails, profilepic=avatar, userID=request.user.id)
trainer.save()
return render(request, 'updateProfile.html')
added this to settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
when I enter in stuff on my form it saves the url of the image to the database no problem but the image doesn't get saved into the media folder. I was under the impression that it created a media folder for you but it didn't. I then created a media folder and still nothing. What am I doing wrong here?
You should be using request.FILES, not request.POST to access uploaded files. Please, see Django docs for more. And, it is convention that model names are Capitalized at each containing word, like TrainerAbout, not trainerabout.
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')
trying to setting up a small website,a newbie in django . when i create a newsletter setup in django, but the email not saving the admin panel. here is my codes. take a look .
models.py
class Newsletter(models.Model):
email = models.CharField(max_length=200)
def __str__(self):
return self.email
views.py
def Newsletter(request):
if request.method=="POST":
email = request.POST.get("email")
email = email(email=email)
email.save()
message.success(request, "email Successfully added")
return render(request, 'index.html')
urls.py
path('newsletter', views.Newsletter, name="newsletter"),
template
<div id="mc_embed_signup" class="subscribe-form subscribe-form-dec subscribe-mrg">
<form id="Newsletter" class="validate subscribe-form-style" novalidate="" name="Newsletter" method="post" action="/Newsletter">
<div id="mc_embed_signup_scroll" class="mc-form">
<input class="email" type="email" required="" placeholder="Your email address…" name="Newsletter" value="" id="Newsletter">
<div class="mc-news" aria-hidden="true">
<input type="text" value="" tabindex="-1" name="Subscribers">
</div>
<div class="clear">
{% csrf_token %}
<input id="mc-embedded-subscribe" class="button" type="submit" name="subscribe" value="Subscribe">
</div>
</div>
models.py
class Newsletter(models.Model):
email = models.CharField(max_length=200)
def __str__(self):
return self.email
views.py:
Here maybe you are overriding the name of the view with the name of Model, try this:
from .models import Newsletter
def adding_email_to_newsletter(request):
if request.method=="POST":
email = request.POST.get("email")
Newsletter.objects.get_or_create(email=email)
message.success(request, "email Successfully added")
return render(request, 'index.html')
the urls.py
path("adding_email_to_newsletter", views.adding_email_to_newsletter, name="adding_email_to_newsletter"),
template:
Here you miss the csrf_token that is required for post submits by default docs and the using of the tag url for best practices.
<div id="mc_embed_signup" class="subscribe-form subscribe-form-dec subscribe-mrg">
<form id="Newsletter" class="validate subscribe-form-style" novalidate="" name="Newsletter" method="post" action="{% url 'adding_email_to_newsletter' %}">
{% csrf_token %}
<div id="mc_embed_signup_scroll" class="mc-form">
<input class="email" type="email" required="" placeholder="Your email address…" name="Newsletter" value="" id="Newsletter">
<div class="mc-news" aria-hidden="true">
<input type="text" value="" tabindex="-1" name="Subscribers">
</div>
<div class="clear">
{% csrf_token %}
<input id="mc-embedded-subscribe" class="button" type="submit" name="subscribe" value="Subscribe">
</div>
</div>
</form>
</div>
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/