<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form method="POST">
{% csrf_token %} {{ form.as_p }}
<input type="submit" value="Submit" />
</form>
</body>
</html>
class Post(CreateView):
fields = ("title","about","itempicture")
template_name = "post.html"
model = models.Listing
I can't seem to figure out why is is not working my html and views connect perfectly put when try to send in a post request it does not work I would happy if someone could help me out
You should define your form in the view:
class Post(CreateView):
fields = ("title","about","itempicture")
template_name = "post.html"
model = models.Listing
form_class = YourForm
Related
I have a simple flask application that looks like that : MyFlaskAPP
the problem is i don't know if it's possible or not to add an "infinite amount" of comments and show them in the page of the software associated
for infos my list.html will be the interface for "admins" and list_user.html is the "user interface" because i don't want users to delete or modify thoses datas.
if somone could help me of give me somes tips btw here is my code :
app.py
from flask import Flask, render_template, redirect, url_for, request
from flask_sqlalchemy import SQLAlchemy
import time
# create the extension
db = SQLAlchemy()
# create the app
app = Flask(__name__)
# configure the SQLite database, relative to the app instance folder
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///web_solinest.db"
# initialize the app with the extension
db.init_app(app)
class Webapp(db.Model):
id = db.Column(db.Integer, primary_key=True)
nom = db.Column(db.String)
pastille = db.Column(db.String)
description = db.Column(db.String)
update_time = db.Column(
db.String, default=time.strftime("%m-%d-%Y %H:%M"))
with app.app_context():
db.create_all()
#app.route("/solistatus")
def show_all():
webapps = db.session.execute(
db.select(Webapp).order_by(Webapp.nom)).scalars()
return render_template("webapp/list_user.html", webapps=webapps)
#app.route("/admin")
def webapp_list():
webapps = db.session.execute(
db.select(Webapp).order_by(Webapp.nom)).scalars()
return render_template("webapp/list.html", webapps=webapps)
#app.route("/solistatus/create", methods=["GET", "POST"])
def webapp_create():
if request.method == "POST":
webapps = Webapp(
nom=request.form["nom"],
pastille=request.form["pastille"],
description=request.form["description"]
)
db.session.add(webapps)
db.session.commit()
return render_template("webapp/create.html")
#app.route("/solistatus/update/<int:id>", methods=["GET", "POST"])
def webapp_update(id):
webapp = Webapp.query.get(id)
if request.method == "POST":
webapp.nom = request.form["nom"]
webapp.pastille = request.form["pastille"]
webapp.description = request.form["description"]
webapp.update_time = time.strftime("%m-%d-%Y %H:%M")
db.session.commit()
return render_template("webapp/update.html", webapp=webapp)
#app.route("/solistatus/<int:id>/delete", methods=["GET"])
def webapp_delete(id):
webapps = Webapp.query.get(id)
db.session.delete(webapps)
db.session.commit()
return redirect(url_for('webapp_list'))
list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght#300;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<title>Admin page</title>
</head>
<body>
<h3>Add Software</h3>
<table class="display_table">
<thead>
<tr>
<th style="width: 10px;">Pastille</th>
<th style="width: 300px;">Nom</th>
<th>ID</th>
</tr>
</thead>
<tbody>
{% for Webapp in webapps %}
<tr>
<td class="tiny"><img style="width: 40px;"
src="https://icones.pro/wp-content/uploads/2021/04/icone-cercle-rempli-{{Webapp.pastille }}.png"
style="width: 10%;" alt=""></td>
<td>{{ Webapp.nom }}</td>
<td>{{ Webapp.id }}</td>
<td>Delete</td>
<td>Update</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
create.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght#300;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<title>Create page</title>
</head>
<html>
<body>
<h3>Software creation</h3>
Home page<br>
<form action="{{ request.path }}" method="post">
<label for="pastille">Pastille</label><br>
<select type="text" name="pastille" id="pastille" class="form-control">
<option value="vert">Vert</option>
<option value="rouge">Rouge</option>
</select><br>
<label for="nom">Nom</label><br>
<input type="text" name="nom" placeholder="nom" /><br>
<label for="description">Description</label><br>
<textarea name="description" placeholder="description"></textarea><br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght#300;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<title>Create page</title>
</head>
<body>
<h1 id="homepage">Home page</h1><br>
<form method="post">
<div class="form-group">
<label for="nom">Nom</label>
<input type="text" class="form-control" id="nom" name="nom" value="{{ webapp.nom }}">
</div>
<div class="form-group">
<label for="pastille">Pastille</label>
<select type="text" name="pastille" id="pastille" class="form-control">
<option value="rouge">Rouge</option>
<option value="vert">Vert</option>
</select>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea type="text" class="form-control" id="description"
name="description">{{ webapp.description }}</textarea>
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</body>
Thank you a lot if someone could help me or inform me I'm interested
i tried to create a new table called history but i don't know how to link the table 1 to the table 2 using the ID and display the comment section of the ID n°1
I'm creating a login, register account website and it works well except for when i use the render template command as it loads the page successfully but then the url of the page is the URL of the previous page and when I refresh it, it goes back to the previous page. But when I use the redirect(url_for command I'm not able to pass variables through it
class LoginForm(FlaskForm):
username= StringField(validators=[InputRequired(),Length(min=4,max=20)],render_kw={"placeholder":"Username"})
password= PasswordField(validators=[InputRequired(),Length(min=8,max=20)],render_kw={"placeholder":"Password"})
submit =SubmitField("Login")
#app.route("/login",methods= ['GET','POST'])
def login():
form=LoginForm()
print("in login html")
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user:
if user.password==form.password.data:
login_user(user)
print("password entered")
userUsername=form.username.data
#return redirect(url_for('dashboard',userUser=userUsername,))
return render_template("dashboard.html",userUser=userUsername)
else:
print("incorrect pass")
return render_template("login.html",form=form)
#app.route("/dashboard",methods= ['GET','POST'])
#login_required
def dashboard():
return render_template("dashboard.html")
this is my python code, my dashboard.html-
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dashboard</title>
<link href = "../static/main.css" rel = "stylesheet">
</head>
<div class = "container1">
<body>
<div data-role="page" id="welcome" data-url="{{ url_for('dashboard') }}">
{%extends "layout.html"%}
{%block content%}
<p>{{userUser}}</p>
<h1>Hello you are logged in. </h1>
<div class = "container1">Welcome {{userUser}}!</div>
<form action ="{{url_for('login')}}" method = POST>
<br> <button type = "submit">Logout</button>
</form>
</div>
{%endblock%}
</body>
</html>
now my login.html
<!DOCTYPE html>
<html lang = "en">
<head>
<link href = "../static/main.css" rel = "stylesheet">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<div class = "container">
<h1>Login</h1>
<form method="POST" actions="">
{{ form.hidden_tag() }}
{{ form.username }}
{{ form.password }}
{{ form.submit }}
</form>
Don't have an account? Sign Up
<div class = "message"> {{errorMessage | safe}}</div>
</div>
</body>
</html>
when i pass userUser through redirect(url_for it doesnt work but with render templates it does but the url remains /login
I've been stuck with this error for a few days and am not able to find where the mistake is.
views section
from django.shortcuts import render,redirect
from django.contrib.auth.models import User,auth
# Create your views here.
def register(request):
if(request.method=='POST'):
username=request.POST['username']
password1=request.POST['password1']
password2=request.POST['password2']
user=User.objects.create_user(username=username,password=password1)
user.save();
print("user created")
return redirect('/')
else:
return render(request,'registration.html')
urls.py section
from django.urls import path
from . import views
urlpatterns=[path('register/',views.register,name="register")]
html section
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration</title>
</head>
<body>
<form action="register" method="POST">
{% csrf_token %}
USERNAME <input type="text" name="username" id=""> <br><br>
PASSWORD <input type="password" name="password1" id=""> <br><br>
RETYPE PASSWORD <input type="password" name="password2" id=""> <br><br>
<input type="submit" value="">
</form>
</body>
</html>
Issue
create_user() doesn't require save() method to be called for creating instance.
You have given only action="register" which is not valid at all, you need to give url tag, to perfectly make route. That's the case for page not found which is the main question.
So, with some modifications try below code:
Views.py
def register(request):
if(request.method=='POST'):
username=request.POST['username']
password1=request.POST['password1']
password2=request.POST['password2']
user=User.objects.create_user(username=username,password=password1)
print("user created")
return redirect('/')
else:
return render(request,'registration.html')
Template file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration</title>
</head>
<body>
<form action="{% url 'register' %}" method="POST">
{% csrf_token %}
USERNAME <input type="text" name="username" id=""> <br><br>
PASSWORD <input type="password" name="password1" id=""> <br><br>
RETYPE PASSWORD <input type="password" name="password2" id=""> <br><br>
<input type="submit" value="Save">
</form>
</body>
</html>
Models:
class ddlname(models.Model):
name=models.CharField(max_length=255)
stdate=models.DateField()
sttime=models.TimeField(default='00:00')
endate=models.DateField()
status=models.ForeignKey(status,on_delete=models.CASCADE,default='Yet To Assign')
def __str__(self):
return self.name
Forms:
from dataclasses import fields
from django import forms
from .models import ddlname
class nameform(forms.ModelForm):
class Meta:
model=ddlname
fields='__all__'
Views:
def home(request):
if request.method=='GET':
form=nameform()
return render(request,'home.html',{'form':form})
else:
form=nameform(request.POST)
if form.is_valid():
form.save()
return redirect('/details')
def details(request):
context={'details':ddlname.objects.all().order_by('stdate','sttime')}
return render(request,'details.html',context)
home template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="#" method="post">
{% csrf_token %}
{{form}}
<button type="submit">submit</button>
</form>
</body>
</html>
details template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<table>
<thead>
<tr>
<td>Name</td>
<td>St Date</td>
<td>St Time</td>
<td>Status</td>
</tr>
</thead>
<tbody>
{% for d in details %}
<tr>
<td>{{d.name}}</td>
<td>{{d.stdate}}</td>
<td>{{d.sttime}}</td>
<td>{{d.endate}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
Requirement:
from home template form, I will input stdate as 22-02-2022 and endate as 25-02-2022 along with name(test) sttime(00:00).
I should get the output as:
test 22-02-2022 00:00 22-02-2022,
test 23-02-2022 00:00 23-02-2022,
test 24-02-2022 00:00 24-02-2022,
test 25-02-2022 00:00 25-02-2022, and get save to DB.
The above mentioned code gives the output as test 22-02-2022 00:00 25-02-2022, request anyone to help me on this issues what i am facing.
I have a small question.
Here is my "Register page":
[![Register page][1]][1]
But when I add my form to the login, for example, I get this:
[![Page with login][2]][2]
I want to know how can I make that form box fit that HTML input field?
I don't know if I have to resize it in the forms.py or if there was a way for it to always bind up the input size that is in the HTML file.
This is the HTML:
{% load static %}
<!DOCTYPE html>
{% csrf_token %}
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>IPV QS Tool Registration</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous"
/>
<link rel="stylesheet" href="registration.css" />
<link rel="stylesheet" type="text/css" href="{% static 'css/style_register.css' %}" />
</head>
<body>
<form method="POST" action="">
<label>
<p class="label-txt">ENTER YOUR AMAZON EMAIL</p>
<input type="email" class="input" required />
<div class="line-box"></div>
<div class="line"></div>
</div>
</label>
<label>
<p class="label-txt">ENTER YOUR AMAZON LOGIN</p>
{{form.username}}
<div class="line-box">
<div class="line"></div>
</div>
</label>
<label>
<p class="label-txt">CREATE A PASSWORD</p>
<input
type="password"
class="input password"
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters"
required
/>
<div class="line-box">
<div class="line"></div>
</div>
</label>
<button type="submit">Submit</button>
</form>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"
></script>
<script src="registration.js"></script>
</body>
</html>
Forms.py:
class createUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
It seems like you are missing class="input" from your input field. Please try this,
username = forms.CharField(max_length=100,
widget= forms.TextInput
(attrs={'class':'input'}))
widget= forms.TextInput(attrs={'class':'input'})
It will result in addition of this class to your CharField.
I hope this helps. Feel free to connect in case if the issue still persists.
Thanks.