Flask RadioField is not working in form POST - python-3.x

Can someone please help resolving RadioField Post issue in below code snippet
As below code is not moving form.validate_on_submit()
**forms.py**
class validatingSPLForm(FlaskForm):
srcfile = FileField('Select Source ZIP', validators=[FileRequired(), FileAllowed(['zip'], 'Only ZIP files are allowed')])
submit = SubmitField("Validate")
proceed = IntegerField()
SPLFiles = RadioField('SPL', choices=[])
archiveresult = []
**routes.py**
app.route('/validatingSPLForm', methods=['GET', 'POST'])
def validatingSPLForm():
form = validatingSPLForm()
if request.method == 'POST':
if form.validate_on_submit():
form.SPLFiles.choices = [(elem.name, elem.des) for elem in form.archiveresult]
**validatingSPLForm.html**
{% extends "layout.html" %}
{% block content %}
<div class="content-section">
<form method="POST" action="" enctype="multipart/form-data">
</form>
</div>
{% endblock content %}
{% block content1 %}
<div class="content-section">
<h6><b class="text-success">"{{ form.srcfile.data.filename }}"</b> is valid, select one of the below SPL for further validation </h6>
{{ form.SPLFiles() }}
</div>
{% endblock content1 %}

Related

Show image name inside the image field in Django forms

I have this edit or update form in which I want to display only the image name in the form for a better user experience so that the user could know which image he has uploaded while creating the data.
I am storing the image name in the model as well,but i want to display the image name inside the image field.
forms.py
class MenuCategoryForm(forms.ModelForm):
image = forms.ImageField(allow_empty_file=True, required=False)
class Meta:
model = MenuCategory
fields = ['name', 'description', 'menu_options']
view
def menu_category_update(request, id):
item = MenuCategory.objects.get(id=id)
if request.method == 'POST':
form = MenuCategoryForm(request.POST, request.FILES, instance=item)
if form.is_valid():
if request.FILES['image']:
image = request.FILES['image']
image_url = upload_image(image, 'menu_category', image.name)
obj = form.save(commit=False)
obj.image_url = image_url
form.save()
else:
form.save()
return redirect('menu-category')
else:
form = MenuCategoryForm(instance=item)
context = {
'form': form,
'item': item
}
return render(request, 'menu/menu_category_update.html', context)
Template
{% extends 'partials/base.html' %} {% load crispy_forms_filters %} {% load
crispy_forms_tags %}
<!-- {% block title %}Menu category {% endblock %} -->
{% block content %}
<div class="container edit-form-flex">
<div class="row Edit-form-box">
<div class="form-inner-box bg-white">
<div class="heading-editing">
<h3>Edit menu category</h3>
</div>
<form method="POST" class="add-new-form edit-form" enctype="multipart/form-data">
{% csrf_token %} {{ form|crispy }}
<div class="update-buttons-container">
<button class="btn btn-info1" type="submit" value="Update">
Update
</button>
<a class="btn btn-secondary" href="{% url 'menu-category' %}"
>Cancel</a
>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
Well in other to get the name of the image in your form you will be better off in using a form initial like so:
def menu_category_update(request,id):
item = MenuCategory.objects.get(id=id)
if request.method == 'POST':
form = MenuCategoryForm(request.POST, request.FILES, instance=item)
if form.is_valid:
obj = form.save(commit=False)
# obj.username = request.user
form.save()
return redirect('menu-category')
else:
form = MenuCategoryForm(
initial={'image':item.image,
'name':item.name,
'description':iteem.description,
})# this are the fields that we want to show in the form
context = {
'form': form,
'item': item
}
return render(request, 'menu/menu_category_update.html', context)
In your form html you will apply the form initial to the field that you want to show in your form, by doing something like this: form.initial.name As i have illustrated below :
{% extends 'partials/base.html' %} {% load crispy_forms_filters %} {% load
crispy_forms_tags %}
<!-- {% block title %}Menu category {% endblock %} -->
{% block content %}
<div class="container edit-form-flex">
<div class="row Edit-form-box">
<div class="form-inner-box bg-white">
<div class="heading-editing">
<h3>Edit menu category</h3>
</div>
<form method="POST" class="add-new-form edit-form" enctype="multipart/form-data">
{% csrf_token %}
<label> Image name </label>
{{form.initial.name}}
<label> Description </label>
{{ form.initial.description }}
<label> Image </label>
{{ form.initial.image }}
<div class="update-buttons-container">
<button class="btn btn-info1" type="submit" value="Update">
Update
</button>
<a class="btn btn-secondary" href="{% url 'menu-category' %}"
>Cancel</a
>
</div>
</form>
</div>
</div>
</div>
{% endblock %}

