I'm trying to get data on_submit from input fields in multiple form fields. But I want to use one submit button from one of the fields. is this even possible?
class Form1(FlaskForm):
entry1 = StringField(('Entry 1'))
class Form2(FlaskForm):
entry2 = StringField(('Entry 2'))
submit = SubmitField(('Register'))
#app.route('/index', methods=['GET', 'POST'])
def index():
form1= Form1()
form2= Form2()
if form2.validate_on_submit():
entry1 = request.form.get('entry1')
entry2= request.form.get('entry2')
flash((entry1))
flash((entry2))
return redirect(url_for('main.index'))
return render_template('index.html', form1=form1, form2=form2)
{% extends "base.html" %}
{% import 'bootstrap/wtf.html' as wtf %}
{% block app_content %}
<div class="row">
<div class="col-md-4">
{{ wtf.quick_form(form1)}}
{{ wtf.quick_form(form2) }}
</div>
</div>
{% endblock %}
You could move the Submit button to a new class that inherits the other forms. From what I understand, validate_on_submit() processes and validates the fields of the called form, which includes any fields of inherited form classes.
class Form1(FlaskForm):
entry1 = StringField(('Entry 1'))
class Form2(FlaskForm):
entry2 = StringField(('Entry 2'))
class FinalForm(Form1, Form2):
submit = SubmitField(('Register'))
Now you only have to refer to the final form in the call and rendering.
#app.route('/', methods=['GET', 'POST'])
def index():
form = FinalForm()
if form.validate_on_submit():
entry1 = request.form.get('entry1')
entry2 = request.form.get('entry2')
flash((entry1))
flash((entry2))
return redirect(url_for('index'))
return render_template('index.html', form=form)
Here were the basic html templates I tested with success, trying to keep with the format you showed.
base.html :
{% extends 'bootstrap/base.html' %}
{% block content %}
<div class="container">
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-info" role="alert">{{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
{% block app_content %}{% endblock %}
</div>
{% endblock %}
index.html :
{% extends "base.html" %}
{% import 'bootstrap/wtf.html' as wtf %}
{% block app_content %}
<div class="row">
<div class="col-md-4">
{{ wtf.quick_form(form) }}
</div>
</div>
{% endblock %}
I am not entirely sure if I understand your problem correctly, but you can use WTForms to build your forms. You'd have to define another class though that holds the both classes with the fields you need to submit.
https://wtforms.readthedocs.io/en/stable/
Related
I have created a custom html template with basic checkboxes to select a value and return the value to the Django admin page.
The value of the selected superprofile does not get captured by the variable "selected_value" in the admin.py
The if statement "if request.method == 'POST':" is getting triggered but i keep getting the value of "selected_value" as none
The Html template
{% extends "admin/base_site.html" %}
{% load i18n admin_urls static admin_modify %}
{% block extrahead %}
{{ media }}
{% endblock %}
{% block content %}
<form class="change_superprofile_parent_form" met`your text`hod="POST" class="change_superprofile_parent_form">{% csrf_token %}
{% for superprofile in superprofiles %}
<input type="checkbox" name="superprofile_selected" {{ superprofile.checked }} value="{{ superprofile }}"> {{ superprofile }}<br>
{% endfor %}
<input type="submit" value="Submit">
</form>
{% endblock %}
Django admin.py
def change_superprofile_parent(self, request, queryset):
"""
Action to change the superprofile of the selected
"""
queryset = queryset.values_list("id", flat=True)
if request.method == 'POST':
selected_value = request.POST.getlist('superprofile_selected')
eligible_superprofiles = SuperProfile.objects.filter(status='Active')
return render(
request, 'admin/auth/user/change_superprofile_parent.html', context={
'superprofiles': eligible_superprofiles,
}
)
I have created a custom html template with basic checkboxes to select a value and return the value to the Django admin page.
I have done a 100 times before, but now the value of the selected superprofile does not get captured by the variable "selected_value" in the admin.py
The if statement "if request.method == 'POST':" is getting triggered but i keep getting the value of "selected_value" as none
Driving me crazy, I cannot find anything wrong in the code
The Html template
{% extends "admin/base_site.html" %}
{% load i18n admin_urls static admin_modify %}
{% block extrahead %}
{{ media }}
{% endblock %}
{% block content %}
<form class="change_superprofile_parent_form" method="POST" class="change_superprofile_parent_form">{% csrf_token %}
{% for superprofile in superprofiles %}
<input type="checkbox" name="superprofile_selected" {{ superprofile.checked }} value="{{ superprofile }}"> {{ superprofile }}<br>
{% endfor %}
<input type="submit" value="Submit">
</form>
{% endblock %}
Django admin.py
def change_superprofile_parent(self, request, queryset):
"""
Action to change the superprofile of the selected
"""
queryset = queryset.values_list("id", flat=True)
if request.method == 'POST':
selected_value = request.POST.getlist('superprofile_selected')
eligible_superprofiles = SuperProfile.objects.filter(status='Active')
return render(
request, 'admin/auth/user/change_superprofile_parent.html', context={
'superprofiles': eligible_superprofiles,
}
)
I am trying to display 2 forms in my contact.html page in a Django project. Each form needs to display a success message when being successfully submitted by users. The problem is that both forms in the page show the same success message when either of them being submitted.
How can I tie the success message to the submitted form on my HTML page?
forms.py
from dataclasses import field, fields
from logging import PlaceHolder
from socket import fromshare
from django import forms
from .models import ServiceRequest, Contact, Newsletter
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = ['name','email','phone','message']
class NewsletterForm(forms.ModelForm):
class Meta:
model = Newsletter
fields = ['name','email']
views.py
from http.client import HTTPResponse
from multiprocessing import context
from django.shortcuts import render
from django.views.generic import TemplateView
from .forms import ContactForm, NewsletterForm, ServiceRequest, ServiceRequestForm
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.urls import reverse
def Contact(request):
contact_form = ContactForm(request.POST or None)
newsletter_form = NewsletterForm(request.POST or None)
if request.method == 'POST' and contact_form.is_valid():
contact_form.save()
messages.success(request, "Thanks for contacting us!")
return HttpResponseRedirect(request.path_info)
elif request.method == 'POST' and newsletter_form.is_valid():
newsletter_form.save()
messages.success(request, "Thanks for joining our newsletter!")
return HttpResponseRedirect(request.path_info)
context = {
"contact_form":contact_form,
"newsletter_form":newsletter_form,
}
return render(request, "main/contact.html", context)
contact.html
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% load static %}
{% block content %}
<div>
<!-- Message from backend -->
{% for message in messages %}
{% if message.tags == 'success' %}
<div>{{message}}
</div>
{% endif %}
{% endfor %}
<form method="POST">
{% csrf_token %}
<div class="row">
{{ contact_form.name|as_crispy_field }}
{{ contact_form.email|as_crispy_field }}
{{ contact_form.phone|as_crispy_field }}
{{ contact_form.message|as_crispy_field }}
</div>
</div>
<button type="submit">Submit</button>
</form>
</div>
<div>
<!-- Message from backend -->
{% for message in messages %}
{% if message.tags == 'success' %}
<div>{{message}}
</div>
{% endif %}
{% endfor %}
<form method="POST">
{% csrf_token %}
<div class="row">
{{ newsletter_form.name|as_crispy_field }}
{{ newsletter_form.email|as_crispy_field }}
</div>
<button type="submit">Submit</button>
</form>
</div>
{% endblock %}
After submitting one form on this page, both forms show the success message:
You can use extra_tags of messages framework Django docs:
So in view:
messages.success(request, "Thanks for contacting us!", extra_tags='form1')
And in template:
{% for message in messages %}
{% if message.tags == 'success' and message.extra_tags == 'form1' %}
<div>{{message}}
</div>
{% endif %}
{% endfor %}
I am running a db query with sqlalchemy and then pushing this output into an HTML page with flask and python. However, the output is formatted as a list, and I am trying to remove the quotes around it and format it nicer.
# views.py
#buyers_blueprint.route('/welcome')
#login_required
def welcome_user():
user = current_user
events = db.session.query(Events.eventname)
return render_template('welcome.html', user=user, events=events)
The welcome.html page is simple and looks like this
welcome.html
{% extends "base.html" %}
{% block content %}
<div class="jumbotron">
<h1>Events Dashboard</h1>
<p>{{user}}! You are logged in.<br>
Here is a list of your events</p><br>
<p>
{% for event in events %}
<li>{{event}}</li>
{% endfor %}
</p>
</div>
{% endblock %}
The output looks like this.
('Event 1',)
('Event 2',)
How do I remove the quotes, and comma to format it so it looks nicer? Thank you so much.
So, thanks to help from others, I came up with an answer. In the HTML, I just needed to ask for the first in tuple.
welcome.html
{% extends "base.html" %}
{% block content %}
<div class="jumbotron">
<h1>Events Dashboard</h1>
<p>{{user}}! You are logged in.<br>
Here is a list of your events</p><br>
<p>
{% for event in events %}
<li>{{event[0]}}</li>
{% endfor %}
</p>
</div>
{% endblock %}
I made a small blog site and is not showing all the items from the database. If i try to see the posts from my phone i see only 3 posts, when in my DB there are 9. When i click on one post i got a Not Found error saying that the requested URL posts/legea etc was not found on server.
LE: My server is inside a VM. Is this maybe an issue?
This is the link that should have all of the posts: http://cohen.ro/posts/
PS I dont have a migrations folder. I just created now and put an init.py file in it. Bu still after running migrate didn't see the migrations and the result is the same.
However, if i enter in admin trhourgh site/admin i can see all of the posts in DB and when i go back to the site all of the items are out there and i can read the posts.
Can someone, please help me in order to fix this?! thank you!
My post List:
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block head_title %} Blog | {% endblock %}
{% block content %}
<div class="container-fluid" style="width:91%;color: currentColor;!important;">
<div class="row" id="list_posts" style="background-color: white;padding-top: 40px;">
<br/>
<br/>
<br>
{% for obj in object_list %}
<div class="col-sm-4">
<div class="thumbnail">
{% if obj.image %}
<img src="{{ obj.image.url }}"/>
{% endif %}
<div class="caption" style="color:currentColor">
{% if obj.draft %} <h3>Staff Only Draft</h3> {% endif %}{% if obj.publish > today %}<h3>Staff Only: Future Post{%endif%}</h3>
<h2><a href='{{ obj.get_absolute_url }}' >{{obj.title }}</a> </h2>
<h5>{{obj.location }} </h5>
{% if obj.user.get_full_name %}<p>Author: {{ obj.user.get_full_name }}</p>{% endif %}
<p> {{ obj.content |linebreaks |truncatechars:150}}</p>
{# <p>View</p>#}
</div>
</div>
</div>
{# {% cycle "" "" "<div class='col-sm-12'><hr/></div></div><div class='row'style='background-color:white;color:currentColor'>" %}#}
{% cycle "" "" "<div class='col-sm-12'><hr/><br/></div><div class='row'style='background-color:white;color:currentColor'></div>" %}
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if object_list.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ object_list.number }} of {{ object_list.paginator.num_pages }}.
</span>
{% if object_list.has_next %}
next
last »
{% endif %}
</span>
</div>
</div>
</div>
Post Form:
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block head_title %} Blog | {% endblock %}
{% block content %}
<div class="container-fluid" id="post_form_id" style="background-color: teal">
<div class="col-sm-6 offset-sm-3">
<h1> Form </h1>
<form method='POST' action='' enctype="multipart/form-data"> {% csrf_token %}
{{ form |crispy }}
<input type="submit" class="btn btn-default" role="button" value="Create Post">
</form>
</div>
</div>
{% include 'navbar_bottom.html' %}
{% endblock %}
My Post detail:
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% load i18n %}
{% block head_title %} Blog | {% endblock %}
{% block content %}
<div class="container-fluid" id="detail_posts" style="background-color: white">
<div class="col-xs-12 offset-xs-0 col-sm-6 offset-sm-3">
{% if instance.image %}
<img src="{{ instance.image.url }}" class="img-responsive" />
{% endif %}
<h1> {{ title }} <small> {% if instance.draft %} <span style="color:red">{% trans "Draft" %}</span> {% endif %}</small></h1>
{% if instance.user.get_full_name %}
<p> {% trans "Autor:" %} {{ instance.user.get_full_name }}</p>
{% endif %}
{{ instance.location |linebreaks }} <br/>
{{ instance.content |linebreaks }} <br/>
Facebook
Twitter
<a href="https://www.linkedin.com/shareArticle?mini=true&url={{ request.build_absolute_uri }}/&title={{ instance.title }}&source={{ request.build_absolute_uri }}">
Linkedin </a>
Reddit
<a href='https://plus.google.com/share?url={{ request.build_absolute_uri }}'>GooglePlus</a>
</div>
</div>
{% include 'navbar_bottom.html' %}
{% endblock content%}
My views:
from contact.forms import ContactForm
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from contact.forms import ContactForm
from django.utils.translation import ugettext_lazy as _
import requests
from django.conf import settings
from django.contrib import messages
def index(request):
return render(request, 'home.html')
def board(request):
return render(request, 'board.html')
def persoanefizice(request):
return render(request, 'persoanefizice.html')
def consultanta(request):
return render(request, 'consultanta.html')
def cyberintelligence(request):
return render(request, 'cyberintelligence.html')
#
# def pay(request):
# return render(request, 'pay.html')
def blog(request):
return render(request, 'blog.html')
def contact(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
contact_name = form.cleaned_data['numele_dumneavoastra']
contact_phone = form.cleaned_data['numarul_de_telefon']
# contact_period = form.cleaned_data['perioada_cand_va_putem_contacta']
subject = contact_name + " | " + contact_phone
content = form.cleaned_data['mesajul_dumneavoastra']
contact_email = form.cleaned_data['emailul_dumneavoastra']
''' Begin reCAPTCHA validation '''
recaptcha_response = request.POST.get('g-recaptcha-response')
data = {
'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}
r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data)
result = r.json()
''' End reCAPTCHA validation '''
if result['success']:
try:
send_mail(subject,content,contact_email, ['greatjobdone770#gmail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
else:
form = ContactForm()
return render(request, "contact.html", {'form': form})
def success(request):
return HttpResponse('Succes! Multumim pt mesajul trimis.')