Having two forms in one HTML page - html

I wanted to have a page for both sign up and login. However I couldn't handle the two forms. Here is my code.
I was wondering myself if it is possible to give names to the forms or handle it in another way?
forms.py
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
class UserCreateForm(UserCreationForm):
class Meta:
fields = ("username", "email", "password1", "password2")
model = get_user_model()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["username"].label = "Display name"
self.fields["email"].label = "Email address"
url.py
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts'
urlpatterns = [
url('', views.SignUp.as_view(), name="signup"),
url('', auth_views.LoginView.as_view(template_name="index.html"),name='login'),
url('', auth_views.LogoutView.as_view(), name="logout"),
]
index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="container">
<h1>Login</h1>
<form method="POST">
{% csrf_token %}
{{ form }}
<input type="submit" class="btn btn-default">
</form>
</div>
<div class="container">
<h1>Sign Up</h1>
<form method="POST" >
{% csrf_token %}
{{ form }}
<input type="submit" class="btn btn-default">
</form>
</div>
</body>
</html>
Thank You very much

I believe this post has the answer you need. Here are my thoughts on the information:
Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms. This will sometimes be a bit messy as some CBVs require a primary key and others do not, which may lead to conflicts.
Read the submit button values from the POST data. You can tell which submit button was clicked: How can I build multiple submit buttons Django form? This is the one that I prefer as it's cleaner to implement.

Actually i want able to POST and my apologies. in short you have to use Fetch API for this

Related

Send Image from Flask to HTML is not successful

I would like to send image with Flask app when I click to predict button in my html code.
Code is supposed to get prompt and run ML model and generate image based on input prompt. I can generate the picture but somehow I can not send it to html or html doesn't show the image.
Anyone can check my flask and html code where the problem is ? My flask image send method is wrong or html part is wrong ? How to show the image in html ?
import os
import io
import base64
from PIL import Image
import torch
from torch import autocast
from diffusers import StableDiffusionPipeline, LMSDiscreteScheduler
import transformers
from flask import Flask, render_template, request
app = Flask(__name__)
lms = LMSDiscreteScheduler(
beta_start=0.00085,
beta_end=0.012,
beta_schedule="scaled_linear"
)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
pipe = StableDiffusionPipeline.from_pretrained(
"CompVis/stable-diffusion-v1-4",
scheduler=lms,
use_auth_token=True,
cache_dir=os.getenv("cache_dir", "./models")
).to("cuda")
#app.route('/', methods=['GET'])
def page_template():
return render_template('index.html')
#app.route('/', methods=['POST'])
def predict():
prompt_text = request.form['word']
with autocast("cuda"):
image = pipe(prompt_text)["sample"][0]
data = io.BytesIO()
image.save(data, "JPEG")
encoded_img_data = base64.b64encode(data.getvalue())
return render_template("index.html", img_data=encoded_img_data.decode('utf-8'))
if __name__ == '__main__':
app.run()
<!DOCTYPE html>
<html>
<head>
<title>Tutorial</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">
</head>
<body>
<h1 class="text-center">Stable Diffusion</h1>
<form class="p-3 text-center" action='/', method="post" enctype="multipart/form-data" >
<label for="promptfield" class="form-label">StableDiffusionPrompt</label>
<input type="text" class="form-control" id="promptfield" name="word" placeholder="Please enter your prompt" />
<input class="form-control" type="file" name="imagefile" >
<input class="btn btn-primary mt-3" type="submit" value="Predict Image" >
</form>
{% if prediction %}
<img id="picture" src="data:image/jpeg;base64,{{ img_data }}">
<p> img id="picture" src="data:image/jpeg;base64,{{ img_data }}"</p>
{% endif %}
</body>
</html>
here is the output of encoded_img_data.decode('utf-8').

Have CSS connected in HTML in a Flask project

<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<div class = "tela">
<h1>Login</h1>
<form action="/" method = "post">
<input class = "inf" type="text" placeholder="Email">
<br><br>
<input class = "inf" type="password" placeholder="Senha">
<br><br>
<button class = "main-btt">Log in</button>
</form>
<form action="/criarconta" method="post">
<button class = "criar">Criar conta</button>
</form>
</div>
</body>
</html>
from flask import Flask, request, render_template, redirect
app = Flask("__name__")
#app.route("/")
def index():
return render_template("login.html")
#app.route("/criarconta", methods=["POST"])
def create():
return render_template("criarconta.html")
I'm working on a Login page, with flask, html and css, but always that I run flask the link that shows up is a html page without css, even when I link css in the html file. I want to resolve tis, and finds out how to open the page and the css is there. OBS: When I open the file alone, without flask, it works.
I tried using href="styles.css" but it didn't work so I changed for url_for, but its still not working.
I think the problem is in the html but I putted the python if you need.

Django How to display a link from user input form safely

I have an model (posts) that is tied to a form that when a certain character is used it creates a link to another portion of the web app. The user can enter several of these characters/links to different areas of the webpage in one post then I want to display all of the users posts to the user in a list looping over the model that stores the link. However, how can I do this while maintaining security? I do not want to allow the user to enter in HTML and it be rendered.
For example:
User enters form information:
"Hello this is a #test and #about is a test too"
User selects submit button and background magic to get the words test and about and convert them into links to take the user to the test and about pages in the web application.
Display all of the inputs/posts that have been created:
"Hello this is a #test and #about is a test too"
I know that I can use the safe tag and just store the HTML link in the model and call like normal but since this is from user input I don't want to allow them to create HTML inside of the input form. How can I achieve this desired result safely?
Loosely what I have now:
views.py
def index(request):
if request.method == "POST":
post_form = PostForm(request.POST, request.FILES)
if post_form.is_valid():
# TODO Add background magic here
post_form.save()
messages.success(request, ('Your post was successfully added!'))
else:
messages.error(request, 'Error saving form')
return redirect("/posts")
post_form = PostForm()
posts = Post.objects.all()
return render(request=request, template_name="posts/page.html", context={'post_form':post_form, 'posts':posts})
page.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Testing</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ post_form }}
<button class="btn btn-primary my-4" type="submit">Submit</button>
</form>
{% for post in posts %}
<p>{{post.id}}</p>
<p>{{post.post}}</p>
{% endfor %}
</body>
</html>