error checking and flashing error messages with FlaskForm

I have a form that is setup as below and ultimately, the error I get in debug mode is sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed. I understand why, but I would like this error to get presented to the user so they know the issue.
class RegistrationForm(FlaskForm):
company_url = StringField('Company Website', validators=[DataRequired(), URL(message='Must be a valid URL')])
password = PasswordField(
'Password', validators=[DataRequired(), EqualTo('pass_confirm',
message='Passwords must match')]
)
pass_confirm = PasswordField('Confirm Password', validators=[DataRequired()])
submit = SubmitField('Register!')
However, when an incorrect URL structure is entered into the form and submitted, I cannot get it to flash an error message in the html page for the user. The html page is below. I will place the base.html below as well.
{% extends "base.html" %}
{% block content %}
<form method="POST">
{{form.hidden_tag()}}
{{form.company_url.label}}{{form.company_url()}}<br>
{{form.password.label}}{{form.password()}}<br>
{{form.pass_confirm.label}}{{form.pass_confirm()}}<br>
{{form.submit()}}
</form>
{% endblock %}
<!DOCTYPE html>
<html>
<head>
...some code here
</head>
<body>
<!-- Just an image -->
<nav class="navbar navbar-dark bg-dark">
<span class="align-bottom text-light">Creating connections, saving time</span>
</nav>
{% with messages = get_flashed_messages() %} {% if messages %} {% for
message in messages %}
<div class="alert alert-warning alert-dismissible" role="alert">
<button
type="button"
class="close"
data-dismiss="alert"
aria-label="Close"
>
<span aria-hidden="true">×</span>
</button>
{{message}}
</div>
{% endfor %} {% endif %} {% endwith %} {% block content %} {% endblock %}
</body>
</html>
The views.py is:
#app.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
user = Buyers(
company_url=form.company_url.data,
password=form.password.data
)
db.session.add(user)
db.session.commit()
flash("Thank you for registering.")
return redirect(url_for('login'))
return render_template('register.html', form=form)
How do I error handle in forms to make sure the user is aware that they have entered a URL with an incorrect structure? I am in debug mode and right now, the register.html page just basically reloads without any message as to why. Thank you!
views.py :
import validators
#app.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
isUrlValid=validators.url(form.company_url.data)
if isUrlValid==True:
user = Buyers(
company_url=form.company_url.data,
password=form.password.data
)
db.session.add(user)
db.session.commit()
flash("Thank you for registering.")
return redirect(url_for('login'))
else:
flash("URL is not valid. Please enter a valid URL")
return redirect(url_for('register'))
return render_template('register.html', form=form)

I want to represent DetailView and ListView in one Template. What can I do?

