I want to have template page with object(orders) list (another list, for another user). Like relations one to many. Where do i need to define that objects(order)(for exemple by id: order_id=1 and order_id=3) is assigned to user(driver) with id=1 etc?
I was trying to create Driver class and than set atribute driver in order Class like this.
form.py
class OrderForm(forms.Form):
telephone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'.")
airport = forms.ChoiceField(choices=AIRPORT_CHOICES) ### Jeśli lotnisko jest celem podróży
direction = forms.ChoiceField(choices=DIRECTION_CHOICES) ## to pick_up < plane i odwrotnie!!!
adress = forms.CharField()
client = forms.CharField()
telephone = forms.CharField(validators=[telephone_regex])
flight_number = forms.CharField()
plane = forms.DateTimeField(input_formats=['%Y-%m-%d'])
pick_up = forms.DateTimeField(input_formats=['%Y-%m-%d'])
gate = forms.CharField()
company = forms.ChoiceField(choices=COMPANY_CHOICES)
driver = forms.ChoiceField(choices=DRIVER_CHOICES)
models.py
class Driver(models.Model):
name = models.CharField(max_length=30)
tel = models.CharField(max_length=17)
class Order(models.Model):
telephone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format:
'+999999999'.")
airport = models.CharField(max_length=10, choices=AIRPORT_CHOICES)
direction = models.CharField(max_length=7, choices=DIRECTION_CHOICES)
adress = models.CharField(max_length=100, null=False, blank=False)
client = models.CharField(max_length=50, null=False, blank=False)
telephone = models.CharField(validators=[telephone_regex], max_length=17, blank=False)
flight_number = models.CharField(max_length=7)
plane = models.DateTimeField(null=True)
pick_up = models.DateTimeField(null=True)
gate = models.CharField(max_length=10, null=True, blank=True)
comapny = models.CharField(max_length=50, choices=COMPANY_CHOICES)
driver = models.ForeignKey(Driver, on_delete=models.CASCADE)
order_list.html
{% extends "base.html" %}
{% block content %}
{% if user.is_authenticated %}
<h1>Hi {{ user.username }}! Have a good tips!</h1>
{% else %}
<h1>You have to login to see your orders list</h1>
{% endif %}
<table class="table table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">client</th>
<th scope="col">telephone</th>
<th scope="col">flight number</th>
<th scope="col">airport</th>
<th scope="col">direction</th>
<th scope="col">adress</th>
<th scope="col">gate</th>
<th scope="col">plane</th>
<th scope="col">pick up</th>
</tr>
</thead>
{% for order in orders %}
<tbody>
<tr>
<th scope="row">{{ order.id }}</th>
<td>{{ order.client }}</td>
<td>{{ order.telephone }}</td>
<td>{{ order.flight_number }}</td>
<td>{{ order.airport }}</td>
<td>{{ order.direction }}</td>
<td>{{ order.adress }}</td>
<td>{{ order.gate }}</td>
<td>{{ order.plane }}</td>
<td>{{ order.pick_up }}</td>
<td>{{ order.driver }}</td>
</tr>
</tbody>
{% endfor %}
</table>
{% endblock %}
views.py
class OrderView(View):
def get(self, request, id):
orders = Order.objects.get(id=id)
users = User.object.get(id=id)
ctx = {
'orders': orders,
'users': users
}
return render(request, 'order.html', ctx)
class OrderListView(View):
def get(self, request):
form = OrderForm()
orders = Order.objects.all()
ctx = {'form': form, 'orders': orders}
return render(request, 'orders/order_list.html', ctx)
class AddOrderView(View):
def get(self, request):
form = OrderForm()
return render(request, 'orders/add_order.html', {'form': form})
def post(self, request, *args, **kwargs):
form = OrderForm(request.POST)
if form.is_valid():
order = Order.objects.create(airport=form.cleaned_data['airport'],
direction=form.cleaned_data['direction'],
adress=form.cleaned_data['adress'],
client=form.cleaned_data['client'],
telephone=form.cleaned_data['telephone'],
flight_number=form.cleaned_data['flight_number'],
plane=form.cleaned_data['plane'],
pick_up=form.cleaned_data['pick_up'],
gate=form.cleaned_data['gate'],
driver=form.cleaned_data['driver'])
return render(request, 'orders/add_order.html', {'form': form})
I expect to get form when i can input new order and select driver but I'm geting this:
http://dpaste.com/0PD363H
Related
I'm having trouble displaying data from current user. It shows all the shifts that was given to other users also. I don't have any idea how to do this. Below is my code.
models.py
class User(models.Model):
user_name = models.CharField(max_length=32, unique=True)
pass_word = models.CharField(max_length=150)
is_active = models.BooleanField(default=True)
class Rostering(models.Model):
name = models.CharField(max_length=64)
begin_time = models.TimeField(default="")
end_time = models.TimeField(default="")
is_active = models.BooleanField(default=True)
class RosteringUser(models.Model):
rostering_user = models.ForeignKey(Rostering, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
views.py
def my_shift(request):
if request.method == 'GET':
queryset = RosteringUser.objects.all()
if queryset:
for obj in queryset:
id = Rostering.objects.get(rosteringuser=obj.id)
obj.id = id
return render(request, 'my_shift.html', {'queryset': queryset})
my_shift.html
{% for obj in queryset %}
<tr>
<td>{{ obj.user.user_name }}</td>
<td>{{ obj.id.name }}-{{ obj.id.begin_time }}</td>
<td>{{ obj.id.name }}-{{ obj.id.end_time }}</td>
</tr>
{% endfor %}
Thank you in advance!
Simply you can try like this:
if queryset:
for obj in queryset:
id = Rostering.objects.get(rosteringuser=obj.id)
obj.id = id
querysets = obj
return render(request, 'my_shift.html', {'querysets': querysets})
And in templates:
{% for object in querysets %}
<tr>
<td>{{ object.user.user_name }}</td>
<td>{{ object.id.name }}-{{ object.id.begin_time }}</td>
<td>{{ object.id.name }}-{{ object.id.end_time }}</td>
</tr>
{% endfor %}
def my_shift(request):
if request.method == 'GET':
rost_id = RosteringUser.objects.filter(user_id=request.user.id).values("rostering_user_id").first()
if rost_id :
data = Rostering.objects.get(id=rost_id['rostering_user_id'])
return render(request, 'my_shift.html', {'queryset': data })
in template you can directly display logged in username {{ request.user.first_name }}
I am learning Django, and started creating a web app, and trying to use django_filters with django_tables2, to filter on the columns in the table. What I am tyrying to change is the default 'exact' lookup method, according to the django_filters instructions. This is the example they show at FilterSet Options
class UserFilter(django_filters.FilterSet):
class Meta:
model = User
fields = {
'username': ['exact', 'contains'],
'last_login': ['exact', 'year__gt'],
}
What happens is that if I don't include 'exact' in the list of lookups (like for the shop__shop field below), the field is not rendered on the page.
class ReceiptFilter(django_filters.FilterSet):
class Meta:
model = expenses
fields = {
'purchase_date': ['exact'],
'shop__shop': ['iexact'],
'payment_method__payment_method': ['exact'],
}
Please, click here to see the web page rendered
If I leave 'exact' in front of the lookup I want to add (as in the instructions), it doesn't seem to have any effect, the filter works like it was an 'exact' lookup.
What am I doing wrong?
Thanks,
Miki.
P.S. Let me add some more code here.
models:
class shops(models.Model):
shop = models.CharField(max_length=50,null=True)
address = models.CharField(max_length=100,null=True)
shop_type = models.CharField(max_length=50,null=True)
phone = models.CharField(max_length=50,null=True)
def __str__(self):
return self.shop
class Meta:
verbose_name = "Shop"
class expenses(models.Model):
item = models.ForeignKey(items, on_delete=models.CASCADE)
shop = models.ForeignKey(shops, on_delete=models.CASCADE)
owner = models.ForeignKey(owners, on_delete=models.CASCADE)
currency = models.ForeignKey(currencies, on_delete=models.CASCADE)
payment_method = models.ForeignKey(payment_methods, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10,decimal_places=2)
amount = models.DecimalField(max_digits=10,decimal_places=3)
purchase_date = models.DateField()
entry_time = models.DateTimeField(null=True)
exclude_from_reports = models.BooleanField(null=True)
transferred = models.BooleanField(null=True)
def __str__(self):
return str(self.amount) + ' ' + self.item.unit + ' of ' + self.item.item
class Meta:
verbose_name = "Expense"
table:
class ReceiptsTable(tables.Table):
class Meta:
model = expenses
template_name = "django_tables2/bootstrap.html"
fields = ('purchase_date','shop__shop','payment_method__payment_method','currency__currency_short','total')
view:
def receipts(request):
receipt_list=expenses.objects.values('purchase_date','shop__shop','payment_method__payment_method','currency__currency_short').annotate(total=Sum('price')).order_by('-purchase_date')
filter = ReceiptFilter(request.GET, queryset=receipt_list)
return render(request, 'household/receipts.html', {'filter':filter})
template:
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'household/style.css' %}">
{# <a href='/household/add_expense'>Add Expense</a> #}
{% block content %}
<table>
<caption>Receipts</caption>
<thead>
<tr>
<th>Date</th>
<th>Shop</th>
<th>Payment Method</th>
<th>Total</th>
</tr>
</thead>
<thead>
<form method='get'>
<tr>
<th>{{ filter.form.purchase_date }}</th>
<th>{{ filter.form.shop__shop }}</th>
<th>{{ filter.form.payment_method__payment_method }}</th>
<th><input type='submit' value='Filter'/></th>
</tr>
</form>
</thead>
<tbody>
{% for obj in filter.qs %}
<tr>
<td>{{ obj.purchase_date }}</td>
<td>{{ obj.shop__shop }}</td>
<td>{{ obj.payment_method__payment_method }}</td>
<td>{{ obj.currency__currency_short }} {{ obj.total }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
I'm new to django-python so I need extra details. All I need is to provide monthly report in a pdf form and a yearly report that also in pdf form.
From my model.py
class Case(models.Model):
case_number = models.CharField(max_length=50, blank=True, null=True, unique=True)
reference_choice = (
('Personal', 'Personal'),
('Court', 'Court'),
)
reference = models.CharField(max_length=20, choices=reference_choice, null=True)
date_of_filing = models.DateField('Date of Filing (mm/dd/yyyy)*', blank=True, null=True)
official_receipt = models.CharField(max_length=50, blank=True, null=True,)
complainant = models.CharField(max_length=150)
respondent = models.CharField(max_length=150)
case_title = models.CharField(max_length=200)
On my views.py
class GeneratePDF(View):
model = Case
def get(self, request, *args, **kwargs):
cases = Case.objects.filter.all()
context = {
'date': date,
'cases': cases,
}
pdf = render_to_pdf('pdf/monthly_report.html', context)
if pdf:
response = HttpResponse(pdf, content_type='application/pdf')
filename = 'monthly_report_%s.pdf' %('month')
content = 'inline; filename="%s"' % (filename)
response['Content-Disposition'] = content
return response
return HttpResponse('Not Found')
and on my monthly_report.html
<div class="container mt-4">
<table class="table-" style="width:1200px">
<thead class="thead-light">
<tr>
<th scope="col">Case Number</th>
<th scope="col">Complainant</th>
<th scope="col">Respondent</th>
<th scope="col">Case Title</th>
<th scope="col">Action Taken</th>
<th scope="col">Remarks</th>
</tr>
</thead>
<tbody>
{% for case in cases %}
<tr>
<td>{{ case.case_number }}</td>
<td>{{ case.complainant }}</td>
<td>{{ case.respondent }}</td>
<td>{{ case.case_title }}</td>
<td>{{ case.mediated| yesno }}</td>
<td>{{ case.remarks }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
On my code I only get all the data but it is not filtered.
so you should change your query to the correct filter.for example you can do this
cases=Case.objects.all().filter(date_of_filing = sometime)
on the line Case.objects.filter.all() you can filter your results. however it does not seem like you are doing that?
an example:
from django.utils import timzeone
Case.objects.filter(date__gte=timezone.now()-timezone.timedelta(days=1))
I am trying to show a detailed view of the contacts stored in a phonebook. The PhoneBook(id, name) is one of my models which is a foreign key to model Contact(id, first_name, last_name, phone_number, phone_book).
In my index page, there is a button which opens the phone book. After that, I want it such that the user may click on a phone book and the detailed view(first_name, last_name, phone_number) would be shown to them.
In view.py, I have a function which captures all the phonebook, passes it through context(dict). In my template, I have used a for loop to go through all the phonebooks and print them.
I am unable to direct the page to a detailed view. How do I get the phonebook the user clicked on? And how to direct the page from ./view to ./detail
# view.py
def view_phone_book(request):
all_phone_books = PhoneBook.objects.all()
context = {
'all_phone_books': all_phone_books
}
return render(request, "CallCenter/view_phone_book.html", context)
def detailed_view_phone_book(request):
all_contacts = Contact.objects.all().filter(phone_book=phone_book_user_clicked_on)
context = {
'all_contacts': all_contacts
}
return render(request, "CallCenter/detailed_view_phone_book.html", context)
# urls.py
urlpatterns = [
path('', index, name="index"),
path('create/', create_phone_book, name="create"),
path('add/', add_to_phone_book, name="add"),
path('view/', view_phone_book, name="view"),
path('detail/', detailed_view_phone_book, name="detailed_view")
]
# models.py
class PhoneBook(models.Model):
"""
Model to store customer to a phone book
"""
name = models.CharField(max_length=10, blank=False)
def __str__(self):
return self.name
class Contact(models.Model):
"""
Model to store customer to a phone book.
"""
first_name = models.CharField(max_length=50, blank=False)
last_name = models.CharField(max_length=50, blank=False)
phone_number = models.CharField(max_length=13, blank=False, unique=True)
phone_book = models.ForeignKey(PhoneBook, on_delete=models.CASCADE)
def __str__(self):
return self.phone_number
<!--view_phone_book.html-->
<table>
<tr>
<th>Phone Book</th>
</tr>
{% for phone_book in all_phone_books %}
<tr>
<form method="get" action="../detail/"><td>{{ phone_book }} </td></form>
</tr>
{% endfor %}
</table>
<!--detailed_view_phone_book.html-->
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone Number</th>
</tr>
{% for phone_detail in all_phone_detail %}
<tr>
<form>
<td>{{ phone_detail.first_name }}</td>
<td>{{ phone_detail.last_name }}</td>
<td>{{ phone_detail.phone_number }}</td>
</form>
</tr>
{% endfor %}
</table>
I am unable to go from ./view to ./detail. Also, how would I know which phone book the user clicked on?
I figured it out on how to make it work, and I'm answering it so that if anyone gets stuck in, it can help themselves.
# views.py
def view_phone_book(request):
all_phone_books = PhoneBook.objects.all()
context = {
'all_phone_books': all_phone_books
}
return render(request, "CallCenter/view_phone_book.html", context)
def detailed_view_phone_book(request, phone_book_id):
try:
all_contacts = Contact.objects.filter(pk=phone_book_id)
except Contact.DoesNotExist:
raise Http404("PhoneBook Does Not Exist!")
context = {
'all_contacts': all_contacts
}
return render(request, "CallCenter/detailed_view_phone_book.html", context)
#urls.py
urlpatterns = [
path('', index, name="index"),
path('create/', create_phone_book, name="create"),
path('add/', add_to_phone_book, name="add"),
path('campaign/', create_campaign, name="create-campaign"),
path('view/', view_phone_book, name="view-phone-book"),
path('detail/<int:phone_book_id>', detailed_view_phone_book, name="detail-view-phone-book"),
<!--view_phone_book.html-->
<body>
{% for phone_book in all_phone_books%}
{{ phone_book }}
<br>
{% endfor %}
Back To Home
</body>
<!--detailed_view_phone_book.html-->
{% if all_contacts %}
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone Number</th>
</tr>
{% for contact in all_contacts %}
<tr>
<form>
<td>{{ contact.first_name }}</td>
<td>{{ contact.last_name }}</td>
<td>{{ contact.phone_number }}</td>
</form>
</tr>
{% endfor %}
</table>
{% endif %}
Back To Home
I watched the Brain's CS50 video, which helped me. I'll suggest you do the same. He explains the concepts in a beginner-friendly way.
I have a problem showing fields from another table, where two tables have relationships.
This is my first model:
class DataPribadiSiswa(models.Model):
SiswaID = models.AutoField(primary_key=True)
WaliKelasID = models.CharField(max_length=11, blank=True, null=True)
My second model:
class transaksi_kas(models.Model):
id_kas = models.AutoField(primary_key=True)
siswaID_trans = models.ForeignKey(DataPribadiSiswa, null=True, blank=True)
kelas = models.CharField(max_length=1, null=True, blank=True)
This is my views.py:
def transaksi_index(request):
transaksi = {}
transaksi['transaksikas'] = transaksi_kas.objects.select_related('siswaID_trans')
return render(request, 'kastransaksi/transaksi_index.html', transaksi)
This is the template:
<table id="simple-table" class="table table-striped table-bordered table-hover">
<tr>
<th>No.</th>
<th>Nama</th>
<th>Wali Murid</th>
<th>Kelas</th>
</tr>
{% for kas in transaksikas%}
<tr>
<td>{{ forloop.counter }}</td>
<th>{{ kas.siswaID_trans }}</th>
<td>{{ kas.WaliKelasID }}</td>
<td>{{ kas.kelas }}</td>
</tr>
{% endfor %}
</table>
How do I show {{ kas.WaliKelasID }} from DataPribadiSiswa?
I think you mean to do the following
{{ kas.siswaID_trans.WaliKelasID }}
transaksi['transaksikas'] = transaksi_kas.objects.select_related('siswaID_trans') after this you have to make query get or filter or other.
Example:
transaksi['transaksikas'] = transaksi_kas.objects.select_related('siswaID_trans').get(id=id)
or
transaksi['transaksikas'] = transaksi_kas.objects.select_related('siswaID_trans').filter(your query)
this is link