Want to extract the month and year from template
template_1.html
<form method = 'POST'>
<input type ='month' name = 'searchmonth'>
<input type = 'submit' value = 'Search'>
</form>
template_2.html
{% for i in record %}
{% if i.record_patient_number == number %}
{{ month = i.record_date.getMonth() }}
{% if month == searchrecordmonth %}
*something*
{% endif %}
{% endif %}
{% endfor %}
All variable are include in views.py
In this search month is not able to extract and record_date is save in models.py and as a
record_date = models.DateField(blank = True , null = True)
You cannot set values while in django template, your code below is invalid
{{ month = i.record_date.getMonth() }}
to get the month, simply get it from the i.record_date
{% if i.record_date.month == searchrecordmonth %}
Related
Django SessionWizardView: User fills in form 1 and then, some of the values of the fields in form one are needed to calculate a number. This number must then be displayed on form 2. I don't know how I can grab the data of form 1 and use it to make a calculation and then display it on form 2.
models.py
class CapsProd(models.Model):
production = models.OneToOneField(Productions, on_delete=models.CASCADE, primary_key=True)
amount_of_caps = models.IntegerField()
conc_per_cap = models.FloatField()
conc_per_tab = models.FloatField()
amount_of_weighed_tabs = models.IntegerField()
mass_all_tabs = models.FloatField()
required_mass_powder = models.FloatField()
weighed_mass_powder = models.FloatField()
caps_size = models.FloatField(choices=CHOICES,)
forms.py
class CapsProdForm1(forms.ModelForm):
class Meta:
model = CapsProd
fields = [
'production',
'amount_of_caps',
'conc_per_cap',
'conc_per_tab',
]
class CapsProdForm2(forms.ModelForm):
class Meta:
model = CapsProd
fields = [
'amount_of_weighed_tabs',
'mass_all_tabs',
'required_mass_powder',
'weighed_mass_powder',
'caps_size',
]
urls.py
app_name = 'caps_prod'
urlpatterns = [
path('', views.CapsProdWizardView.as_view([CapsProdForm1, CapsProdForm2]), name="add_new"),
]
views.py
class CapsProdWizardView(SessionWizardView):
template_name = "caps_prod/prod_form.html"
html
{% extends "base.html" %}
{% load django_bootstrap5 %}
{% block body_block %}
<h1>
Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}
</h1>
<form class="custom-form" method="post">
{% csrf_token %}
<!-- {% bootstrap_form form %} -->
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{wizard.form.management_form }}
{% for form in wizard.form.forms %}
{% bootstrap_form form %}
{% endfor %}
{% else %}
{% bootstrap_form wizard.form %}
{% endif %}
{% if wizard.steps.prev %}
<button type="submit" class="btn btn-primary" value="{{ wizard.steps.first }}">First step</button>
<button type="submit" class="btn btn-primary" value="{{ wizard.steps.prev }}">Previous step</button>
{% endif %}
<input type="submit" value="Submit">
</form>
{% endblock %}
Thanks!
{%for feed,tim in feeds,time %}
{% set nickname = feed.nick %}
{% set like = feed.like %}
{% set text = feed.text %}
{% set today = tim %}
{% set postid = feed.postid %}
{% set photo = feed.photo %}
{% set profile = feed.profile %}
{%for cmt in cmts %}
{% set nickname = cmt.nick %}
{% set cmt = cmt.cmt %}
{% set cmtid = cmt.cmtid %}
{% if cmtid == postid %}
<p class="description"><span>{{nickname}} </span> {{cmt}}</p>
{% endif %}
{% endfor %}
<div class="comment-wrapper">
<img src="../static/images/smile.PNG" class="icon" alt="">
<input type="text" class="comment-box" id='cmt' placeholder="Add a comment">
<button class="comment-btn" onclick=cmt_write()>post</button>
</div>
</div>
</div>
{% endfor %}
succeeded in executing the for statement with one list in jinja2,
but we have to use two lists.
i try 2 list ( feeds, time ) use in jinja2
how to jinja2 for loop from jinja2
Is there a way to use two lists in jinja2?
If you want to loop over a combined list of two lists (of same length) you have to apply zip function on them. E.g.:
def view_function():
feeds = [...]
time = [...]
feeds_and_time = zip(feeds, time)
# Looks like this: [('feed_1', 'time_1'), ('feed_2', 'time_2')]
Then pass this new feeds_and_time variable to the render function. And in the template, modify the loop:
{% for feed,tim in feeds_and_time %}
have a table with websites and a many to one table with descriptions
trying to get a list, firstly getting the latest descriptions and then displaying them ordered by the content of the descriptions...
have the following in views.py
def category(request, category_name_slug):
"""Category Page"""
context_dict = {}
try:
category = Category.objects.get(slug=category_name_slug)
subcategory = SubCategory.objects.filter(category=category)
websites = Website.objects.filter(sub_categories=subcategory, online=True, banned=False)
sites = websites
descriptions = WebsiteDescription.objects.prefetch_related("about")
descriptions = descriptions.filter(about__in=sites)
descriptions = descriptions.order_by('about', '-updated')
descs = []
last_site = "" # The latest site selected
# Select the first (the latest) from each site group
for desc in descriptions:
if last_site != desc.about.id:
last_site = desc.about.id
desc.url = desc.about.url
desc.hs_id = desc.about.id
desc.banned = desc.about.banned
desc.referral = desc.about.referral
descs.append(desc)
context_dict['descs'] = descs
context_dict['websites'] = websites
context_dict['subcategory'] = subcategory
context_dict['category'] = category
except SubCategory.DoesNotExist:
pass
return render(request, 'category.html', context_dict)
this gives me a list with sites and their latest descriptions, so i have the following in category.html
{% if category %}
<h1>{{ category.name }}</h1>
{% for subcategory in category.subcategory_set.all %}
{{ subcategory.name }} ({{ subcategory.website_set.all|length }})
{% endfor %}
{% if descs %}
{% load endless %}
{% paginate descs %}
{% for desc in descs|dictsortreversed:"description"|dictsortreversed:"officialInfo" %}
<ul id='list' class='linksteps'>
<a href="/{{ desc.about_id }}" rel="nofollow" target="_blank">
<img src="/static/screenshots/{{ desc.about_id }}.png" />
</a>
<li><h3>{{ desc.about_id }}{% if desc.title %} - {{ desc.title }} {% endif %}</h3>
{% if desc.description %}<b>Description: </b>{{ desc.description }}
<br />{% endif %} {% if desc.subject %}<b>Keywords: </b>{{ desc.subject }}
<br />{% endif %} {% if desc.type %}<b>Type: </b>{{ desc.type }}
<br />{% endif %} {% if desc.officialInfo %} {% if desc.language %}<b>Language: </b>{{ desc.language }}
<br />{% endif %} {% if desc.contactInformation %}<b>Contact info: </b>{{ desc.contactInformation }}
<br />{% endif %}
{% else %}
{% endif %}
</li>
</ul>
</div>
{% endfor %}
{% show_pages %}
{% else %}
<strong>No websites currently in category.</strong>
{% endif %}
{% else %}
The specified subcategory {{ category_name }} does not exist!
{% endif %}
Initially i used dictsort
{% for desc in descs|dictsortreversed:"description"|dictsortreversed:"officialInfo"|dictsortreversed:"referral" %}
to give me the list in the desired order, so i was all happy ;)
Then however i decided i needed some pagination because the lists became too long.
django-endless-pagination works fine and does what its supposed too, however it splits up my list before the dictsort kicks in.
is there a way to sort before pagination happens and after i ordered_by at the initial query to have the latest descriptions selected?
much obliged
EDIT:
not getting any answers so my question might not be clear.
as far as i understand i need to sort the values in context_dict at the end in views.py replacing the dictsort as in the template
SOLVED:::
doing this did the trick for me to replace the dictsort.
descs1 = sorted(descs, key=operator.attrgetter('referral', 'officialInfo', 'description'), reverse=True)
context_dict['descs'] = descs1
SOLVED:::
doing this did the trick for me to replace the dictsort.
descs1 = sorted(descs, key=operator.attrgetter('referral', 'officialInfo', 'description'), reverse=True)
context_dict['descs'] = descs1
I have a webapp that allows users to create their own fields to be rendered in a form later on.
I have a model Formfield like so:
class Formfield(db.Model):
id = db.Column(db.Integer, primary_key = True)
form_id = db.Column(db.Integer, db.ForeignKey('formbooking.id'))
label = db.Column(db.String(80))
placeholder_text = db.Column(db.String(80))
help_text = db.Column(db.String(500))
box_checked = db.Column(db.Boolean, nullable = True, default = False)
options = db.Column(db.String) # JSON goes here?
answer = db.Column(db.String)
required = db.Column(db.Boolean, nullable = False, default = False)
order = db.Column(db.Integer)
fieldtype = db.Column(db.Integer)
that I use to represent a field, whatever the kind (checkbox, input, more in the future).
As you can see, every field has a FK to a form_id.
I’m trying to generate a dynamic form for a given form_id.
The catch is that I need to determine the type of field to render for every Formfield.
So I also need to process the fieldtype at some point.
I guess a solution would be to somehow pass the form_id to a function in my Form class.
I have no clue how to do it or where to look for a solution.
Any help would be very appreciated!
I think I managed to create dynamic forms with the idea from here https://groups.google.com/forum/#!topic/wtforms/cJl3aqzZieA
you have to create a dynamic form at view function, fetch the form field you want to get, and iterate every field to construct this form object. I used for fieldtypes simple text instead of integer values. Since it seems easy to read at code level.
class FormView(MethodView):
def get(self):
class DynamicForm(wtforms.Form): pass
dform = main.models.Form.objects.get(name="name2")
name = dform.name
for f in dform.fields:
print f.label
setattr(DynamicForm , f.label, self.getField(f))
d = DynamicForm() # Dont forget to instantiate your new form before rendering
for field in d:
print field # you can see html output of fields
return render_template("customform.html", form=d)
def getField(self, field):
if field.fieldtype == "text":
return TextField(field.label)
if field.fieldtype == "password":
return PasswordField(field.label)
# can extend if clauses at every new fieldtype
for a simple form render jinja template 'forms.html'
{% macro render(form) -%}
<fieldset>
{% for field in form %}
{% if field.type in ['CSRFTokenField', 'HiddenField'] %}
{{ field() }}
{% else %}
<div class="form-group {% if field.errors %}error{% endif %}">
{{ field.label }}
<div class="input">
{% if field.name == "body" %}
{{ field(rows=10, cols=40) }}
{% else %}
{{ field() }}
{% endif %}
{% if field.errors or field.help_text %}
<span class="help-inline">
{% if field.errors %}
{{ field.errors|join(' ') }}
{% else %}
{{ field.help_text }}
{% endif %}
</span>
{% endif %}
</div>
</div>
{% endif %}
{% endfor %}
</fieldset>
{% endmacro %}
and customform.html is like this
{% extends "base.html" %}
{% import "forms.html" as forms %}
{% block content %}
{{ forms.render(form) }}
{% endblock %}
Here's my view function:
def detail(request, movie_id):
movie = Movie.objects.get(id = movie_id)
movieReleases = Release.objects.filter(movie = movie)
reviews = Review.objects.filter(movie = movie)
initRating = 0
if request.user.is_authenticated():
user = Account.objects.get(user = request.user.id)
try:
myreview = Review.objects.get(movie = movie, user = user)
initRating = myreview.rating
except:
pass
releaseContext = dict()
for release in movieReleases:
if release.isReleased():
releaseContext[release.id] = {'buttonURL' : reverse('movies.views.add', args=(release.id,)), 'buttonText' : 'Add to cart'}
elif MovieReleaseReminder.objects.filter(account=user, movie=release).exists():
releaseContext[release.id] = {'buttonURL' : reverse('movies.views.unsubscribeFromReleaseReminder', args=(release.id,)), 'buttonText' : 'Unsubscribe from release reminder'}
else:
releaseContext[release.id] = {'buttonURL' : reverse('movies.views.subscribeForReleaseReminder', args=(release.id,)), 'buttonText' : 'Subscribe to release reminder'}
if MovieUpdateSubscription.objects.filter(account=user, movie=movie).exists():
movieSubscribeURL = reverse('movies.views.unsubscribeFromUpdates', args=(movie.id,))
movieSubscribeButtonText = 'Unsubscribe from updates'
else:
movieSubscribeURL = reverse('movies.views.subscribeForUpdates', args=(movie.id,))
movieSubscribeButtonText = 'Subscribe for updates'
else:
releaseContext = None
movieSubscribeURL = None
movieSubscribeButtonText = None
averageRating = calculateAverageRating(movie)
t = loader.get_template('movies/detail.html')
c = RequestContext(request, {'movie' : movie,
'movieReleases' : movieReleases,
'releaseContext' : releaseContext,
'reviews': reviews,
'averageRating': averageRating,
'initRating': initRating,
'movieSubscribeURL' : movieSubscribeURL,
'movieSubscribeButtonText' : movieSubscribeButtonText})
return HttpResponse(t.render(c))
Here's the template code in question:
{% if movieReleases%}
<table border="1px">
{% for release in movieReleases %}
<tr>
<td>{{release.format}}</td>
<td>{{release.region}}</td>
<td>{{release.price}}</td>
{% if user.is_authenticated %}
{% with release_id=release.id %}
<td><form action="{{ releaseContext.release_id.buttonURL }}" method="post">{% csrf_token %}<input type="submit" value="{{ releaseContext.release_id.buttonText }}" /></form></td>
{% endwith %}
{% endif %}
</tr>
{% endfor %}
</table>
{% endif %}
The problem is that both {{ releaseContext.release_id.buttonURL }} and {{ releaseContext.release_id.buttonText }} are evaluating to the empty string when the template is rendered, even though I've checked in the debugger that releaseContext has the appropriate data. What am I missing?
Since releaseContext is a dictionary, attribute lookup (x.y) is not what you require, but element lookup (x[y]).
So instead of:
{{ releaseContext.release_id.buttonURL }}
use
{{ releaseContext['release_id']['buttonURL'] }}
Try getting the value out of the dictionary before handing it to the template:
{% display = releaseContext['release_id']['buttonURL'] %}
{{ display }}