I want to express the detailview as the picture. I want to code the box part in the template of the picture.
enter image description here
It is as follows now.
views.py
#login_required
def product_detail(request, id, product_slug=None):
product = get_object_or_404(Product, id=id, slug=product_slug)
return render(request, 'shop/detail.html', {'product': product})
I think it should be modified to class. I would like to explain it by representing DetailView and ListView together in detail_template. I modified only views.py as shown below.
class ProductDetailView(DetailView, ListView):
model = Product
template_name = 'shop/detail.html'
context_object_name = 'latest_question_list'
#login_required
def get_queryset(self, id, product_slug=None):
product = get_object_or_404(Product, id=id, slug=product_slug)
return render(self, 'shop/detail.html', {'product': product})
This error occurs. AttributeError: 'ProductDetailView' object has no attribute 'user'
urls.py
urlpatterns = [
.........
path('<int:id>/<product_slug>/', product_detail, name='product_detail'),
.........
]
detail.html
{% extends 'base.html' %}
{% block title %}Product Detail{% endblock %}
{% block content %}
<div class="col">
<div class="alert alert-info" role="alert">Detail</div>
<div class="container">
<div class="row">
<div class="col-4">
<img src="{{product.image.url}}" width="100%">
</div>
<div class="col">
<h1 class="display-6">{{product.cname}}</h1>
<p class="card-text">{{product.pname}}</p>
<h5><span class="badge badge-secondary">Description</span>{{product.description|linebreaks }}</h5>
{% if product.author.username == user.username %}
Update
Delete
{% endif %}
{% if product.author.username != user.username %}
Inquiry
{% endif %}
Continue shopping
</div>
</div>
</div>
<p></p>
<div class="col">
<div class="alert alert-info" role="alert">Products added by registrants</div>
<div class="container">
{% for product in products %}
<div class="row">
{% if product.user.username == user.username %}
<div class="col-4">
<img src="{{product.image.url}}" width="auto" height="250">
</div>
<div class="col">
<h1 class="display-6">{{product.pname}}</h1>
<h5><span class="badge badge-secondary">Description</span>{{product.description|linebreaks}}</h5>
</div>
{% endif %}
</div>
{% endfor %}
</div>
{% endblock %}
Please help me how to fix it. I would also appreciate it if you would recommend any textbooks that I can refer to.
I have a similar situation. I wanted to display create form, detail and list on the same page:
urls:
example_urlpatterns = [
path('', views.ExampleCreateView.as_view(), name='_list'),
path('new/', views.ExampleCreateView.as_view(), name='_create'),
path('<int:pk>/', views.ExampleCreateView.as_view(), name='_detail'),
path('<int:pk>/del', views.ExampleDeleteView.as_view(), name='_del'),
]
urlpatterns = [
# ...
path('example/', include(example_urlpatterns)),
# ...
]
As you can see, I have two views, ExampleCreateView (also providing detail and list) and ExampleDeleteView for deleting. ExampleCreateView is primarily a create view:
class ExampleCreateView(CreateView):
template_name = 'example.html'
form_class = ExampleCreateForm
model = Example
def form_valid(self, form):
pass # Stuff to do with a valid form
# add user info from request to the form
def get_form_kwargs(self, *args, **kwargs):
kwargs = super().get_form_kwargs(*args, **kwargs)
kwargs['user'] = self.request.user
return kwargs
# Create appropriate context
def get_context_data(self, **kwargs):
kwargs['object_list'] = Example.objects.order_by('ip') # list
try: # If we have pk, create object with that pk
pk = self.kwargs['pk']
instances = Example.objects.filter(pk=pk)
if instances:
kwargs['object'] = instances[0]
except Exception as e:
pass # No pk, so no detail
return super().get_context_data(**kwargs)
Because I'm inheriting from CreateView, all the form processing is taken care of by default.
Adding the line kwargs['object_list'] =... makes it work as a list view, and the try block after that line makes it work as a detail view.
In the template all relevant parts are displayed:
{% if object %}
{% comment %}
...display the object... (Detail section)
{% endcomment %}
{% endif %}
{% if form %}
{% comment %}
...display the form... (Create section)
{% endcomment %}
{% endif %}
{% if object_list %}
{% comment %}
...display the list... (List section)
{% endcomment %}
{% endif %}
Let me know if this helps
Currently I have applied like this
views.py : modified
#method_decorator(login_required, name="dispatch")
class ProductDetailView(DetailView):
model = Product
template_name = 'shop/detail.html'
def get_context_data(self, **kwargs):
context = super(ProductDetailView, self).get_context_data(**kwargs)
context['product_list'] = Product.objects.all()
return context
index = ProductDetailView.as_view()
detail.html : modified
<div class="col">
<div class="alert alert-info" role="alert">Products added by this registrant</div>
<div class="container">
{% for prdt in product_list %}
{% if product.author.username == prdt.author.username %}
{% if product.pname != prdt.pname %}
{{ prdt }}<br>
{% endif %}
{% endif %}
{% endfor %}
</div>
enter image description here

