{% for n in medrec %}
<tr>
<td>{{ n.patient.pk }}</td>
<td>{{ n.patient.name }}</td>
<td>
<div class="ui grid">
<form class="ui form" id="mform{{ n.id }}" action="/mbill/" method="post">
{% csrf_token %}
<input value="{{ n.pk }}" type="hidden" name="pk">
{% for m in n.med_set.all %}
<div class="row">
<div class="eight wide column">{{ m.medicine }}</div>
<div class="eight wide column">
<div class="field"><input name="{{ m.medicine.id }}" type="text"></div>
<h5>{{ m.medicine.quantity }} left</h5>
</div>
</div>
{% endfor %}
</form>
</div>
</td>
<td class="right aligned">
<button type="submit" class="ui button green" form="mform{{ n.id }}" id="mbill">bill</button>
</td>
</tr>
{% endfor %}
I am trying to access pk of foreign keys of medrec or n. but instead of real pk it show 1,2,3... every time
the n.medicine.id gives 1,2,3... instead of the real 3,4,5 is there a work around for this?
class Medicine(models.Model):
medicalrec = models.ForeignKey(MedicalRec,related_name='med_set')
medicine = models.ForeignKey(Stock,related_name='stock_set')
stockpk = models.IntegerField()
class MedicalRec(models.Model):
patient = models.ForeignKey(Patient)
date = models.DateField()
disease = models.TextField()
treatment = models.TextField()
billed = models.BooleanField()
Related
ı wanna submit more than one record but in that code only first student can be record how can ı add more than one record in django view ı am prety new in django can anyone help about that table image
thats the model.py
class GonulluOgrenciDevamsizlik(models.Model):
ogrenci_dersi = models.ForeignKey('Ogrenci', null=True, on_delete=models.SET_NULL)
gonulu = models.ForeignKey('Gonullu', null=True, on_delete=models.SET_NULL)
devamsizlik = models.BooleanField(verbose_name="Devamsızlık Bilgisi",blank=True, default=False)
sinif = models.ForeignKey('SinifListe', null=True, on_delete=models.SET_NULL)
olusturma_tarihi = models.DateTimeField(auto_now_add=True, verbose_name='Oluşturma Tarihi')
guncelleme_tarihi = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-devamsizlik']
verbose_name = 'Devamsızlık'
verbose_name_plural = 'Devamsızlıklar'
def __str__(self):
return self.gonulu.ad + ' ' + self.gonulu.soyad
here is my view: in view ı had been add required foreign keys for my table and then try to save coming post data from table form.
def ogrencidevamsizlik(request, id):
details = "hesabim/ogrenci-devamsizlik.html"
siniflar = SinifListe.objects.filter(gonullu__gonullu__email=request.user.email)
ogrenci = SinifDetay.objects.filter(sinif__gonullu__gonullu__email=request.user.email)
gonulu = GonulluDersleri.objects.get(gonullu__email__iexact=request.user.email, id=id)
gonulluler = Gonullu.objects.get(email__iexact=request.user.email)
ders = GonulluDersleri.objects.filter(gonullu__email=request.user.email, id=id)
devamsizliklar = SinifDetay.objects.filter(sinif__gonullu__gonullu__email=request.user.email, sinif__gonullu__id=id)
if request.method == 'POST':
form = DevamsizlikDetayForm(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.success(request, 'Devamsızlıklar başarılı bir şekilde eklendi.')
return redirect('gonullu-siniflar')
else:
messages.error(request, 'Devamsızlık bilgilerinizdeki zorunlu alanları eksiksiz doldurmalısınız.')
else:
form = DevamsizlikDetayForm()
context = {'devamsizliklar': devamsizliklar,
'gonulu': gonulu,
'ders': ders,
'form': form,
'ogrenci': ogrenci,
'siniflar': siniflar,
'gonulluler': gonulluler}
return render(request, details, context)
and here is my table: in table ı try to add devamsizlik area for each student , gonulu , ogrenci and sinif ıd are already coming with views info but devamsizlik will submited by the gonullu so ı made a for loop for all student but when ı submit only first one can be submit thats the promlem
<form class="" novalidate method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.title }}
<div class="row justify-content-center">
<div class="col-12 col-md-9 mt-3 ">
<div class="font-weight-bold align-center">Gönüllü Dersi :
{% for x in ders %}
{{ x.gonullu }} {% if x.birinci_ders != null %} {{ x.birinci_ders }} {{ x.birinci_ders_seviye }} {% endif %}
{% endfor %}
</div>
</div>
</div>
<div class="row justify-content-center">
<table class="table table-hover">
<thead>
<tr data-toggle="collapse" data-target="#accordion" class="clickable">
<th scope="col">Id</th>
<th scope="col">Öğrenci</th>
<th scope="col">Sınıf</th>
<th scope="col">Aktif</th>
<th scope="col">Devamsızlık</th>
</tr>
</thead>
<tbody>
{% for y in devamsizliklar %}
<tr>
<td id="accordion" class="collapse">{{ y.id }}</td>
<td id="accordion" class="collapse">{{ y.ogrenci }}</td>
<td id="accordion" class="collapse">{{ y.sinif }}</td>
<td id="accordion" class="collapse">{{ y.aktif }}</td>
<td id="accordion" class="collapse">
<div class="form-group row">
<div class="col-sm-10 col-md-7">
<input data-handle-width="20" data-label-width="1" data-size="mini"
{{ form|validation_class:"devamsizlik" }} id="devamsizlik" name="devamsizlik"
{% if form.devamsizlik.value %}checked{% endif %} class="form-control swich-check"
type="checkbox">
{{ form.devamsizlik|f_errors }}
</div>
</div>
<div class="form-group row" style="visibility: hidden; display: none">
<label for="gonulu" class="col-sm-2 col-md-5 col-form-label">Gönüllü*</label>
<div class="col-sm-10 col-md-7">
<select class="custom-select my-1 mr-sm-2 {{ form|validation_class:"gonulu" }}" name="gonulu"
id="gonulu" required>
<option value="{{ gonulu.gonullu.pk }}" selected="selected">{{ gonulu.gonullu|safe }}</option>
</select>
{{ form.gonulu|f_errors }}
</div>
</div>
<div class="form-group row" style="visibility: hidden; display: none">>
<label for="ad" class="col-sm-2 col-md-5 col-form-label">Öğrenci*</label>
<div class="col-sm-10 col-md-7">
<select class="custom-select my-1 mr-sm-2 {{ form|validation_class:"ogrenci_dersi" }}" name="ogrenci_dersi"
id="ogrenci_dersi" required>
<option value="{{ y.ogrenci.ogrenci.pk }}" selected="selected">{{ y.ogrenci.ogrenci|safe }}</option>
</select>
{{ form.ogrenci_dersi|f_errors }}
</div>
</div>
<div class="form-group row" style="visibility: hidden; display: none">>
<label for="ad" class="col-sm-2 col-md-5 col-form-label">Sınıf</label>
<div class="col-sm-10 col-md-7">
<select class="custom-select my-1 mr-sm-2 {{ form|validation_class:"sinif" }}" name="sinif"
id="sinif" required>
{% for x in siniflar %}
<option value="{{ x.pk }}" selected="selected">{{ x|safe }}</option>
{% endfor %}
</select>
{{ form.sinif|f_errors }}
</div>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!--submit-->
<div class="row justify-content-center">
<button type="submit" name="save" value="save"
class="btn btn-primary mb-2 float-left bg-c b-0 rounded-0">
Devamsızlık bilgilerimi güncelle
</button>
</div>
</form>
And thats is the form.py
class DevamsizlikDetayForm(forms.ModelForm):
class Meta:
model = GonulluOgrenciDevamsizlik
fields = '__all__'
I want to display the list of users with some objects in 2 modelapps created.
these are the models.
first model:
class UserProfile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
indirizzo = models.CharField(max_length=50)
citta = models.CharField(max_length=50)
paese = models.CharField(max_length=50)
ecap = models.CharField(max_length=4)
descrizione = models.CharField(max_length=100, default='')
image = models.ImageField(upload_to='profile_image', blank=True,null=True)
second model:
class Ore(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ore",null=True,)
data = models.DateField(default=timezone.now)
oret = models.CharField(max_length=3,)
contrattiok = models.PositiveSmallIntegerField()
contrattiko = models.PositiveSmallIntegerField(default=0,)
nomecognome = models.CharField(max_length=100,blank=True)
my view:
def inizio(request):
users = User.objects.all()
return render (request, "base.html", {"users":users})
my template:
{% for users in users %}
<tbody>
<tr>
<td>
<img src="{{ users.userprofile.image.url }}"class="thumbnail">
<h4 class="small font-weight-bold">{{users}}</h4>
</td>
<td><h4 class="small font-weight-bold">{{users.last_name}}</h4></td>
<td class="text-center">
<h4 class="small font-weight-bold" class="btn btn-primary btn-circle">{{ users.ore.contrattiok }}</h4> <<<<<(does not work)
</td>
</tr>
{% endfor %}
I saw several problems in your templates.
1. It would be better to make different variable of users loop to increase readability code.
don't do this: {% for users in users %}
but instead: {% for user in users %}
so then you can use it with user instead of users inside loop like:
{{ user.last_name }}
2. your <tbody> inside forloop users, but theres no </tbody> right before the {% endfor %}.
But I suggest you to do not include <tbody> inside forloop.
Do this instead:
<tbody>
{% for user in users %}
<tr><td></td></tr>
{% endfor %}
</tbody>
since your foreign key is inside Ore model instead
(one to many relationship which means 1 user has many ores),
so you need to loop every ore on each user.
{% for user in users %}
{% for ore in user.ore.all %}
{{ ore.contrattiok }}
{% endfor %}
{% endfor %}
so the final result will be like this:
<tbody>
{% for user in users %}
<tr>
<td>
<img src="{{ user.userprofile.image.url }}" class="thumbnail">
<h4 class="small font-weight-bold">{{ user }}</h4>
</td>
<td><h4 class="small font-weight-bold">{{user.last_name}}</h4></td>
<td class="text-center">
{% for ore in user.ore.all %}
<h4 class="small font-weight-bold" class="btn btn-primary btn-circle">
{{ ore.contrattiok }}
</h4>
{% endfor %}
</td>
</tr>
{% endfor %}
</tbody>
EDITED
based on your comment, so you want to sum the total of contrattiok field?
if that so, you need to change your view using annotate
from django.db.models import Sum
users = User.objects.annotate(total_contrattiok=Sum('ore__contrattiok'))
then in your template:
{% for user in users %}
<td class="text-center">
<h4 class="small font-weight-bold" class="btn btn-primary btn-circle">
{{ user.total_contrattiok }}
</h4>
</td>
{% endfor %}
One more time, I come back to you in order to get advices or your help.
I'm displaying in my django template a list of objects and I would like to sort them through a common attributes : category.
Each object displayed (a publication) gets some attributes : category, format, language ...
For example :
The white text with blue background indicates the category. I have 2 publications with category = BIOLOGICAL STANDARDISATION PROGRAMME and 1 publication with category = TEST
I would like to group both BIOLOGICAL STANDARDISATION PROGRAMME in one panel but I don't find a way to do that.
This is my HTML template file :
{% for element in test_research|dictsort:"publication.category.name" %}
<div class="col-sm-12">
<div class="panel panel-default request-panel">
<div class="panel-heading" role="tab">
<h4 class="panel-title">
{{ element.publication.category }}
</h4>
</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-9">
<p class="request-publication">{{ element.publication }} </p>
</div>
<div class="col-sm-3 request-cover">
{% if element.publication.cover %}
<a href="{{ element.publication.cover.url }}" target="_blank">
{% thumbnail element.publication.cover "40x40" crop="center" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}</a>
{% endif %}
</div>
</div>
</div>
<div class="panel-footer">
<div class="row">
<table>
<tbody>
<tr>
<td class="col-md-1">
<div class="material-switch pull-right">
<input id="someSwitchOptionSuccess_{{ element.id }}" name="DocumentChoice" type="checkbox"
value="{{ element.id }}"/>
<label for="someSwitchOptionSuccess_{{ element.id }}" class="label-success"></label>
</div>
</td>
<td class="col-md-1 request-language"> {{ element.language }}</td>
<td class="col-md-1 request-format">
{% if element.format == 'pdf' %}
<span class="badge alert-danger">{{ element.format }}</span>
{% endif %}
{% if element.format == 'epub' %}
<span class="badge alert-info">{{ element.format }}</span>
{% endif %}
</td>
<td class="col-md-1 request-flag">
{% if element.publication.new_publication == True %}
<span class="glyphicon glyphicon-flag"></span>
{% else %}
<span></span>
{% endif %}
</td>
<td class="col-md-offset-5 col-md-3 text-right">{{ element.title }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
{% endfor %}
And in my views.py file :
def get_context_data(self, **kwargs):
search_category = Document.objects.values_list('publication__category__name', flat=True).distinct()
kwargs['search_category'] = search_category
search_format = Document.objects.values_list('format', flat=True).distinct()
kwargs['search_format'] = search_format
search_language = Document.objects.values_list('language', flat=True).distinct()
kwargs['search_language'] = search_language
checkbox_category = self.request.GET.getlist('CategoryChoice')
checkbox_format = self.request.GET.getlist('FormatChoice')
checkbox_language = self.request.GET.getlist('LanguageChoice')
choice_title = self.request.GET.get('TitleChoice')
kwargs['checkbox_category'] = checkbox_category
kwargs['checkbox_format'] = checkbox_format
kwargs['checkbox_language'] = checkbox_language
kwargs['choice_title'] = choice_title
# default to all documents
test_research = Document.objects.all().order_by('publication__category__name')
kwargs['test_research'] = test_research
if "SubmitChoice" in self.request.GET:
test_research = Document.objects.all()
# if user entered any search criteria, add those filters
if checkbox_category:
test_research = test_research.filter(publication__category__name__in=checkbox_category)
if checkbox_format:
test_research = test_research.filter(format__in=checkbox_format)
if checkbox_language:
test_research = test_research.filter(language__in=checkbox_language)
if choice_title:
test_research = test_research.filter(
Q(title__icontains=choice_title) | Q(publication__title__icontains=choice_title))
kwargs['test_research'] = test_research
return super(HomeView, self).get_context_data(**kwargs)
I can add models.py file if necessary. How it's possible to group them under the same category panel ?
EDIT :
I maybe found something with that :
{% for category in checkbox_category %}
<div class="col-sm-12">
<div class="panel panel-default request-panel">
<div class="panel-heading" role="tab">
<h4 class="panel-title">
{{ category }}
</h4>
</div>
{% for element in test_research %}
{{ element.publication.category }} - {{ category }}
{% if element.publication.category == category %}
But the if condition doesn't seems to work even if {{element.publication.category}} == {{category}}
You should restructure your data in the view so that it's already prepared for the template. Django's template system is built in a way to avoid this type of logic.
You might be able to do it simply like this:
from collections import defaultdict
research_categories = defaultdict(list)
for element in test_research:
research_categories[element.publication.category].append(element)
Then use research_categories in your template.
I am trying to edit user details of a specific user when admin logins its going to edit page but when I press the update button it's not updating not showing any error message. (correct me please if I am wrong).
This is my edit.html
{% extends 'base.html' %}
{% block title %}edit details{% endblock %}
{% block content %}
{% if emp %}
<form method="POST" class="form-inline my-2 my-lg-0" ">
{% csrf_token %}
<div class="container">
<br>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<h3>Update Details</h3>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee User:</label>
<div class="col-sm-4">
<input type="text" id="id_user" required maxlength="20" value="{{
emp.user }}"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee first_name:</label>
<div class="col-sm-4">
<input type="search" id="id_first_name" required maxlength="100"
value="{{ emp.first_name }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee last_name:</label>
<div class="col-sm-4">
<input type="text" id="id_last_name" required maxlength="100" value="{{
emp.last_name }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee Email:</label>
<div class="col-sm-4">
<input type="email" id="id_email" required maxlength="254" value="{{
emp.email }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee Gender:</label>
<div class="col-sm-4">
<input type="text" id="id_gender" required maxlength="15" value="{{
emp.gender }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee Age:</label>
<div class="col-sm-4">
<input type="text" id="id_age" required maxlength="100" value="{{
emp.age }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee salary:</label>
<div class="col-sm-4">
<input type="text" name="ename" id="id_salary" required maxlength="100"
value="{{ emp.salary }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<button type="submit" class="btn btn-success">Update</button>
</div>
</div>
</div>
</form>
{% endif %}
{% endblock %}
This is my profile.html page
{% if user.is_authenticated %}
{% if user.is_superuser %}
<table class="table table-striped table-bordered table-sm">
<thead class="thead-dark">
<tr>
<th>Employee User</th>
<th>Employee first_name</th>
<th>Employee last_name</th>
<th>Employee Email</th>
<th>Employee Gender</th>
<th>Employee Age</th>
<th>Employee Salary</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for employee in employees %}
<tr>
<td>{{ employee.user }}</td>
<td>{{ employee.first_name }}</td>
<td>{{ employee.last_name }}</td>
<td>{{ employee.email }}</td>
<td>{{ employee.gender }}</td>
<td>{{ employee.age }}</td>
<td>{{ employee.salary }}</td>
<td>
<a href="{% url 'edit' employee.id %}"><span class="glyphicon
glyphicon-pencil" >Edit</span></a>
Delete
</td>
</tr>
{% endfor %}
</tbody>
</table>
<br>
<br>
<center><a href="{% url 'signup' %}" class="btn btn-primary">Add New
Record</a></center>
{% else %}
<p>username : {{ user }}</p>
<p>firstname : {{ user.first_name }}</p>
<p>lastname : {{ user.last_name }}</p>
<p>{{user.employee.age}}</p>
<p>
Edit details
</p>
<p>
Change password
</p>
{% endif %}
{% endif %}
This is view.py of edit method
def edit(request, emp_id):
if request.method == 'POST':
emp = employee.objects.get(pk=emp_id)
form = EmployeForm(request.POST or None, instance=emp)
if form.is_valid():
form.save()
messages.success(request, ('Item has been edited'))
return HttpResponseRedirect('view_profile')
else:
emp = employee.objects.get(pk=emp_id)
return render(request, 'edit.html', {'emp': emp})
def view_profile(request):
employees = employee.objects.all()
args= {'user':request.user,'employees':employees}
return render(request,'profile.html',args)
This is my model page
class employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(max_length=50)
gender = models.CharField(max_length=1,choices=(('M','Male'),
('F','Female')),blank=True)
age = models.PositiveIntegerField(blank=True, null=True)
salary = models.CharField(blank = True,max_length=50
def __str__(self):
return self.user.username
Please, any advice on how to troubleshoot or any documentation I can read.
You're not using the form properly. Forms are not only for validation, they are also responsible for rendering the error messages. You want to change your view to pass the form to the template:
def edit(request, emp_id):
emp = employee.objects.get(pk=emp_id)
if request.method == 'POST':
form = EmployeForm(request.POST, instance=emp)
if form.is_valid():
form.save()
messages.success(request, ('Item has been edited'))
# this one is probably not going to work
# as expected - you may want to check the
# doc for the `redirect` shortcut instead
return HttpResponseRedirect('view_profile')
else:
form = EmployeForm(instance=emp)
return render(request, 'edit.html', {'emp': emp, 'form':form})
Then in your template instead of manually writing the whole form markup, use the form for rendering so you have the validation errors correctly displayed.
I am trying to mark attendance. But I am not able to get the code. My submit should send the input to database for each student. Any suggestion for doing this in better way is welcome.
My models.py is as follows
It has Employee, Mentor and Student and below is the model where values can be changed.
class ClassName(models.Model):
class_name = models.CharField(max_length=20)
class_date=models.DateField(blank=True, null=True)
Mentor= models.ForeignKey(Mentor, related_name='class_mentor')
student = models.ManyToManyField(Student, related_name='class_student')
attendance = models.BooleanField(default=True)
def __str__(self):
return str(self.class_name)
Views.py : This is just to display the markattendance page. I am not able to figure out how to get the value and Post the value to database. Right now, I am fetching Students value from the Students table. I think I should be creating Classname Form and and display students. I was getting Internal server error.
def markattendance(request):
students = Student.objects.all()
return render(request, 'home/markattendance.html',
{'students': students})
markattendance.html : On clicking submit, the attendance should be marked.
{% extends 'home/index.html' %}
{% block content %}
<div class="container-fluid">
<div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Name</th>
<th>Class</th>
<th>Attendance</th>
</tr>
</thead>
<tbody>
{% for students in students %}
{% ifequal students.Men_name|stringformat:"s" user.username %}
<tr>
<td>{{ students.Student_name }}</td>
<td>{{ students.Student_Class }}</td>
<td>
<label class="switch">
<input id="toggle-slider_position()" type="checkbox">
<span class="slider round"></span>
</label>
</td>
</tr>
{% endifequal %}
{% endfor %}
</tbody>
</table>
</div>
<br/>
<div class="row" >
<div class="col-sm-4"></div>
<div class='col-sm-4' align="center">
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<button class="btn btn-lg">Submit</button>
</div>
<div class="col-sm-4">
</div>
</div>
<br/><br/><br/><br/><br/>
</div>
</div>
</div>
{% endblock %}
Please help me out. Any suggestion is welcome.