django get value from html - python

I want to list all tables using my Crawledtables, and when i click table1 i need to pass in the table_id. With that table_id i need to get the table_name and list all the info inside that table. i m stuck at getting the table_id
this is my views.py
EDITED views.py
def table_base(request):
table_name = Crawledtables._meta.db_table
list_tables = Crawledtables.objects.order_by('id')
return render(request, 'tables/table_base.html', {'table_name': table_name,
'list_tables': list_tables})
class AboutDetail(DetailView):
model = Crawledtables
pk_url_kwarg = 'table_id'
template_name = 'tables/table_list.html'
def __init__(self, **kwargs):
super(AboutDetail, self).__init__(**kwargs)
def get_object(self, **kwargs):
if 'table_id' not in self.kwargs:
return Crawledtables.objects.get(id=1)
else:
id_table = Crawledtables.objects.get(id=self.kwargs['table_id'])
return id_table
# need to create another fuction and i need to pass on the table_id
# with this table_id i need to get the table_name
# need to use the table_name to get the content using
# Ex: test = AllTables.objects.all()
# i need to return the the content of the table id
this is my table_base.html
<br>
<div class="container">
<div class="jumbotron">
<h1> {{ table_name }} List</h1>
{% if list_tables %}
<table class="table table-bordered sortable">
<thead>
<th>Id</th>
<th>Name</a></th>
<th>Date</a></th>
<th>Search Button</th>
</thead>
{% for list in list_tables %}
<tr>
<td><pre><a href="#" >{{ list.id }}</a></pre></td>
{# this is where i get the id of the table in CrawledTables and i set it equal to table_id #}
<td><pre>{{ list.name }}</pre></td>
<td><pre>{{ list.date }}</pre></td>`
</tr>
{% endfor %}
</table>
{% else %}
<p> No Records Found</p>
{% endif %}
</div>
</div>
and this is what i have for now for table_list.html
<table class="table table-bordered sortable">
<thead>
<tr>
{{ context }}
<th>Id</th>
<th>Title</th>
<th>Url</th>
</tr>
</thead>
{# make a for loop here #}
<tr>
<td> </td> {# get the id #}
<td></td> {# get the title #}
<td></td> {# get the url #}
</tr>
{% endfor %}
</table>
I ve tried to figure out without using requests or forms...i did get it...but i got stuck at creating a search engine...so now i have to go back to do it the right way using request and/or forms...
Please help me i really don't know what command i need to put...and those django docs don't really help me because its more about users and passwd and emails...
Thank you in advance
UPDATE
models.py
#python_2_unicode_compatible
class Crawledtables(models.Model):
name = models.CharField(db_column='Name', unique=True, max_length=100)
date = models.CharField(db_column='Date', max_length=100)
class Meta:
managed = True
db_table = 'CrawledTables'
def __str__(self):
return self.name
def __unicode__(self):
return '%name' % {'name': self.name}
#python_2_unicode_compatible
class AllTables(models.Model):
title = models.TextField(db_column='Title', blank=True, null=True)
url = models.CharField(db_column='Url', unique=True, max_length=250, blank=True,
null=True)
created_at = models.DateTimeField(db_column='Created_at')
class Meta:
managed = False
def __str__(self):
return self.url
def __unicode__(self):
return self.title
forms.py
class TableIdForm(forms.Form):
class Meta:
fields = ('id', 'name','date')
model = Crawledtables
class AllTablesForm(forms.Form):
title = forms.CharField(label='title')
url = forms.CharField(label='url', max_length=250)
created_at = forms.DateTimeField(label='Created at')

Related

Django automatically add number in table

I would like when I add a file in the table it automatically adds a number from 1. I cannot use the primary key in the model because I already use it. anyone have a solution. thank you.
====Page.html====
<h5>Documents</h5>
</div>
<div class="row">
<div class="col-md">
<div class="card card-body">
<table class="table table-sm">
<tr>
<th>#</th>
<th>Nom du fichier</th>
<th>Fichier</th>
<th></th>
</tr>
{% for d in document %}
<tr>
<td>{{d.Number}}</td>
<td>{{d.Description}}</td>
<td><a download href="{{d.Fichier.url}}">{{d.Fichier}}</a></td>
<td><a class="btn btn-outline-danger" href="{% url 'supprimerdocument' d.id %}">Supprimer</a>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
====view.py====
# Button to add docs
#login_required(login_url='loginpage')
#allowed_users(allowed_roles=['admin', 'livraison'])
def createDocument(request):
forms = documentForm()
if request.method == 'POST':
forms = documentForm(request.POST, request.FILES)
if forms.is_valid():
forms.save()
return redirect('/employe')
context = {'forms':forms}
return render(request, 'accounts/document_form.html', context)
====Models.py====
class Document(models.Model):
employe = models.ForeignKey(Employe, null=True, on_delete=models.SET_NULL)
Number = models.IntegerField(default=1)
Description = models.CharField(max_length=100, null=True)
Fichier = models.FileField(upload_to='documents/')
data_created = models.DateTimeField(auto_now_add=True, null=True)
====Form.py====
class documentForm(ModelForm):
class Meta:
model = Document
fields = '__all__'
exclude = ['Number']
You can use forloop.counter in your template to access the (1-indexed) iteration of the for loop
{% for d in document %}
<tr>
<td>{{ forloop.counter }}</td>
...
</tr>
{% endfor %}
It looks like you can do an AutoField as per How do I make an auto increment integer field in Django?
But as a fallback: You could just do an Integer field and override the modelform's .save() method and auto fill it like self.some_field = Document.objects.all().count()
..if you do that, best to add a flag for if it's an edit form or not.. I believe you can do that with if self.instance: if true, is edit form
use callable default
def get_next_number():
max_val = Document.objects.aggregate(models.Max('Number'))['Number__max'] or 0
return max_val + 1
class Document(models.Model):
Number = models.IntegerField(default=get_next_number)
...

Chained Dropdown in ModelFormset_Factory - Django

I want chained dropdown list in model formset.
I have 4 models in my app App_Prod - Category, Product, OrderInfo, Order
In my form, I used two views combinely. OrderInfo and Order
So the choice list of product field of the Order model should be dependent on the category field of the OrderInfo model. Like if I select Electronics category the choice list should return only laptop and mobile option instead of showing all. See the image for your better understanding.
Please suggest me what should I edit in my codes, or is there any other way to do so.
models.py
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.IntegerField()
category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE)
def __str__(self):
return self.name
class OrderInfo(models.Model):
category = models.ForeignKey(Category, related_name='orderInfo', on_delete=models.CASCADE)
date = models.DateField()
def __str__(self):
return self.category.name
class Order(models.Model):
info = models.ForeignKey(OrderInfo, related_name='orders', on_delete=models.CASCADE)
product = models.ForeignKey(Product, related_name='productName', on_delete=models.CASCADE, null=True)
quantity = models.IntegerField()
def __str__(self):
return self.product.name
forms.py
class OrderInfoForm(forms.ModelForm):
date = forms.DateField(widget=DateInput)
class Meta:
model = OrderInfo
fields = ["category","date",]
class OrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ["product","quantity",]
widgets = {
'product': forms.Select(attrs={'class': 'formset-field form-control'}),
'quantity': forms.NumberInput(attrs={'class': 'formset-field form-control'}),
}
views.py
def order_create(request):
context = {}
OrderFormset = modelformset_factory(Order, form=OrderForm)
form = OrderInfoForm(request.POST or None)
formset = OrderFormset(request.POST or None, queryset=Order.objects.none(), prefix='productName')
if request.method == "POST":
if form.is_valid() and formset.is_valid():
try:
with transaction.atomic():
info = form.save(commit=False)
info.save()
for order in formset:
data = order.save(commit=False)
data.info = info
data.save()
except IntegrityError:
print("Error Encountered")
return redirect('App_Prod:order_create')
context['formset'] = formset
context['form'] = form
return render(request, 'App_Prod/order_create.html', context)
urls.py
urlpatterns = [
path('create/', views.order_create, name="order_create"),
]
order_create.html
<!DOCTYPE html>
{% extends 'base.html' %}
{% load static %}
{% load crispy_forms_tags %}
{% block body_block %}
<form method="POST">
{% csrf_token %}
{{ form|crispy }}
<table class="table form-table table-bordered table-sm">
<thead class="text-center">
<tr>
<th>Product</th>
<th>Quantity</th>
<th></th>
</tr>
</thead>
<tbody>
{% for form_data in formset %}
<tr class="item">
<td>
{{ form_data.product }}
</td>
<td>
{{ form_data.quantity }}
</td>
<td>
<button type="button" class="btn btn-danger btn-sm remove-form-row"
id="{{ formset.prefix }}">
Delete
</button>
</td>
</tr>
{% endfor %}
<tr>
<td colspan="9"
style="border-left: none!important; border-right: none !important; border-bottom: none!important;">
<button type="button" class="btn btn-sm btn-success add-form-row"
id="{{ formset.prefix }}">
Add Activity
</button>
</td>
</tr>
</tbody>
</table>
{{ formset.management_form }}
<button class="btn btn-info" type="submit">Submit</button>
</form>
{% endblock %}
{% block extra_script %}
<script type="text/javascript" src="{% static 'js/formset.js' %}"></script>
{% endblock%}

django modelformset_factory raises form not valid: id Select a valid choice. That choice is not one of the available choices

i am trying to create a student attendance sheet in django using django modelformset_factory...but when i save the formset it thows me the id is not valid here is my implementation
i have two models one StudentAttendance and StudentClass:
1: the StudentAttendance model is responsible for stroring students
attendance data here is the example
class StudentAttendance(models.Model):
classroom_id = models.ForeignKey(ClassRoom, on_delete=models.CASCADE, related_name='student_attendance')
attendance_date = models.DateField()
student_id = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='student_attendance')
status = models.CharField(max_length=20, choices=ATTENDANCE_CHOICES)
comment = models.CharField(max_length=150, blank=True)
#signed_by = models.ForeignKey(Teacher, on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.student_id)
2: the StudentClass model is a submodel that maps a student to his respective class
class StudentClass(models.Model):
"""
This is a bridge table to link a student to a class
when you add a student to a class we update the selected class capacity
"""
main_class = models.ForeignKey(ClassRoom, on_delete=models.CASCADE, related_name='class_student')
academic_year = models.ForeignKey(AcademicYear, on_delete=models.CASCADE)
student_id = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='student_class')
#property
def is_current_class(self):
if self.academic_year.is_current_session:
return True
return False
def __str__(self):
return str(self.student_id)
So my forms.py implementation is:
class StudentsAttendanceForm(forms.ModelForm):
class Meta:
model = StudentAttendance
fields = ('status', 'comment')
#exclude = [
#'siqned_by',
#]
On my views.py:
def student_attendance_manager(request):
"""
this function is responsible for querying the attendance parameters and present the student multiple attendance form
"""
if request.method == "POST":
# get the class name , the attendance date and present the attendance form
class_name = get_object_or_404(ClassRoom, pk=request.POST['class_name']) # class name
attendance_date = request.POST['date_field'] # date
# get the students in the class which is current active
student = StudentClass.objects.filter(main_class=request.POST['class_name'])
# modelform creation
AttendanceFormSet = modelformset_factory(StudentAttendance, form=StudentsAttendanceForm, extra=0)
# initiate the form and pass in the required parameters ie: classroom_id, attendance_date
list_formset = AttendanceFormSet(queryset=student)
# initialise the class_name and attendance date
#for form_inst in list_formset:
#form_inst.fields['classroom_id'].initial = class_name
#form_inst.fields['attendance_date'].initial = attendance_date
template = 'attendance/students_attendance_form.html'
context = {
'class_name':class_name,
'attendance_form': list_formset,
}
return JsonResponse({'html_form': render_to_string(template, context, request=request)})
template = 'attendance/students_attendance_manager.html'
class_date_selector_form = ClassroomDateQueryForm(request.GET or None)
context = {
'choice_form':class_date_selector_form
}
return render(request, template, context)
when the User Posts the form to be submited this is how i handle the form:
def student_attendance_register(request):
if request.method == "POST":
students = StudentClass.objects.filter(main_class=request.GET['class_id'])
StudentsAttendanceFormSet = modelformset_factory(StudentAttendance, form=StudentsAttendanceForm, extra=0)
list_formset = StudentsAttendanceFormSet(request.POST, queryset=students)
if list_formset.is_valid():
list_formset.save()
return HttpResponse('valid')
else:
return HttpResponse(list_formset.errors)
on my template i display the form in a table and this is my implementation:
form.html:
<form class="js-mark-attendance" method="post" action="{% url 'attendance:student_attendance_register' %}?class_id={{ class_name.id }}">
{% csrf_token %}
<table class="table-striped table table-bordered" id="Student_attendance_table">
<thead>
<tr>
<th>#</th>
<th>Admission Number</th>
<th>Name</th>
<th>Status</th>
<th>Comment</th>
</tr>
</thead>
<tbody>
{{ attendance_form.management_form }}
{% for form_inst in attendance_form %}
{% for hidden in form_inst.hidden_fields %}
{{ hidden }}
{% endfor %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ form_inst.instance.student_id.admission_number }}</td>
<td>{{ form_inst.instance.student_id }}</td>
<td>{{ form_inst.status }}</td>
<td> {{ form_inst.comment }}</td>
{{ form_inst.classroom_id.as_hidden }}
{{ form_inst.attendance_date.as_hidden }}
{{ form_inst.student_id.as_hidden }}
</tr>
{% endfor %}
</tbody>
</table>
<div class="row">
<div class="col-md-12 d-flex justify-content-center">
<input type="submit" value="Mark Attendance" class="btn btn-success">
</div>
</div>
</form>
and this is the error that django throws after the user has clicked submit button:
id
Select a valid choice. That choice is not one of the available choices.
so my question is ... how can i handle this post request form and or if their is an alternative way of doing my task:
any leads will be much upreciated
oops....I found my problem was the wrong usage of modelsfomset_factory...

NoReverseMatch at /availability/1/edit/ Reverse for 'availability_list' with no arguments not found. Tried: ['availability\\/(?P<pk>[0-9]+)\\/list$']

I'm getting this error using Django 3 when trying to either 1) create a new object (CreateView), or 2) edit an existing one (UpdateView). Using CBVs and ModelForms.
I explored similar questions on Stackoverflow. Very often, it's about the template missing pk reference, but I triple-checked that and it doesn't seem to be the case.
Any idea?
Here are my codes:
URLs
path('availability/<int:pk>/list', views.AvailabilityListView.as_view(), name='availability_list'),
path('availability/new/', views.AvailabilityCreateView.as_view(), name='availability_new'),
path('availability/<int:pk>/edit/', views.AvailabilityUpdateView.as_view(), name='availability_edit'),
Views
class AvailabilityUpdateView(UpdateView):
template_name = 'crm/availability_form.html'
form_class = AvailabilityForm
model = Availability
class AvailabilityUpdateView(UpdateView):
template_name = 'crm/availability_form.html'
form_class = AvailabilityForm
model = Availability
class AvailabilityListView(TemplateView):
template_name = 'crm/availability_list.html'
def get_context_data(self, **kwargs):
user = self.request.user
kwargs['availabilities'] = Availability.objects.filter(staff__manager=Manager.objects.get(user=user)).filter(staff=self.kwargs['pk'])
return super().get_context_data(**kwargs)
Forms
class AvailabilityForm(forms.ModelForm):
class Meta():
model = Availability
exclude = []
Models
class Availability(models.Model):
staff = models.ForeignKey(Staff, on_delete=models.CASCADE)
start = models.DateTimeField()
end = models.DateTimeField()
class Meta:
verbose_name_plural = "Availabilities"
def get_absolute_url(self):
return reverse('staff_list')
Template
{% block body_block %}
<div class="container">
<div class="heading">
<h1>Availability</h1>
<a class = 'btn btn-primary' href="{% url 'availability_new' %}">+Create new availability</a>
</div>
<hr/>
{% if availabilities %}
<table class="table">
<tbody>
{% for availability in availabilities %}
<tr>
<td>{{availability.pk}}</td>
<td>{{availability.staff}}</td>
<td>{{availability.start}}</td>
<td>{{availability.end}}</td>
<td>
Edit
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p class='empty'>Staff does not have any availability</p>
{% endif %}
</div>
{% endblock %}

May I display the field from other table in the template in Django 1.10?

May I display the field from other table in the template in Django 1.10?
I have 3 tables as the following models.py
import datetime
from django.db import models
from django.forms import ModelForm
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
#python_2_unicode_compatible
class Group(models.Model):
group_name = models.CharField(max_length=255)
no_of_monk = models.IntegerField()
def __str__(self):
return self.group_name
class Meta:
ordering = ['id']
#python_2_unicode_compatible
class Tbl_Province(models.Model):
province_code = models.CharField(max_length=2)
province_name = models.CharField(max_length=150)
geo_id = models.IntegerField()
def __str__(self):
return self.province_name
#python_2_unicode_compatible
class Contact(models.Model):
group = models.ForeignKey(Group, on_delete=models.CASCADE)
order = models.IntegerField()
name = models.CharField(max_length=255, db_index=True)
description = models.TextField(blank=True)
amount = models.DecimalField(max_digits=10, decimal_places=2)
confirm = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
province = models.ForeignKey(Tbl_Province, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Meta:
ordering = ['order', 'province']
and I would like to display tbl_province.province_name where id=contact.id in the following template, is it possible?
{% for contact in group.contact_set.all %}
<tr>
<td width="10%" class="table-text"><div><strong>{{ forloop.counter0|mod:5|add:1 }}</strong></div></td>
<td width="10%" class="table-text"><div>{{ forloop.counter }}</div></td>
<td width="10%" class="table-text"><div>{{ contact.order }}</div></td>
<td class="table-text"><div>{{ contact.name }}</div></td>
{% if contact.province_id %}
<td class="table-text"><div>{{ **Want to display tbl_province.province_name where id=contact.id here** }}</div></td>
{% endif %}
<td width="13%" class="table-text"><div><input type="text" name="ord" id="con-ord" class="form-control" value="{{ contact.amount|intcomma }}"></div></td>
<td width="10%" class="table-text"><div>บาท</div></td>
<td>
<form action="{% url 'contribution:contactdel' contact.id %}" method="POST">
{% csrf_token %}
<button type="submit" id="delete-group" class="btn btn-danger">
<i class="fa fa-btn fa-trash"></i> Delete
</button>
</form>
</td>
</tr>
{% endfor %}
Templates don't have the access to the database, so they can't execute a query (and that's basically what you want)
However, I can see that you have a foreign key to Tbl_Province in Contact and you can use that instead - just write {% contact.province.province_name %} (if I understand correctly what you're trying to achieve)
If you need anything more exotic, you'll have to execute your query inside the view function, and then pass it to template context.

Categories

Resources