python3 flask: how to display the json result in html

Now I want to send the json data to html, I just display the dictionary data(json), How to display the value of dictionary in the html.
The python code is:
#app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
img_file = request.files['img_file']
if img_file and allowed_file(img_file.filename):
filename = secure_filename(img_file.filename)
img_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
raw_img_url = './static/asset/uploads/' + filename
result_img_url = './static/asset/output/Line/' + filename
ratio = check_banner(filename)
result_dict = {'result': ratio}
return render_template("upload.html", result_img_url=result_img_url, result=json.dumps(result_dict))
else:
return ''' ok</p> '''
else:
return redirect(url_for('upload'))
The html code:
{% extends "base.html" %}
{% block content %}
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" id="img_file" name="img_file" class="col-sm-4">
<input type="submit" value="check" class="btn">
</form>
<p>
{% if result_img_url %}
<img src="{{ result_img_url }}" width='400' height='350'>
{% endif %}
</p>
<ul>
<li>{{result}}</li>
</ul>
{% endblock %}
But the result html is, but I just want to show the value of result :
If you want to pass only one parameter in result, you may change result_dict = {'result': ratio} to result = ratio.
It will show only the result in the page:

If else in django template

I have a problem with if/else condition into my template.
I have a simple form and confirmation button. User should input text in this form, then should press button and only after that, user will see other part of page.
This is my template code:
{% extends "home/base.html" %}
{% load staticfiles %}
{{% block body %}
<h1 align="center">Analyzed text</h1>
<form class="form" action="analyze" method="post">
<div id="form">
<dd><textarea id="textarea" name="q" rows=10 cols=55 placeholder=" Input your text in japanese here ..."></textarea>
<dd><input class="myButton" type="submit" value="Analyze">
</div>
</form>
<div class=page>
{% if 'q' != None %}
{% include "kanji_analyzer/show_results.html" %}
{% endif %}
</div>
{% endblock %}}
views.py
from django.shortcuts import render_to_response
from kanji_analyzer.logic_part.kanji_analyzer import KanjiesText
def start_kanji(request):
return render_to_response('kanji_analyzer/main.html')
def show_entries():
global analyzed_text
global list_of_percents
global list_of_find_kanjies
return render_to_response('show_entries.html', {'analyzed_text': analyzed_text, 'list_of_percents': list_of_percents,
'list_of_find_kanjies': list_of_find_kanjies,})
def send_text(request):
if 'q' in request.POST:
q = request.POST['q']
a = KanjiesText(request.POST['q'])
a.remove_spaces_from_text()
list_of_percents = a.take_percent_count()
list_of_find_kanjies = a.list_find_kanjies()
for i in range(0,5):
if len(list_of_find_kanjies[i]) == 0:
list_of_find_kanjies[i] = ''
return render_to_response('kanji_analyzer/main.html', {'q': q, 'list_of_percents': list_of_percents,
'list_of_find_kanjies': list_of_find_kanjies,})
else:
q = "your form is empty"
return render_to_response('kanji_analyzer/main.html', {'q': q},)
This block if/else doesn't work. 'q' - value with user's text

Resources