If else in django template - python-3.x

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

Related

Flask RadioField is not working in form POST

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 %}

How to resolve NoReverseMatch Exception for 'app_list' with upload files in changelist view page of model admin using django 3?

Code snippets that I was able to add so far:
Model class:
class MboxForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MboxForm, self).__init__(*args, **kwargs)
csv_file = forms.FileField(required=True,
label="Select CSV file")
class Meta:
model = Mbox
fields = ['some_field',
]
widgets = {
'csv_file': forms.FileInput(),
}
In admin.py:
class MboxAdmin(admin.ModelAdmin):
actions = [import_from_csv,
export_to_csv]
def get_form(self, request, obj=None, **kwargs):
kwargs['form'] = MboxForm
return super().get_form(request, obj, **kwargs)
def get_urls(self):
urls = super().get_urls()
my_urls = [
path("upload_csv",
self.upload_csv, name='upload_csv')
]
return my_urls + urls
urls = property(get_urls)
def upload_csv(self, request):
if request.method == 'POST':
form = MboxForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('admin/change_list.html')
else :
return render(request, 'admin/change_list.html',
{'form': form,
'opts': Mbox._meta})
else:
return render(
request,
'admin/change_list.html',
context
)
def changelist_view(self, request, extra_context=None):
extra_context = {}
extra_context['submit_csv_form'] = MboxForm
if 'action' in request.POST and request.POST['action'] == 'import_from_csv':
if not request.POST.getlist(admin.ACTION_CHECKBOX_NAME):
post = request.POST.copy()
for u in Mbox.objects.all():
post.update({admin.ACTION_CHECKBOX_NAME: str(u.id)})
request._set_post(post)
return super().changelist_view(request, extra_context=extra_context)
This button displays in place of the add button in the listing page with the template with the file browser to upload any file.
{% extends "admin/change_list.html" %}
{% load i18n admin_urls static admin_list %}
{% block object-tools %}
{% if has_add_permission %}
{% block object-tools-items %}
<form id="upload-csv-form" method="POST"
action="{% url 'admin:upload_csv' %}"
method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
{% comment %}
<p>{{ submit_csv_form.as_p }}</p>
{% endcomment %}
<p>{{ submit_csv_form.csv_file.errors }}</p>
<p><input type="file" value="CSV file" />
<p><input type="submit" value="Upload" />
<!-- input type="reset" value="Reset"> -->
</form>
{% endblock %}
</ul>
</div>
{% endif %}
{% endblock %}
The error That I get on clicking the upload button:
NoReverseMatch
Exception Value:
Reverse for 'app_list' with keyword arguments '{'app_label': ''}' not
found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|mailmanager)/$'
mailmanager is the app for which the model: Mbox exists. Besides where do I place this change_view.html template in the template structure for only this model. I tried placing the template under myproject/templates/admin/templates/mailmanager/mbox, but it is not found. Also I don't wish to replace the 'Add model' button but have this placed next to it in the default model change list template.
I have followed the stack link so far but not got it working as yet. :Upload CSV file in django admin list view, replacing add object button Please guide .

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:

Resources