I have some code, in Python and sqlite, which when executed and printed, returns the correct data. But when I try pass it to HTML, it is retrieving data from the wrong table and displaying it to the HTML.
For example, I execute the following python code:
comments = c.execute('''SELECT * FROM comments''')
conn.commit
for each in comments:
print(each)
newsubs = c.execute('''SELECT * FROM submissions WHERE Signiture = signiture AND Client_ID = client_ID ORDER BY date DESC''')
conn.commit()
print("hello")
var = "hello,!"
return render_template('profile.html', comments = comments, newsubs = newsubs)
Then, I have the following HTML code calling in comments and newsubs to display the data:
{% for y in newsubs %}
<br>
<div id="subcss">
<legend><strong> {{ y[2] }} </strong> {{ y[4] }} <br><br></legend>
{{ y[3] }} <br><br>
<p id = "sig"><strong>Signiture:</strong> {{ y[5] }}</p>
{{ y[1] }} <br><br>
<div id="subcss">
<form action="/comments" method="post">
<textarea name="comment" rows="7" cols="76">Write a comment...</textarea><br>
<input type="submit" value="Submit"><br><br><br>
<button onclick="myFunction()">View Comments</button>
<div id="comdiv">
{% for z in comments %}
<strong>Date:</strong> {{ z[0] }} <br>
<strong>Comment:</strong> {{ z[1] }} <br><br>
{{ z[2] }}
<br>{ z[3] }} {{ z[4] }}
<br>
{% endfor %}
</form><br>
</div>
{% endfor %}
</div>
</div>
The problem is is that the output to the webpage from this code:
{% for z in comments %}
<strong>Date:</strong> {{ z[0] }} <br>
<strong>Comment:</strong> {{ z[1] }} <br><br>
{{ z[2] }}
<br>{ z[3] }} {{ z[4] }}
<br>
{% endfor %}
Is displaying data from the submissions table, not the comments table.
Any help or anything is greatly appreciated.
Related
I am developing a domestic worker booking app in django
When I try to pass the formset, I am not geting the label of that field. I am only getting the field in html.
{% for formset in formsets %}
<form method="post">
{% for form in formset %}
{% for field in form %}
<div>
<label for="{{ field.auto_id }}">{{ field.label }}</label>
{{ field }}
{% for error in field.errors %}
<p>{{ error }}</p>
{% endfor %}
</div>
{% endfor %}
{% endfor %}
<input type="submit" value="Submit">
</form>
{% endfor %}
This the html code
def staffApply(request,pk):
if request.method == 'POST':
selected_domestic_works = request.POST.getlist('domestic_works')
formsets = []
if 'cook' in selected_domestic_works:
formsets.append(CookingForm(request.POST,prefix='cook'))
if 'driver' in selected_domestic_works:
formsets.append(DriverForm(request.POST,prefix='driver'))
print(formsets)
return render(request, 'staffApply2.html', {'formsets': formsets})
return render(request,'staffapply.html',{'uid':pk})
enter code here
This is my views.py
class CookingForm(ModelForm):
food_cooked=(('veg','veg'),
('non-veg','non-veg'),
('both','both')
)
class Meta:
model = Cook
fields = '__all__'
exclude=['user']
widgets={
'food_cooked':forms.widgets.RadioSelect(),
'type_of_cuisine':forms.widgets.CheckboxSelectMultiple()
}
This is my forms.py
I am getting the fields to type. But I am not getting hte label for those fields. Please help me fix this.
class Cook(models.Model):
food_cooked=(('veg','veg'),
('non-veg','non-veg'),
('both','both')
)
type_of_cuisine=(('NorthIndian','NorthIndian'),
('SouthIndian','SouthIndian'),
('Chettinadu','Chettinadu'),
('Chinese','Chinese'),
)
user=models.ForeignKey(User,on_delete=models.CASCADE)
food_cooked=models.CharField(choices=food_cooked,max_length=30)
type_of_cuisine=models.CharField(choices=type_of_cuisine,max_length=30)
experience=models.IntegerField()
wages_expected=models.IntegerField()
dishwashing_flag=models.BooleanField()
wages_for_dishwashing=models.IntegerField(null=True)
desc=models.TextField(max_length=200)
This is my models.py
You have one extra loop, with the wrong naming so you cannot access {{ field.label }} on your loops its like you are trying something like {{ form.field.attribute.label }}, the correct way would be the following:
{% for form in formsets %}
<form method="post">
{% for field in form %}
<div>
<label for="{{ field.auto_id }}">{{ field.label }}</label>
{{ field }}
{% for error in field.errors %}
<p>{{ error }}</p>
{% endfor %}
</div>
{% endfor %}
<input type="submit" value="Submit">
</form>
{% endfor %}
That being said, you can also use Django form rendering options, instead of doing it manually.
{% for form in formsets %}
<form method="post">
{{form.as_p}}
<input type="submit" value="Submit">
</form>
{% endfor %}
I don't understand where to add the class name so I can change the background color of the checkbox.
form.py
DOMAINS = ['Bakeries', 'Bars and Pubs', 'Butcher Shops', 'Electronics', 'Fashion', 'Fish Shops',
'Flowers', 'Furniture', 'Gelaterias and Sweets', 'Pets', 'Other', 'Restaurants and Cafés', 'Sport',
'Supermarkets', 'Vegetables and Fruits']
class MultiCheckboxField(SelectMultipleField):
widget = widgets.ListWidget(prefix_label=False)
option_widget = widgets.CheckboxInput()
class BuyerForm(FlaskForm):
address = StringField(label='Address', validators=[InputRequired()])
domains_fields = [(x, x) for x in DOMAINS]
domains = MultiCheckboxField(label='Domains', choices=domains_fields)
radius = DecimalRangeField(label='Radius (KM)', default=5, validators=[InputRequired()])
submit = SubmitField(label='Search')
buyer_form.html
<div class="form-group">
{{ form.domains.label(class="form-control-label") }}
{% if form.domains.errors %}
{{ form.domains(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.domains.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.domains(class="form-control form-control-lg") }}
{% endif %}
</div>
I'm looking where to add:
CSS file
.container input:checked ~ .checkmark {
background-color: #e86875;
}
(I took it from w3school)
First of all, the part of the CSS you've taken from the example code will not work on its own. When you look at the complete example, it actually removes the original checkboxes and replaces them with new ones done entirely in CSS so they can look and behave a certain way. This means you will need to include the entire CSS code to make the checkboxes look like in the example and change color when selected.
Once you have that done, you can put this in your buyer_form.html code:
<div class="form-group">
{{ form.domains.label(class="form-control-label") }}
{% if form.domains.errors %}
{{ form.domains(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.domains.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{% for domain in form.domains %}
<label class="container">{{ domain.label() }}
{{ domain() }}
<span class="checkmark"></span>
</label>
{% endfor %}
{% endif %}
</div>
I googled for this, and the radio button should have the same 'name' attribute to allow only a single value to be chosen.
So I did, and It's still allowing me to choose multiple values...
I used HTML and Jinja2 templates for this, so the code might be looking a bit strange..
{% if search_keyword == None: %}
<p>Please enter your search keyword</p>
{% else: %}
{% for i in range(0, 10) %}
<form method="POST" action="./search">
<h2>
<input type="radio" name="selected_food" id="{{ i }}" value="{{ search_data["hits"][i]['recipe']['label'] }}">
{{ search_data["hits"][i]['recipe']['label'] }}
</h2>
<h4>
Calroies: {{ '%0.2f'| format(search_data["hits"][i]['recipe']['calories']) }} kcal
</h4>
{% for j in range(0, 40) %}
<p>{{ search_data['hits'][i]['recipe']['ingredientLines'][j] }}</p>
{% endfor %}
</form>
{% endfor %}
{% endif %}
In the above code the loop is creating multiple forms. This is the reason why you're able to select multiple values in radio.
If you can modify your code like this, it will work
{% if search_keyword == None: %}
<p>Please enter your search keyword</p>
{% else: %}
<form method="POST" action="./search">
{% for i in range(0, 10) %}
<div>
<h2>
<input type="radio" name="selected_food" id="{{ i }}" value="{{ search_data["hits"][i]['recipe']['label'] }}">
{{ search_data["hits"][i]['recipe']['label'] }}
</h2>
<h4>
Calroies: {{ '%0.2f'| format(search_data["hits"][i]['recipe']['calories']) }} kcal
</h4>
{% for j in range(0, 40) %}
<p>{{ search_data['hits'][i]['recipe']['ingredientLines'][j] }}</p>
{% endfor %}
</div>
{% endfor %}
</form>
{% endif %}
Hello Everyone,
This is my first time here. I have been having issues regarding the flask_upload to upload the files. I am not sure where I am going wrong with the flask_upload. Hence every time I have been trying to upload the file it is throwing the error in the title
(** storage must be a werkzeug.FileStorage)
enter image description here**)
I am attaching the pictures of my application factory, along with the config file and the html file.Any help will be greatly appreciated.Since I am not sure where I am going wrong
{% block content %}
<h1>upload files</h1>
<form action="{{ url_for('rep.upload') }}" method="post",enctype="multipart/form-data">
{{ form.hidden_tag() }}
<p>
{{ form.report_title.label }}<br>
{{ form.report_title(size=32) }}<br>
{% for error in form.report_title.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>
{{ form.report_description.label }}<br>
{{ form.report_description(size=64) }}<br>
{% for error in form.report_description.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>
{{ form.report_file.name }}<br>
{{ form.report_file}}<br>
{% for error in form.report_file.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>{{ form.submit() }}</p>
</form>
{% endblock %}
enter code here
(Report Blueprint)
#rep.route("/add",methods=['GET','POST'])
#login_required
#roles_requried("patient")
def upload():
form = AddReportForm()
if form.validate_on_submit():
print(request.files.get('report_file'))
filename = images.save(request.files.get('report_file'),name="Hello",folder="static/img",)
url = images.url(filename)
data = {"report_title":form.report_title.data,"report_description":form.report_description.data,
"report_filename":filename,"report_url":url}
print(data)
new_report = Report(**data)
new_report.save()
flash( 'New report, {}, added!'.format(new_report.report_title), 'success')
return redirect(url_for('user.profile'))
return render_template(template_name_or_list='user/add_report.html',form=form)
enter code here
[config.py]
UPLOADS_DEFAULT_DEST = '/static/img/'
UPLOADS_DEFAULT_URL = 'http://localhost:5000/img/'
UPLOADED_IMAGES_DEST = '/static/img/'
UPLOADED_IMAGES_URL = 'http://localhost:5000/img/'
enter code here
(extensions)
images = UploadSet('images',IMAGES)
enter code here
(Application Factory)
app = Flask(__name__, instance_relative_config=False)
app.config.from_object(config_settings)
handler = RotatingFileHandler(app.config.get('LOGGING_LOCATION'), maxBytes=10240,backupCount=10 )
handler.setLevel(app.config.get('LOGGING_LEVEL'))
formatter = handler.setFormatter(app.config.get('LOGGING_FORMAT'))
handler.setFormatter(formatter)
patch_request_class(app, 32 * 1024 * 1024 )
app.register_blueprint(user)
app.register_blueprint(doc)
app.register_blueprint(adm)
app.register_blueprint(rep)
configure_uploads(app, images)
app.logger.addHandler(handler)
error(app)
extensions(app)
I was learning to create a wtf Flask web form which was:
class Update(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
email = StringField('Email', validators=[DataRequired(), Email()])
pic = FileField('Update Profile Pic', validators=[FileAllowed(['jpg','png'])])
submit = SubmitField('Update')
What I wanted to do was that the form would load on the same page on a button click without making a seperate html page for the form. How can it be done either by using Flask or HTML? If any changes to route have to be made, please mention that as well.
HTML Code:
<div class="content-section">
<form method="POST" action="" enctype="multipart/form-data">
{{ form.hidden_tag() }}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Account Info</legend>
<div class="form-group">
{{ form.username.label(class="form-control-label") }}
{% if form.username.errors %}
{{ form.username(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.username.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.username(class="form-control form-control-lg") }}
{% endif %}
</div>
<div class="form-group">
{{ form.email.label(class="form-control-label") }}
{% if form.email.errors %}
{{ form.email(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.email.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.email(class="form-control form-control-lg") }}
{% endif %}
</div>
<div class="form-group">
{{ form.pic.label() }}
{{ form.pic(class="form-control-file") }}
{% if form.pic.errors %}
{% for error in form.picture.errors %}
<span class="text-danger">{{error}}</span><br>
{% endfor %}
{% endif %}
</div>
</fieldset>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</form>
You can load your form normally, and set it's visibility to hidden. If someone clicks on the button, just change visibility of a form to visible.
Example below:
function toggle_display(){
el = document.querySelector('.content_section');
if(el.style.visibility == 'hidden'){
el.style.visibility = 'visible'
}else{
el.style.visibility = 'hidden'
}
}
<button onclick="toggle_display()">Toggle display</button>
<div class="content_section">See me no more</div>
EDIT:
One more thing to mention, visibility property when set to hidden takes up space, even if it's hidden. To completly remove space that form will take and hide form, set display property to none. To show it again, set display to block.