django queryset not showing accurate result (building a news app)

I am creating a news app using django. It consists of search by date option. When i choose the date(ex:29-11-2020) and click submit, It should take me to the news of that particular day. When i try the below code instead of showing the details it is giving me a blank page.
views.py
from django.shortcuts import render
from .models import *
from django.views.generic.detail import DetailView
from django.views.generic import ListView
def index(request):
return render(request,'newspaperapp/index.html')
class nowlist(ListView):
model = newsmodel_1
template_name = 'newspaperapp/index.html'
class newslist(DetailView):
model = newsmodel_1
template_name = 'newspaperapp/home.html'
context_object_name = 'newspaperapp'
# search by giving date in index and search date
class SearchView(ListView):
model = newsmodel_1
template_name = 'newspaperapp/search.html'
context_object_name = 'all_search_results'
def get_queryset(self):
result = super(SearchView, self).get_queryset()
query = self.request.GET.get('search')
if query:
postresult = newsmodel_1.objects.filter(date_published__contains=query)
result = postresult
else:
result = None
return result
urls.py
from django.urls import path
app_name = 'newspaperapp'
from .views import newslist,SearchView,nowlist
from newspaperapp import views
urlpatterns = [
path('',views.index,name='index'),
path('date/',nowlist.as_view(),name = "date"),
path('<int:pk>',newslist.as_view(),name = "home"),
path('results/', SearchView.as_view(), name='search'),
]
newspaperapp/home.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>Today's Paper</p>
{{newspaperapp.date_published}}
{{newspaperapp.category}}
</body>
newspaperapp/index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- this page has search option and different categories of news -->
<!-- to create search option we write views code and continue -->
<form class="form-inline my-2 my-lg-0" method="GET" action="{% url 'newspaperapp:search' %}">
<input class="form-control mr-sm-2" type="date" placeholder="Search" aria-label="Search"
name="search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
{%for newspaperapp in object_list %}
<li>{{newspaperapp.title}}
{{newspaperapp.date_published}}
{%endfor%}
</ul>
</body>
</html>
newspaperapp/search.html
{% block content %}
{% for newspaperapp in all_search_results %}
<h3></h3>
{% empty %}
<h2>No results found</h2>
{% endfor %}
{% endblock %}
Contain usually translated to LIKE in sql typically is used to search for a specified text pattern in a column.
If you want to filter date, you could convert query it to datetime object, and search the objects in that particular date range using gte and lt lookups.
from datetime import datetime, timedelta
class SearchView(ListView):
model = newsmodel_1
template_name = 'newspaperapp/search.html'
context_object_name = 'all_search_results'
def get_queryset(self):
result = super(SearchView, self).get_queryset()
query = self.request.GET.get('search')
# query is of type 'str', convert to datetime
start_day = datetime.fromisoformat(query)
end_day = start_day + timedelta(days=1)
if query:
postresult = newsmodel_1.objects.filter(
date_published__gte=start_day,
date_published__lt=end_day
)
result = postresult
else:
result = None
return result
Note: add more logic to handle query is None

Django form not being submitted

I have a Django model/view/form that is rendering correctly in the template, but it is not submitting the data that is input to the database. Any help with this would be greatly appreciated!
#models.py
from django.db import models
from django.forms import ModelForm
class UserRegistration(models.Model):
user_first = models.CharField(max_length=50)
user_last = models.CharField(max_length=50)
user_email = models.EmailField()
#user_fantasyhost = models.CharField(max_length=50)
def __unicode__(self):
return u'%s %s %s' % (self.user_first, self.user_last, self.user_email)
class RegForm(ModelForm):
class Meta:
model = UserRegistration
#views.py
from django.shortcuts import render_to_response
from django.shortcuts import render
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
from acme.dc_django.models import UserRegistration
from acme.dc_django.models import RegForm
def regPage(request, id=None):
form = RegForm(request.POST or None,
instance=id and UserRegistration.objects.get(id=id))
if request.method == 'POST' and form.is_valid():
form.save()
return HttpResponseRedirect('/league_setup/')
user_info = UserRegistration.objects.all()
context = {
'form':form,
'user_info' :user_info,
}
return render(request, 'regpage.html', context)
#repage.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML lang="en">
<head>
<title>User Registration</title>
</head>
<body>
<form method="POST" action="/league/">
{% csrf_token %}
<table>{{ form }}</table>
<input type="submit" value="Create Account"
</form><br /><br />
</body>
</HTML>
Thank you for your help,
dp
I tried your code. Your problem is that the action attribute of your html form tag is set to "/league/".
Unless reqPage url is actually "/league/", it won't work. When i changed action="/league/" to action="" as such:
<HTML lang="en">
<head>
<title>User Registration</title>
</head>
<body>
<form method="POST" action="">
{% csrf_token %}
<table>{{ form }}</table>
<input type="submit" value="Create Account" />
</form><br /><br />
</body>
</HTML>
The form did work:
In [3]: UserRegistration.objects.all()
Out[3]: [<UserRegistration: aoeu oeu oeu#aeou.com>]