2 form at the same page flask - python

Hello guys hope u doing fine, I got this project and in home page of my website i have two form
1 to login and the other to upload a file however every time i submit with any form the same function keeps getting executed please help.
this is the html code
<!--login-->
<section class="bg-dark text-light p-5 text-center">
<div class="container">
<h2>First step </h2>
<form action = "http://localhost:5000" method="post" name="login" >
<div class="col">
<div class="hide-md-lg">
<h4>Sign in to your <span class="text-warning">Linkedin account</span> </h4>
</div>
<br>
<input type="text" name="username" placeholder="Username" required>
<br><br>
<input type="password" name="password" placeholder="Password" required>
<br><br>
<input class="btn btn-primary" type="submit" value="Login">
</div>
</form>
</div>
</section>
<!--upload excel-->
<section class="bg-dark text-light p-4">
<div class="container bg-primary rounded border-0 p-5">
<div class="d-md-flex justify-content-between align-items-center">
<div class="container">
<h5 class="mt-2">Choose an excel file</h5>
<h6 class="mb-3"><span class="text-warning">NB: first 2 columns have to be: "Prénom" and "Nom"</span></h6>
</div>
<form class="input-group" action = "http://localhost:5000" method = "POST" enctype = "multipart/form-data" name="upload">
<input class="form-control size-file" type="file" name="file" id="formFile">
<input class="btn btn-dark" type = "submit" value="Start scraping" >
</form>
</div>
</div>
</section>
and this is the backend part
#app.route('/', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST' :
f = request.files['file']
f.save(secure_filename(f.filename))
df = pd.read_excel(f.filename)...............
#app.route('/', methods = ['GET', 'POST'])
def login_info():
if request.method == 'POST' and 'Sign in to your' in request.form['h4']:
user_info = request.form.get("username")
pass_info = request.form.get("password")

Although unable to try it this way, I updated your code with different action parameters.
<!--login-->
<section class="bg-dark text-light p-5 text-center">
<div class="container">
<h2>First step </h2>
<form action = "{{url_for('login_info')}}" method="post" name="login" >
<div class="col">
<div class="hide-md-lg">
<h4>Sign in to your <span class="text-warning">Linkedin account</span> </h4>
</div>
<br>
<input type="text" name="username" placeholder="Username" required>
<br><br>
<input type="password" name="password" placeholder="Password" required>
<br><br>
<input class="btn btn-primary" type="submit" value="Login">
</div>
</form>
</div>
</section>
<!--upload excel-->
<section class="bg-dark text-light p-4">
<div class="container bg-primary rounded border-0 p-5">
<div class="d-md-flex justify-content-between align-items-center">
<div class="container">
<h5 class="mt-2">Choose an excel file</h5>
<h6 class="mb-3"><span class="text-warning">NB: first 2 columns have to be: "Prénom" and "Nom"</span></h6>
</div>
<form class="input-group" action = "{{url_for('upload_file')}}" method = "POST" enctype = "multipart/form-data" name="upload">
<input class="form-control size-file" type="file" name="file" id="formFile">
<input class="btn btn-dark" type = "submit" value="Start scraping" >
</form>
</div>
</div>
</section>
And the #app.route should lead to two function :
#app.route('/upload_file', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST' :
f = request.files['file']
f.save(secure_filename(f.filename))
df = pd.read_excel(f.filename)...............
#app.route('/login_info', methods = ['GET', 'POST'])
def login_info():
if request.method == 'POST' and 'Sign in to your' in request.form['h4']:
user_info = request.form.get("username")
pass_info = request.form.get("password")
If you want both those page to return to your home screen, you just have to tell them to return to this same template with render_template() or redirect()

Related

How can I fix my code For Django's reply comment

When entering a reply comment,
It will be redirected to my post with comments
How can I fix it? Please Someone help me
post_detail.html
<!-- Reply Button Area -->
<button class="btn btn-sm btn-secondary" type="button" style="float:right" data-toggle="collapse" data-target="#replyBox{{comment.id}}" aria-expanded="false" aria-controls="replyBox{{comment.id}}">
Reply
</button>
<div class="collapse" id="replyBox{{comment.id}}">
<div class="card card-body my-2">
<form action="/blog/{{ comment.pk }}/reply_comment/" method="post">
{% csrf_token %}
<div class="form-group">
<label for="comment">Reply </label>
<input type="text" class="form-control" name="comment" placeholder="type the comment">
<input type="hidden" name="parentSno" value="{{comment.id}}">
</div>
<input type="hidden" name="post.pk" value="{{post.pk}}">
<button type="submit" class="btn btn-sm btn-primary">Complete</button>
</form>
</div>
</div>
<!-- Reply Button Area END -->
Views.py
def reply_comment(request , comment_pk) :
if request.user.is_authenticated :
comment = get_object_or_404(Comment , pk=comment_pk)
if request.method == 'POST' :
recomment_form = ReCommentForm(request.POST)
if recomment_form.is_valid() :
recomment = recomment_form.save(commit=False)
recomment.author = request.user
recomment.comment = comment
recomment.save()
return redirect(comment.get_absolute_url())
return redirect(comment.post.get_absolute_url())
else :
raise PermissionError
It's the github address with the code
Thank you !!!
https://github.com/JaehyoJJAng/doitdjnago_help/tree/c36a75bf089ceb027c9cf9f5c184ac37f77f3788

i can't create user in django

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

form.is_valid() not working when using django forms for updating information to the databse

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().

Problem in getting data from form in flask

I am basically creating a flask web app which takes username from user and gets his /her codeforces data I am having a problem in extracting the email-id
from the form. I am getting the username but not the email-id.They are both in one form tag in the html file.
Error in browser:
werkzeug.exceptions.HTTPException.wrap..newcls: 400 Bad Request: KeyError: 'email-id'
<form method="POST">
<div class="field">
<label class="label">Username:</label>
<div class="control">
<input class="input" type="text" placeholder="Enter Codeforces username" name="username" value="{{user.handle}}"></input>
</div>
</div>
<div class="has-text-centered">
<input class="button is-link" name="get-info" type="submit" value="Get Info">
</div>
<div class="field">
<label class="label">EMail id:</label>
<div class="control">
<input class="input" type="text" placeholder="Enter mail id" name="email-id" value="">
</div>
</div>
<div class="has-text-centered">
<input class="button is-link" name="get-mail" type="submit" value="Get Mail">
</div>
</form>
#app.route('/',methods=['GET','POST'])
def index():
if request.method == 'POST':
username = request.form['username']
email_id = request.form['email-id']
print(email_id)
print(username)

How to get checked multiple radio input value in flask?

I am making a quiz app. I want to send back the values of checked radio inputs after form has been submitted.Howto send the values in dict format. like this: { 1:A,2:B...}
FLASK
app.route('/test', methods=['GET','POST'])
#is_logged_in
def test():
if request.method == 'POST':
app.logger.info(request.form)//What to do here?
#create cursor
cur=mysql.connection.cursor()
cur.execute("SELECT * FROM questions")
data = cur.fetchall()
return render_template('quiz.html', data=data)
HTML
<form action="" class="text-left ml-4" method="POST">
{% for i in data %}
<h5>{{i['id']}}. {{i['question']}}</h5>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="radio" name="option" value="A"
> {{i['chA']}}
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="radio" name="option" value="B">{{i['chB']}}
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="radio" name="option" value="C" > {{i['chC']}}
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="radio" name="option" value="D" > {{i['chD']}}
</label>
</div>
<br>
{% endfor%}
<div class="col-md-12 text-center mb-1">
<button type="submit" class="btn-new btn-lg"> Submit </button>

Categories