how can i get data from this below django html template
<form action="{% url 'purchase_order_item' p_order.id %}" method="post" enctype="multipart/form-data" class="form-group">
{% csrf_token %}
<table id="example-datatable" class="table table-vcenter table-condensed table-bordered">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Brand Name</th>
<th>Product Type</th>
<th>Category</th>
<th>SubCategory</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for p in product %}
<tr>
<td>{{p.id}}</td>
<td>
{{p.name}}
</td>
<td>{{p.brand}}</td>
<td>{{p.ptype}}</td>
<td>{{p.catname}}</td>
<td>{{p.supplier}}</td>
<td>
<input type="text" id="quantity" name="quantity" value="1" class="form-control">
</td>
<td>
<input type="text" id="unitprice" name="unitprice" value="1" class="form-control">
</td>
<td>
<button type="submit" class="btn btn-primary btn-xs">Add</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
views.py
def purchase_order_item(request,id):
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
if (len(str(day))) == 1:
day = '0' + str(day)
if (len(str(month))) == 1:
month = '0' + str(month)
date = str(year) + '-' + str(month) + '-' + str(day)
randstrn = ""
for i in range(5):
randstrn = randstrn + random.choice(string.digits)
# catid = Cat.objects.get(name=name).pk
# news = News.objects.filter(ocatid=catid) # showing post based on master category
supplier = Supplier.objects.all()
p_order = Purchase_order.objects.get(pk=id)
product = Parts.objects.all()
# this is the form for getting data from html
if request.method == 'POST':
quantity = request.POST.get('quantity')
unit_price = request.POST.get('unitprice') # itemid = pk type
nameid = request.POST.get('quantity')
ref_num = Purchase_order.objects.get(pk=id).order_id
order_id = Purchase_order.objects.get(pk=id).order_id # get Purchase Order Id for Relational Referance
sv = Purchase_order_item(
ref_number=ref_num,
product_name='sample_name',
# product_brand='product_brand',
# product_type = 'product_type',
# product_cat = 'product_cat',
# product_sub_cat = 'k',
quantity=quantity,
unit_price = unit_price,
total_price = '12',
order_id=order_id
)
sv.save()
# return redirect('purchase_order_item_list')
return render(request,'back/purchase/assign_purchas_item.html',
{'p_order':p_order,'supplier':supplier,
'product':product}
)
This is my Models.py
class Purchase_order_item(models.Model):
# order_id = models.IntegerField(default=0) # this is a purchase order id for referance purpose and relation both
ref_number = models.IntegerField(default=0)
product_name = models.CharField(max_length=50) # generate an unique Rendome number for farther relation for invoice item
product_brand = models.CharField(max_length=50)
product_type = models.CharField(max_length=50) # genuine or after market
product_cat = models.CharField(max_length=50) # product name
product_sub_cat = models.CharField(max_length=50) # product name
quantity = models.IntegerField(default=0)
unit_price = models.FloatField(default=250)
total_price = models.FloatField()
order_id = models.IntegerField(default=0)
This is my Html screenshot
Now my question is that ..
how can i get all the listed data after click add button as like Name , brand name , product type , category , subcat , quantity , unit price , etc save to purchase_order_item table .
thanks in advance
Related
I have 2 models; Invoice and Expense. Both have a date field. I want to create a django-filter where I put a start-date and end-date and get the result on 2 differents table in the same HTML page. So far I need to use 2 different filters and if I put the date in the Invoice Filter it clears the Expense Filter. Same if I put the date in the Expense Filter it clears the Income Filter.
Here is my filters.py
class DashboardIncomeFilter(django_filters.FilterSet):
start_date = DateFilter(field_name = "invoice_date", lookup_expr='gte', label='Start Date')
end_date = DateFilter(field_name = "invoice_date", lookup_expr = 'lte', label = 'End Date')
class Meta:
model = Invoice
fields = '__all__'
exclude = ['invoice_slug', 'therapist', 'invoice_date', 'service', 'customer', 'invoice_no', 'price', 'quantity', 'total', 'payment', 'balance']
class DashboardExpenseFilter(django_filters.FilterSet):
exp_start_date = DateFilter(field_name = "expense_date", lookup_expr='gte', label='Start Date')
exp_end_date = DateFilter(field_name = "expense_date", lookup_expr = 'lte', label = 'End Date')
class Meta:
model = Expense
fields = '__all__'
exclude = ['expense_date', 'vendor', 'expense_category', 'description','amount']
Than on my dashboard.html
{% block content %}
<center><h3>DASHBOARD</h3><br/>
<h3>Todays Date: {{ month }} {{ current_day }}, {{ year }} # {{ current_time }}</h3><br/>
<div class="row">
<div class="col">
<div class="card card-body"><h4>Incomes Filter</h4><br/>
<form method="get">
{{ ResultFilter.form }}
<button class="btn btn-primary" type="submit">
Search...</button>
<a class="btn btn-primary" href="{% url 'Dashboard' %}" role = "button">Reset</a>
</form>
</div><br/>
<table style="width: 80%" class="table table-primary table-bordered table-striped">
<thead>
<tr>
<th scope="col">Total Incomes</th>
<th scope="col">Total Threatments</th>
<th scope="col">Days Open</th>
</tr>
</thead>
<tbody>
<tr>
<td scope="row">{{ income_total }} IDR</td>
<td scope="col">{{ threatments }}</td>
<td scope="col">{{ days_open }}</td>
</tr>
</tbody>
</table>
</div><br/>
<div class="col">
<div class="card card-body"><h4>Expenses Filter</h4><br/>
<form method="get">
{{ OutcomeFilter.form }}
<button class="btn btn-primary" type="submit">
Search...</button>
<a class="btn btn-primary" href="{% url 'Dashboard' %}" role = "button">Reset</a>
</form>
</div><br/>
<table style="width: 80%" class="table table-primary table-bordered table-striped">
<thead>
<tr>
<th scope="col">Total Expenses</th>
<th scope="col">Personnal Expenses</th>
<th scope="col">Profit +/-</th>
</tr>
</thead>
<tbody>
<tr>
<td scope="col">{{ expense_total }} IDR</td>
<td scope="col">{{ personnal_expense }} IDR</td>
<td scope="col">{{ profit }} IDR</td>
</tr>
</tbody>
</table>
</div>
</div>
</div><br/>
Finally, my views.py
ResultFilter = DashboardIncomeFilter(request.GET, queryset=invoice_list)
invoice_list = ResultFilter.qs
OutcomeFilter = DashboardExpenseFilter(request.GET, queryset=expense_list)
expense_list = OutcomeFilter.qs
All the fields are excluded since I only want to filter on the invoice_date and expense_date field at the same time. Thanks.
When you submit whichever of the filters you specified, it does a GET request with the otther two filter values belonging to the other table not specified.
I've never tried this, but I expect that you can force it to submit all four with either filter submit by defining some null filters. same name as the other table, a method argument, pointing at a method that does nothing at all. Something like
class DashboardIncomeFilter(django_filters.FilterSet):
start_date = DateFilter(field_name = "invoice_date", lookup_expr='gte', l abel='Start Date')
end_date = DateFilter(field_name = "invoice_date", lookup_expr = 'lte', label = 'End Date')
# no-op filters
exp_start_date = DateFilter(field_name = "expense_date",
method = no_op, widget=forms.HiddenInput, label='Start Date') # label not needed?
exp_end_date = DateFilter(field_name = "expense_date",
method = no_op, widget=forms.HiddenInput, label = 'End Date')
class Meta:
model = Invoice
fields = '__all__'
exclude = ['invoice_slug', 'therapist', 'invoice_date', 'service', 'customer', 'invoice_no', 'price', 'quantity', 'total', 'payment', 'balance']
def no_op( self, qs, name, value):
return qs
Similarly but "mirror imaged" for the other table.
widget=forms.HiddenInput ought to make these fields invisible to the users. See Django forms docymentation and this answer.
Let us know if it works.
In this case, since the filter fields are identical, it might also work if you give the filters for both tables identical names, so the same filter is applied to both tables. Of course, that's assuming you do want to apply the same dates to both tables.
i had been trying to solve this problem for almost 3 hrs but i didnt get the result i want,
this is the result i want
this is my current result
this is my html
<table id="blacklistgrid" border="2px">
<tr>
<th>Students Name</th>
{% for student in teacherStudents %}<th >{{student.Date}}</th>{% endfor %}
<th data-id='headers' id='headerave'>Average</th>
</tr>
<tr>
<tbody id="scoreboard">
{% for students in studentname %}
<tr class="tr2">
<td><input type="text" name="students" value="{{student.id}}" id="student" hidden>{{students.Students_Enrollment_Records.Students_Enrollment_Records.Student_Users}}</td>
<tr>
{% endfor %}
</tr>
<tr>
{% for studentss in Students %}
<td class="td" scope="row"><input type="text" name="students" value="{{student.id}}" id="student" hidden>{{studentss.Grade}}</td>{% endfor %}
<td data-id='row' id="ans"><input type='number' class='averages' step="any" name="average" readonly/></td>
</tr>
</tbody>
</table>
this is my views.py
teacherStudents = studentsEnrolledSubjectsGrade.objects.filter(Teacher = teacher).filter(grading_Period = period).filter(Subjects = subject).filter(Grading_Categories = category).filter(GradeLevel = grade).distinct('Date')
studentname = studentsEnrolledSubjectsGrade.objects.filter(Teacher = teacher).filter(grading_Period = period).filter(Subjects = subject).filter(Grading_Categories = category).filter(GradeLevel = grade).distinct('Students_Enrollment_Records')
Students = studentsEnrolledSubjectsGrade.objects.filter(Teacher = teacher).filter(grading_Period = period).filter(Subjects = subject).filter(Grading_Categories = category).filter(GradeLevel = grade)
return render(request, 'Homepage/period.html',{"teacherStudents":teacherStudents,"Students":Students,"studentname":studentname})
my models.py
class studentsEnrolledSubjectsGrade(models.Model):
Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE,
null=True,blank=True)
GradeLevel = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,
null=True,blank=True)
Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True)
Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+',
on_delete=models.CASCADE, null=True)
Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE,
null=True,blank=True)
grading_Period = models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE,
null=True,blank=True)
#Items = models.IntegerField(blank=True, null=True)
Date = models.DateField(null=True, blank=True)
Grade = models.FloatField(null=True, blank=True)
this is my data in admin.py
can you guys help me in my html loop? do you have suggestions? my database is postgresql
UPDATE just like mr #Chris said in the comment section, I want to create a table with a row per student and in the columns the grades at a specific date, Create the table in your view (e.g. as a list of lists or one annotated queryset) and use the template for rendering but i dont know how, please help me guys,
I would suggest generating the table in your view and the pass it to your template for rendering.
#views.py
def your_view(request):
students = StudentsEnrolledSubjectsGrade.objects.filter(put_in_your_filters).order_by('student_name', 'date').values('student_name', 'date', 'grade')
dates = list(students.values_list('date', flat=True).distinct().order_by('date'))
# table basics
table = []
student_name = None
table_row = None
columns = len(dates) + 1
# table header
table_header = ['Student Name']
table_header.extend(dates)
table.append(table_header)
for student in students:
if not student['student_name'] == student_name:
if not table_row is None:
table.append(table_row)
table_row = [None for d in range(columns)]
student_name = student['student_name']
table_row[0] = student_name
table_row[dates.index(student['date']) + 1] = student['grade']
table.append(table_row)
return render(request, 'my_template.html', {'table': table})
Then you can interate through all the rows of that table in you template:
<table id="blacklistgrid" border="2px">
<tr>
{% for v in table.0 %}
<td>{{ v }}</td>
{% endfor %}
</tr>
<tbody>
{% for row in table|slice:"1:" %}
<tr>
<td>{{ row.0 }}</td>
{% for c in row|slice:"1:" %}
<td>{{ c }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
You need to adapt that to your needs, it is just to give you an idea
I am creating a timesheet application. I want to display timesheet on a weekly basis, which I am able to do.
I have create previous and next week button.
what approach should I use, so that when someone clicks on previous week, it shows timsheet for previous week and same for next week.
note - I have a timesheet table that contains one entry per day for time entry.
models.py --
class TimeRecords(models.Model):
emp_id = models.IntegerField(verbose_name = 'Employee ID')
ts_date = models.DateField(null=False, blank=False,verbose_name = 'Time Sheet Date')
ts_effort = models.PositiveIntegerField(default=8,verbose_name = 'Hours worked')
ts_desc = models.CharField(max_length=200,verbose_name = 'Time Description')
class Meta:
verbose_name = 'Time Records'
verbose_name_plural = 'Time Records'
unique_together = (("emp_id", "ts_date"),)
ordering = ["-emp_id"]
def __str__(self):
return self.ts_desc
forms.py ---
class CreateTimeSheetForm(forms.ModelForm):
emp_id = forms.IntegerField(widget=forms.HiddenInput(), initial=123)
class Meta:
model = TimeRecords
fields = '__all__'
labels = {
"ts_desc": "Task Description"
}
widgets = {
'ts_date': forms.TextInput(attrs={'readonly': True}),
}
views.py ---
def dateEnds():
date=datetime.date.today()
year, week, dow = date.isocalendar()
if dow == 1:
start_date = date
else:
start_date = date - timedelta(dow)
end_date = start_date + datetime.timedelta(days=7)
return start_date ,end_date
def daterange():
start_date, end_date=dateEnds()
for n in range(int((end_date - start_date).days)):
yield start_date + timedelta(n)
def timeEntryList(request):
start_date, end_date=dateEnds()
time_records=TimeRecords.objects.filter(emp_id=emp_id,ts_date__range=
(start_date, end_date))
context = {'time_records': time_records}
return render(request, 'timesheets/list.html', context)
list.html --
<tr> <th > Date</th> <th> Efforts</th> <th> Description</th> <th> Action</th> </tr>
{% for time_record in time_records %}
<tr>
<td >{{ time_record.ts_date|date:"SHORT_DATE_FORMAT" }}</td>
<td>{{ time_record.ts_effort }}</td>
<td>{{ time_record.ts_desc }}</td>
<td >Edit Delete</td>
</tr>
{% endfor %}
</table>
<a href="/timesheets/view" ><button type="button" class="btn" >Previous Week</button></a>
This is how I would approach this problem.
In models.py,
class TimeRecord(models.Model):
ts_date = models.DateTimeField()
# Other fields
def get_week(self):
return self.ts_date.isocalendar()[1]
In the views.py I would use list comprehensions to get time records for previous week and next week.
from django.utils import timezone
def my_view(request):
context = dict()
time_records = TimeRecord.objects.all()
current_week = timezone.now().isocalendar()[1]
current_records = [time_record for time_record in time_records if time_record.get_week() == current_week]
if request.method == 'POST':
week = request.POST['week']
if week == 'next-week':
current_records = [time_record for time_record in time_records if
time_record.get_week() == current_week + 1]
if week == 'last-week':
current_records = [time_record for time_record in time_records if
time_record.get_week() == current_week - 1]
context['current_records'] = current_records
return render(request, 'my.html', context)
Finally in the templates I would used hidden form inputs for next week and previous week.
<div>
{% for record in current_records %}
<p># {{ forloop.counter }} {{ record.ts_date }}</p>
{% endfor %}
<form action="" method="post">
{% csrf_token %}
<input type="hidden" name="week" value="next-week">
<button type="submit">next week</button>
</form>
<form action="" method="post">
{% csrf_token %}
<input type="hidden" name="week" value="last-week">
<button type="submit">last week</button>
</form>
</div>
Following the suggestions from my last post I got this far:
Post model:
class Post(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
Group model:
class Group(models.Model):
title = models.CharField(max_length=200)
url = models.URLField(unique=True)
contact_updated = models.DateField(auto_now=False, auto_now_add=True)
group_status = models.CharField(max_length=20)
admin = models.CharField(max_length=20)
admin_status = models.CharField(max_length=20)
frequency = models.IntegerField() # allowed post frequency
frq_scale = models.CharField(max_length=20, blank=True)
obs = models.TextField(blank=True)
posts = models.ManyToManyField(Post, through='control.Control')
Control model:
class Control(models.Model):
published = models.DateField(auto_now=False, auto_now_add=False)
post = models.ForeignKey('posts.Post', on_delete=models.CASCADE)
group = models.ForeignKey('groups.Group', on_delete=models.CASCADE)
This is control for posts in groups. I can have 1 post published in many groups controlled from Control model.
CORRECTION:
It is possible for a Post to be published in many groups.
How can I produce the table (link above) with those models? Or perhaps there is something I need to change?
The table I want to produce
class Control(models.Model):
published = models.DateField(auto_now=False, auto_now_add=False)
post = models.ForeignKey('posts.Post', on_delete=models.CASCADE)
group = models.ForeignKey('groups.Group', on_delete=models.CASCADE)
class Meta:
unique_together = (post, group )
I ended up creating a dictionary in the view to be passed to the template.
I haven't changed the models.
This is the view:
def control_list(request):
group_status = STATUS_LIST
group_query_idx = 1
period_initial = date.today()-timedelta(days=30)
period_final = date.today()
if request.method == "POST":
filter_form = FilterControl(request.POST)
if filter_form.is_valid():
group_query_idx = int(filter_form.cleaned_data['group_status'])
period_initial = filter_form.cleaned_data['period_initial']
period_final = filter_form.cleaned_data['period_final']
else:
filter_form = FilterControl()
if group_query_idx:
filtered_groups = Group.objects.filter_by_status(group_status[group_query_idx])
queryset_list = Control.objects.filter_by_group_status(group_status[group_query_idx])\
.filter(published__range=[period_initial, period_final])
query = request.GET.get("q")
if query:
queryset_list = queryset_list.filter(
Q(post__content__icontains=query) |
Q(post__title__icontains=query) |
Q(group__title__icontains=query) |
Q(group__admin__icontains=query) |
Q(group__obs__icontains=query)
).distinct() # avoid duplicated items
controls_per_group = {}
for group in filtered_groups:
control = queryset_list.filter(group_id=group.id)
controls_per_group[group.title] = control
context = {
"object_list": queryset,
"title": "Control",
"controls_per_group": controls_per_group,
"column": range(10),
"group_status": group_status,
"filter_form": filter_form,
}
return render(request, "control_list.html", context)
And this is the template:
<table class="table table-hover table-striped">
<thead class="thead-inverse">
<tr>
<th class="text-center">Action</th>
<th class="text-center">Group</th>
{% for value in column %}
<th class="text-center">#</th>
{% endfor %}
</tr>
</thead>
{% for key, value in controls_per_group.items %}
<tr>
<td class="text-center"><a class='btn btn-info btn-xs disabled' href="#"><i class="fa fa-pencil"></i></a>
<i class="fa fa-trash-o"></i></td>
<th class="text-center">{{ key }}</th>
{% for control in value %}
<th class="text-center">{{ control.published | date:"d/m/y" }}<br>{{ control.post.id }}</th>
{% endfor %}
</tr>
{% endfor %}
Models.py
class ZoneDetail(models.Model):
zone_id = models.IntegerField(primary_key=True )
zone_name = models.CharField(max_length = 20 )
def __str__(self):
return self.zone_name
class StateDetail(models.Model):
zoneId = models.ForeignKey(ZoneDetail)
state_name = models.CharField(max_length = 20 , choices = STATE_CODE )
def __str__(self):
return self.id
class Transaction(models.Model):
zone = models.ForeignKey(ZoneDetail)
state = models.ForeignKey(StateDetail)
def __str__(self):
return self.vechile_number
Transaction model will store the data on form submission.
forms.py
class TransactionForm(forms.ModelForm):
zone = forms.ModelChoiceField(queryset = ZoneDetail.objects.all(), empty_label = "-- Select Zone --")
state_name = forms.ModelChoiceField(queryset = StateDetail.objects.none())
class Meta:
model = Transaction
fields = ['zone','state_name']
HTML
<form method="POST" action = "." >{% csrf_token %}
<table border = "0" align="left" margin: "5" >
<tr>
<td style="font-size: 15px; border-bottom: 0px " > {{ form.zone.label_tag }}{{ form.zone }} </td>
</tr>
<tr>
<td style="font-size: 15px; border-bottom: 0px "> {{ form.state_name.label_tag }}{{ form.state_name }}</td>
</tr>
<input value="Save" title="Save" type="submit" id="btn_save">
</table>
</form>
Form Submission giving me the error as : Select a valid choice. That choice is not one of the available choices