ValueError at /signup/ The given username must be set - python

so basically I have been building this blogging website and now I am stuck at this point of the Signup process, the whole work is done using django
views.py:
def handleSignup(request):
if request.method == 'POST':
# getting user parameters
username = request.POST.get('username')
fname = request.POST.get('fname')
lname = request.POST.get('lname')
email = request.POST.get('email')
pass1 = request.POST.get('pass1')
pass2 = request.POST.get('pass2')
# fname = request.POST['fname']
# lname = request.POST['lname']
# email = request.POST['email']
# pass1 = request.POST['pass1']
# pass2 = request.POST['pass2']
# creating users
myuser = User.objects.create_user(username = username, email = email, password = pass1)
myuser.first_name = fname
myuser.last_name = lname
myuser.save()
messages.success(request, 'your account have been successfully created!')
return redirect(request, 'home')
else:
return HttpResponse("error 404 not found")
form in base.html:
<form action="/signup/" method="post">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" placeholder="choose a unique username">
</div>
<div class="form-group">
<label for="fname">Firstname</label>
<input type="text" class="form-control" id="fname" placeholder="First Name">
</div>
<div class="form-group">
<label for="lname">Lastname</label>
<input type="text" class="form-control" id="lname" placeholder="Last Name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" placeholder="email#example.com">
</div>
<div class="form-group">
<label for="pass1">Choose Password</label>
<input type="password" class="form-control" id="pass1">
</div>
<div class="form-group">
<label for="pass2">Confirm password</label>
<input type="password" class="form-control" id="pass2">
</div>
{% csrf_token %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
now I am getting this error:
ValueError at /signup/
The given username must be set
Request Method: POST
Request URL: http://127.0.0.1:8000/signup/
Django Version: 3.1
Exception Type: ValueError
Exception Value:
The given username must be set
Exception Location: C:\Users\jayant nigam\projects\practise\lib\site-packages\django\contrib\auth\models.py, line 135, in _create_user
Python Executable: C:\Users\jayant nigam\projects\practise\Scripts\python.exe
Python Version: 3.8.5
Python Path:
['C:\\Users\\jayant nigam\\projects\\everythingcs',
'C:\\Python38\\python38.zip',
'C:\\Python38\\DLLs',
'C:\\Python38\\lib',
'C:\\Python38',
'C:\\Users\\jayant nigam\\projects\\practise',
'C:\\Users\\jayant nigam\\projects\\practise\\lib\\site-packages']
Server time: Mon, 28 Sep 2020 16:21:27 +0000
as you guys can see in views.py I have already tried fname = request.POST['fname'] but then I was getting the MultiValueDictKeyError for which I searched on net and got a suggestion to use request.POST.get(' ') and after using that I am facing the above error

You have to add name to your input field in HTML:
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name="username" placeholder="choose a unique username">
</div>
You are not giving name in any of the input field. Server takes data from the form on the basis of name, but not id. So, provide name to each input tag in your form. And, you are good to go.

Related

How to fix "Method not allowed" error in Python Flask app

I have a defined route in my Python Flask app(which worked fine).
#app.route('/insertpage', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
companyname = request.form['companyname']
username = request.form['username']
userpass = request.form['password']
new_company= Grocery(companyname=companyname,
username=username, userpass=userpass)
try:
db.session.add(new_company)
db.session.commit()
return render_template('index.html', data=Todos.query.all())
except:
return "The problem occurred while adding a new company...."
else:
groceries = Grocery.query.order_by(Grocery.created_at).all()
return render_template('index.html', groceries=groceries)
And I am collecting information in my HTML page:
<form action="/" method="POST">
<div class="form-row">
<div class="col-sm-3 my-1">
<label for="newStuff" class="sr-only">New company:</label>
<input type="text" class="form-control" name="companyname" id="newStuff" placeholder="Enter name of new company">
</div>
<div class="col-sm-3 my-1">
<label for="newStuff" class="sr-only">New username:</label>
<input type="text" class="form-control" name="username" id="newStuff" placeholder="Enter username...">
</div>
<div class="col-sm-3 my-1">
<label for="newStuff" class="sr-only">New password:</label>
<input type="text" class="form-control" name="password" id="newStuff" placeholder="Enter password...">
</div>
<div class="col-sm-3 my-1">
<button type="submit" class="btn btn-primary btn-block">Add</button>
</div>
</div>
</form>
After a couple of successful CRUD operations, I am facing the following error(even if I defined 'POST' and 'GET' in my def).
Method Not Allowed
The method is not allowed for the requested URL.
The action attribute of your HTML form needs to match the name of your Flask route.
Your page is sending a POST to url '/' , so it isn't hitting your route, which is for the path '/insertpage'
You should change it to <form action="/insertpage" method="POST">

ValueError: The given username must be set. Error Occured Using Django for registering User

raise ValueError('The given username must be set') using django python
...
I have been trying to register a user using from django.contrib.auth.models import user
Views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.models import User
# Create your views here.
def register(request):
if request.method == 'POST':
username = request.POST.get('username')
email = request.POST.get('email')
password1 = request.POST.get('password1')
password2 = request.POST.get('password2')
if password1 == password2:
if User.objects.filter(username = username).exists():
return redirect('register')
elif User.objects.filter(email = email).exists():
return redirect('register')
else:
user=User.objects.create_user(username = username,password =password1, email = email)
user.save()
return redirect('login')
else:
return redirect('/')
else:
return render(request, 'register.html')
def login(request):
return render(request, 'login.html')
register.html
<form method="POST" action="{% url 'register' %}">
{% csrf_token %}
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username">
</div>
<div class="form-group">
<label for="password1">Password</label>
<input type="password" class="form-control" id="password1">
</div>
<div class="form-group">
<label for="password2">AGAIN Password</label>
<input type="password" class="form-control" id="password2">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" placeholder="name#example.com">
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="check">
<label class="form-check-label" for="check">Check me out</label>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
user=User.objects.create_superuser(username = username,password =password1, email = email)
I want to know that why it is just sending that The given username is must be set but instead I have set super_user already. How to resolve this? It is not getting the username by POST method or is there any other mistake which I am ignoring?
add name attribute in your input tags, something like this:
...
<input type="text" class="form-control" id="username" name="username">
...
<input type="password" class="form-control" id="password1" name="password1">
...
<input type="password" class="form-control" id="password2" name="password2">
...
<input type="email" class="form-control" id="email" name="email" placeholder="name#example.com">
...
I think your problem here is the use of request.POST. If this is a form, you probably want to change this to be request.form wherever you're using request.POST. At the moment, your line request.POST.get("username") is returning None, so when you try to save the user it complains.
The Authentication system might be a little bit tricky if this is your first time doing it. I am going to link you with this project that i did a while ago; it has an authentication system with Django; it can help you out :
https://github.com/Nouamanezh909/BLog_repo.
--Go to Accounts, there you will find (
forms , view , everything you need.
)

can't get the POST parameters in django

I am trying to make a login-page using django, I am facing troubles in getting POST parameters
login view:
def ProcLogin(request):
if request.method == 'POST':
account_name = request.POST.get('username','')
password = ToMd5(request.POST.get('password',''))
if not account_name or not password: return HttpResponse("invalid input")
template code:
<form method="post" action="{% url 'Main:login' %}" class="login_form">
{% csrf_token %}
<div class="form-group text-right">
<label for="username">User name:</label>
<input id="username" type="text" class="form-control box_shadow">
</div>
<div class="form-group text-right">
<label for="password">Password: </label>
<input id="password" type="password" class="form-control box_shadow">
</div>
<button type="submit" class="login_btn"></button>
</form>
Output when testing it:
invalid input
everything is supposed to be correct except the results aren't. Thank you.

Django doesn't read form

I have form:
<form id="contact-form" class="contact__form" method="POST" action="{% url 'backcall' %}">
{% csrf_token %}
<span class="text-color">Send letter</span>
<div class="form-group">
<input name="name" type="text" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<input type="tel" name="phone" class="form-control" placeholder="Phone (+380)" pattern="[\+][3][8][0]\d{9}" minlength="13" maxlength="13" />
</div>
<div class="form-group">
<input name="email" type="email" class="form-control" placeholder="Email">
</div>
<div class="form-group-2 mb-4">
<textarea name="message" class="form-control" rows="4" placeholder="Your letter"></textarea>
</div>
<button class="btn btn-main" name="submit" type="submit">Send</button>
</form>
views.py:
def backcall(request):
backcall = BackCall(name = request.POST['name'], phone = request.POST['phone'], email=request.POST['email'] , message = request.POST['message'])
backcall.save()
return redirect('thanks')
models.py
class BackCall(models.Model):
name = models.CharField(max_length=50)
phone = models.CharField(max_length=13)
email = models.EmailField()
message = models.TextField(default=None)
datetime = models.DateTimeField(auto_now_add=True)
When I fill out the form and submit nothing happens. When I follow the link 'backcall/' I get an error.
What the problem can be connected with and how to fix it?
Please, search more, exist the solution
Use the MultiValueDict's get method. This is also present on
standard dicts and is a way to fetch a value while providing a default
if it does not exist.
def backcall(request):
backcall = BackCall(name = request.POST.get('name'), phone = request.POST.get('phone'), email=request.POST.get('email') , message = request.POST.get('message'))
backcall.save()
return redirect('thanks')
You should check whether or not the record exists in your database, I think, a quick example would be:
def backcall(request):
obj, created = BackCall.objects.get_or_create(email=request.POST.get('email'),
defaults={'phone': request.POST.get('phone'),
'name': request.POST.get('name'),
'message': request.POST.get('message')}
if created:
return redirect('thanks')
return ...

Data not appearing in database after form submission

I have created an HTML form trying to do simple registration.
The problem is that after clicking submit button no error appears but when I chech database the data from fields is not there.
signup.html
<form action="\polls\Registration" method="POST">
<div class="form-group mb15">
<input type="text" class="form-control" name="userName" placeholder="Enter Your Username" required>
</div>
<div class="form-group mb15">
<input type="password" class="form-control" name="password" placeholder="Enter Your Password">
</div>
<div class="form-group mb15">
<input type="text" class="form-control" name="fullName" placeholder="Enter Your Full Name">
</div>
<div class="form-group mb20">
<label class="ckbox">
<input type="checkbox" name="checkbox">
<span>Accept terms and conditions</span>
</label>
</div>
<div class="form-group">
<button class="btn btn-success btn-quirk btn-block">Create Account</button>
<br>
Already a member? Sign In Now!
</div>
</form>
forms.py
class RegistrationForm(forms.Form):
userName= forms.CharField(label='Username',max_length=100)
password = forms.CharField(label='Password', max_length=100)
fullName= forms.CharField(label='Full Name', max_length=100)
myview.py
def reg(request):
if request.method == 'POST':
the request:
form = forms.RegistrationForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/polls/signin')
else:
form = forms.RegistrationForm()
return render(request, 'signup.html', {'form': form})
urls.py
urlpatterns = [
url(r'^Registration', myview.reg,name='Registration'),
]
[SOLVED]
What I did is that I created a model to handle form processing.I also used modelForm instead of forms. For anyone having same issue check this

Categories

Resources