class MyForm(forms.Form):
row_1 = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
row_2_col_1 = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
row_2_col_2 = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)
def render_form(request):
form = MyForm()
# render form
What should be my template so that final html is something like
<table>
<tr> row_1 field.. </tr>
<tr>
<td> row_2_col_1 field.. </td>
<td> row_2_col_2 field.. </td>
</tr>
If you've passed the table to the form in the request you just need to use Django template mark up:
<table>
<tr>{{ table.row_1 }}</tr>
<tr>
<td>{{ table.row_2_col_1 }}</td>
<td>{{ table.row_2_col_2 }}</td>
</tr>
Related
I want to display all the users, in my template but I i received this error.
TypeError at /list/
init() takes 1 positional argument but 2 were given
views.py
class UsersView(TemplateView):
template_name = 'list.html'
context = super(UsersView, self).get_context_data(**kwargs)
context['object_list'] = User.objects.values()
list.html
<tbody>
<tr>
<th scope="col">Id</th>
<th scope="col">username</th>
<th scope="col">email Adress</th>
<th scope="col">First Name </th>
<th scope="col">Last Name</th>
</tr>
</thead>
<tbody>
{% for user in users %}
<tr>
<td>{{ user.id }} </td>
<td>{{ user.username}}</td>
<td>{{ user.email }}</td>
<td>{{ user.first_name}}</td>
<td>{{ user.last_name }}</td>
How could you pull all users?
There is no self nor context, etc. in a class. You should override the .get_context_data(…) method [Django-doc]:
class UsersView(TemplateView):
template_name = 'list.html'
def get_context_data(self, *args, **kwargs):
context = super(UsersView, self).get_context_data(*args, **kwargs)
context['object_list'] = User.objects.all()
return context
You named your template variable ojbect_list, so you should iterate over object_list, not users:
{% for user in object_list %}
<tr>
<td>{{ user.id }} </td>
<td>{{ user.username}}</td>
<td>{{ user.email }}</td>
<td>{{ user.first_name}}</td>
<td>{{ user.last_name }}</td>
</tr>
{% endfor %}
It might however make more sense to use a ListView [Django-doc] instead:
from django.views.generic.list import ListView
class UsersView(ListView):
template_name = 'list.html'
model = User
I have a model called ItemBatch
# item upload
class ItemBatch(models.Model):
ttypes =(('Open','Open'),('Container','Container'),('Trailer','Trailer'),('All','All'))
uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='uploaded_by')
name = models.CharField(max_length=30)
pid = models.IntegerField(blank=True)
quantity = models.IntegerField(blank=True)
length = models.FloatField(blank=True)
width = models.FloatField(blank=True)
height = models.FloatField(blank=True)
volume = models.FloatField(blank=True)
weight = models.FloatField(blank=True)
truck_type = models.CharField(max_length=255,default=0, choices=ttypes)
origin = models.CharField(max_length=100, blank=True)
destination = models.CharField(max_length=100, blank=True)
time = models.DateTimeField(max_length=100, blank=True,default=now)
rtd = models.BooleanField(default=False) #ready to dispatch checkbox
def __str__ (self):
return self.name
And I am using this views function to render it:
#method_decorator([login_required, teacher_required], name='dispatch')
class UploadedItems(ListView):
model = ItemBatch
ordering = ('name',)
context_object_name = 'items'
template_name = 'classroom/teachers/item_list.html'
def get_queryset (self):
return ItemBatch.objects.filter(uploaded_by=self.request.user)
I am rendering this table in a template and getting this:
This is the code in the template:
{% for quiz in last %}
<tr>
<form method="post" novalidate>
{% csrf_token %}
<td class="align-middle"><input type="checkbox" value="{{ quiz.pid }}"></td>
<td class="align-middle">{{ quiz.name }}</td>
<td class="align-middle">{{ quiz.pid }}</td>
<td class="align-middle">{{ quiz.quantity }}</td>
<td class="align-middle">{{ quiz.length }}x{{ quiz.width }}x{{ quiz.height }}</td>
<td class="align-middle">{{ quiz.volume }}/{{ quiz.weight }}</td>
<td class="align-middle">{{ quiz.origin }}</td>
<td class="align-middle">{{ quiz.destination }}</td>
<td class="align-middle">{{ quiz.time|naturaltime }}</td>
</form>
</tr>
{% empty %}
What I tried
As you can see, I have created a form inside the table and also included a checkbox. But, I am not able to take the output of the that checkbox in any way. How can I let the user select a few items, and get that data returned to me in any way so I can use it another function ? If the checkbox can just give me the id or pk value, I will be able to reverse it with the appropriate object, but I can't create an input form on a table which already is an output render of another function. Is this the correct way ?
You could add a submit button at the end of your form, and inside the form tag specify the action and map it to a django view.
Also, you need to moove out your form tags outside of the for loop.
Should look like this:
<form method="post" action="{% url 'your_url_name'%}" novalidate>
{% csrf_token %}
{% for quiz in last %}
<tr>
<td class="align-middle"><input name='quiz-pids' id='checkbox-{{forloop.counter}}' type="checkbox" value="{{ quiz.pid }}"></td>
<td class="align-middle">{{ quiz.name }}</td>
<td class="align-middle">{{ quiz.pid }}</td>
<td class="align-middle">{{ quiz.quantity }}</td>
<td class="align-middle">{{ quiz.length }}x{{ quiz.width }}x{{ quiz.height }}</td>
<td class="align-middle">{{ quiz.volume }}/{{ quiz.weight }}</td>
<td class="align-middle">{{ quiz.origin }}</td>
<td class="align-middle">{{ quiz.destination }}</td>
<td class="align-middle">{{ quiz.time|naturaltime }}</td>
</tr>
{% endfor %}
<input type="submit" value='Do something'>
</form>
In you urls add to path:
path('your-url', views.YourView.as_view(), name='your_url_name'),
Your View:
class YourView(View):
def post(self, request, *args, **kwargs):
#get the selected quizs
quizs = request.POST.getlist('quiz-pids')
#retrieves thoses quizes from the database:
items = ItemBatch.objects.filter(pid__in=quizs)
#do something with each of them:
for item_batch in items:
#do something
pass
There are two things wrong here.
Firstly you need a single form around all of the options, not one form per row.
And secondly you need a name attribute in your input element, so that the browser knows how to send it to the backend.
<form method="post" novalidate>
{% csrf_token %}
{% for quiz in last %}
<tr>
<td class="align-middle"><input type="checkbox" name="pids" value="{{ quiz.pid }}"></td>
...
</tr>
{% endfor %}
<input type="submit">
</form>
Now in your view you can get the submitted values via self.request.POST.getlist('pids') - for instance, you could use that to filter the queryset via ItemBatch.objects.filter(pid__in=self.request.POST.getlist('pids')).
I am new in Django.
I want to update the value in the database based on the order id. Therefore, every order id has different updates. But, i only can update the last item that i add to the order. And every previous orders that i have, will directly follow the update from the last item.
models.py
class OrderItem(models.Model):
Table_No = models.IntegerField(blank=False)
FoodId = models.TextField()
Item = models.TextField()
Qty = models.DecimalField(max_digits=5, decimal_places=0)
Price = models.DecimalField(max_digits=10, decimal_places=2)
TotalPrice = models.TextField()
Note = models.TextField(max_length=100, null=True)
OrderId = models.TextField(max_length=5, null=True)
FoodStatus = (
('1', 'Has been ordered'),
('2', 'cooked'),
('3', 'ready to be served'),
('4', 'done'),
)
food_status = models.CharField(max_length=50, choices=FoodStatus)
views.py
def kitchen_view(request):
chef_view = OrderItem.objects.all()
if request.method == "POST":
order_id = request.POST.get("OrderId")
status = OrderItem.objects.filter(OrderId=request.POST.get("OrderId"))
status.status1 = OrderItem.objects.update(food_status=request.POST.get("food_status"))
return render(request, 'restaurants/kitchen_page.html', {'chef_view': chef_view})
kitchen_page.html
<form action="#" method="post">
<style>
table, th, td {
border: 1px solid black;
}
</style>
{% csrf_token %}
{% for order in chef_view %}
<table width="800">
<tr>
<th width="800">Table Number</th>
<th width="800">Item</th>
<th width="800">Quantity</th>
<th width="800">Price</th>
<th width="800">Note</th>
<th width="800">Order Id</th>
<th width="800">Status</th>
</tr>
<tr>
<td width="800">{{ order.Table_No }}</td>
<td width="800">{{ order.Item }}</td>
<td width="800">{{ order.Qty }}</td>
<td width="800">{{ order.Price }}</td>
<td width="800">{{ order.Note }}</td>
<td width="800">{{ order.OrderId }}</td>
<td width="800">{{ order.food_status }}
<input type="text" name="food_status">
</tr>
</table>
{% endfor %}
<br><a href='' button onclick="myFunction()"><input type="submit" value="Change Status"></button>
</form>
The result should be able to update the food_status based on the order_id. Therefore, every order_id may have different food_status and show it to the template.
Anyone can help me to solve this problem? I really need the help to solve this issue. Really appreciate.
Ok so real problem is that your form is incorrect - you are not sending OrderId to view. Here's quickfix to it:
kitchen_page.html:
<style>
table, th, td {
border: 1px solid black;
}
</style>
<form action="#" method="post">
<table width="800">
<tr>
<th width="800">Table Number</th>
<th width="800">Item</th>
<th width="800">Quantity</th>
<th width="800">Price</th>
<th width="800">Note</th>
<th width="800">Order Id</th>
<th width="800">Status</th>
</tr>
{% csrf_token %}
{% for order in chef_view %}
<tr>
<td width="800">{{ order.Table_No }}</td>
<td width="800">{{ order.Item }}</td>
<td width="800">{{ order.Qty }}</td>
<td width="800">{{ order.Price }}</td>
<td width="800">{{ order.Note }}</td>
<td width="800">{{ order.OrderId }}</td>
<td width="800">{{ order.food_status }}
<input type="text" name="food_status" value="{{ order.food_status }}">
</tr>
<input type="hidden" name="OrderId" value="{{ order.OrderId }}">
{% endfor %}
</table>
<br><button type="submit" value="Change Status">Change Status</button>
</form>
views.py:
def kitchen_view(request):
if request.method == "POST":
order_ids = request.POST.getlist("OrderId")
food_statuses = request.POST.getlist("food_status")
for i in range(len(order_ids)):
OrderItem.objects.filter(OrderId=order_ids[i]).update(food_status=food_statuses[i])
chef_view = OrderItem.objects.all()
return render(request, 'restaurants/kitchen_page.html', {'chef_view': chef_view})
Previously stored filtered objects are not being updated as you have
status = OrderItem.objects.filter(OrderId=request.POST.get("OrderId"))
but when you are updating them, you should be updating the already filtered objects like
status = status.update(food_status=request.POST.get("food_status"))
Hope this helps.
You can update multiple objects at once including the filter in a single line as:
status = OrderItem.objects.filter(OrderId=request.POST.get("OrderId")).update(food_status=request.POST.get("food_status"))
The problem in your code:
status.status1 = OrderItem.objects.update(food_status=request.POST.get("food_status"))
was that you were not using the filter, instead you tried updating the status1 field(Can't see a status1 field in your model) using status.status1.
I am trying to construct a user profile page for my project, hence I need to access to user Model's data like first_name and last_name. But for some reason I can access the username and email field but not the first_name and last_name. When I call these fields from my template, nothing displays.
<table class="table-responsive">
<tr>
<td>Username</td>
<td>{{ user.get_username }}</td>
</tr>
<tr>
<td>First Name</td>
<td>{{ user.first_name }}</td>
</tr>
<tr>
<td>Last Name</td>
<td>{{ user.last_name }}</td>
</tr>
<tr>
<td>Email</td>
<td>{{ user.email }}</td>
</tr>
</table>
My profile_view.py
def profile_view(request):
args = {'user' : request.user}
return render(request, 'user_account/profile.html', args)
I've tried using the functions like user.get_full_name but that doesn't work either.
thanking you in advance.
Have you tried this?
def profile_view(request, id):
user = User.objects.get(id=id)
args = {'user' : user}
return render(request, 'user_account/profile.html', args)
I have created a table with django forms in it. The forms do get data from the database, from two different models. Since this form has 42 fields consisting of 7 days and 6 shifts, i would love to save it as the table it is rendered. Is there any way to do this?
forms.py
class EditSchedule(forms.Form):
def __init__(self,*args,**kwargs):
super(EditSchedule, self).__init__(*args,**kwargs)
for k in range(1,8):
for i in range(1,7):
self.fields["S"+str(i)+"D"+str(k)] = forms.ChoiceField(choices=get_my_choices(i,k))
self.fields["S"+str(i)+"D"+str(k)].widget.attrs.update({"class":"form-control select2 select2-hidden-accessible"})
html file
<div class="box">
<form method="POST" action="">{% csrf_token %}
<div class="box-body">
<div class="table-container table-responsive">
<table class="table table-bordered table-hover dataTable" role="grid" >
<thead>
<tr>
<th class = "shicht"><h3>Schicht</h3></th>
<th class = "montag"><h3>Montag</h3></th>
<th class = "dienstag"><h3>Dienstag</h3></th>
<th class = "mittwoch"><h3>Mittwoch</h3></th>
<th class = "donnerstag"><h3>Donnerstag</h3></th>
<th class = "freitag"><h3>Freitag</h3></th>
<th class = "samstag"><h3>Samstag</h3></th>
<th class = "sonntag"><h3>Sonntag</h3></th>
</tr>
</thead>
<tbody>
<tr class="even">
<td class="shicht">Schicht 1</td>
<td class="montag">{{ form.S1D1 }}</td>
<td class="dienstag">{{ form.S1D2 }}</td>
<td class = "Mittwoch">{{ form.S1D3 }}</td>
<td class = "donnerstag">{{ form.S1D4 }}</td>
<td class = "freitag">{{ form.S1D5 }}</td>
<td class ="samstag">{{ form.S1D6 }}</td>
<td class ="sonntag">{{ form.S1D7 }}</td>
</tr>
<tr class="odd">
<td class="shicht">Schicht 2</td>
<td class="montag">{{ form.S2D1 }}</td>
<td class="dienstag">{{ form.S2D2 }}</td>
<td class = "Mittwoch">{{ form.S2D3 }}</td>
<td class = "donnerstag">{{ form.S2D4 }}</td>
<td class = "freitag">{{ form.S2D5 }}</td>
<td class ="samstag">{{ form.S2D6 }}</td>
<td class ="sonntag">{{ form.S2D7 }}</td>
</tr>
<tr class="even">
<td class="shicht">Schicht 3</td>
<td class="montag">{{ form.S3D1 }}</td>
<td class="dienstag">{{ form.S3D2 }}</td>
<td class = "Mittwoch">{{ form.S3D3 }}</td>
<td class = "donnerstag">{{ form.S3D4 }}</td>
<td class = "freitag">{{ form.S3D5 }}</td>
<td class ="samstag">{{ form.S3D6 }}</td>
<td class ="sonntag">{{ form.S3D7 }}</td>
</tbody>
</table>
</div>
</div>
<input type="submit" value="Save">
You can use raw queries for this.
For capture the form filds you can use the "clean" methods in the base form class see forms validation