Django: how to get an object of manager on admin page - python

I am new to Django and I am working on a project. In my project an admin will have the power to assign the project to a manager. So I want to render the name of all the managers from the database so that it will be displayed to the admin.
here is my .html file where I want to render the name of the manager in:
<div class="body table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>S No.</th>
<th>COMPANY NAME</th>
<th>TEAM MEMBER</th>
<th>EMAIL</th>
<th>ASSIGN TEAM</th>
</tr>
</thead>
<tbody>
{%for team in object%}
<tr>
<form id="form_id" method="POST" action = "{% url 'accept' %}">
{% csrf_token %}
<th scope="row"> {{ forloop.counter }}</th>
<td>{{team.company_name}}</td>
<td>{{team.team_member}}</td>
<td>{{team.email}}</td>
<td>
<select name="manager">
{% for manager in managers %}
<option value ="{{manager.id}}">{{manager.name}}</option>
{% endfor %}
</select>
<!-- </div> -->
</td>
</tr>
{% endfor %}
</tbody>
</table>
Here is my model for manager:
class manager(models.Model):
name = models.CharField(max_length= 500)
designation = models.CharField(max_length= 500)
class Meta:
permissions = [
("edit_task", "can edit the task"),
]
def __str__(self):
return self.name
Here is my views.py;
def accept(request):
obj= Create_Team.objects.filter(status='Accept')
if request.method == 'POST':
acc = manager()
manager_id = int(request.POST.get('manager', 1))
acc.manager = manager.objects.get(pk=manager_id)
return render(request, "admin/accept.html", {"object": obj})
In the admins page, I want to display all the names of the managers. I have added the image of the admin page.

I think you forgot to include the managers queryset in the context variable
def accept(request):
obj= Create_Team.objects.filter(status='Accept')
managers = manager.objects.all()
if request.method == 'POST':
acc = manager()
manager_id = int(request.POST.get('manager', 1))
acc.manager = manager.objects.get(pk=manager_id)
return render(request, "admin/accept.html", {"object": obj, "managers": managers})

Related

Django error value error: The view sub_categories.views.insert_sub_categories didn't return an HttpResponse object. It returned None instead

I am tasked with making a shopping crud project with models Products,categories,sub_categories,size,colors. Categories and subcategories are connected via foreign keys and I am using SERAILIZERS.the problem is that when I try to insert the data into sub Categories it doesnt come in both the database and the webpage
I also tried value = "{{c.category_name}}" as well in select dropdown as well
below are the models
class Categories(models.Model):
category_name = models.CharField(max_length=10)
category_description = models.CharField(max_length=10)
isactive = models.BooleanField(default=True)
class SUBCategories(models.Model):
category_name = models.ForeignKey(Categories,on_delete=models.CASCADE)
sub_categories_name = models.CharField(max_length=20)
sub_categories_description = models.CharField(max_length=20)
isactive = models.BooleanField(default=True)
show and insert function of sub_categories
def show_sub_categories(request):
showsubcategories = SUBCategories.objects.filter(isactive=True)
#print(showsubcategories)
serializer = SUBCategoriesSerializer(showsubcategories,many=True)
print(serializer.data)
return render(request,'polls/show_sub_categories.html',{"data":serializer.data})
def insert_sub_categories(request):
if request.method == "POST":
insertsubcategories = {}
insertsubcategories['sub_categories_name']=request.POST.get('sub_categories_name')
insertsubcategories['sub_categories_description']=request.POST.get('sub_categories_description')
form = SUBCategoriesSerializer(data=insertsubcategories)
if form.is_valid():
form.save()
print("hkjk",form.data)
messages.success(request,'Record Updated Successfully...!:)')
print(form.errors)
return redirect('sub_categories:show_sub_categories')
else:
print(form.errors)
else:
insertsubcategories = {}
form = SUBCategoriesSerializer(data=insertsubcategories)
category_dict = Categories.objects.filter(isactive=True)
category = CategoriesSerializer(category_dict,many=True)
hm = {'context': category.data}
if form.is_valid():
print(form.errors)
return render(request,'polls/insert_sub_categories.html',hm)
html of the insert page and show page respectively
<td>category name</td>
<td>
<select name="category_name" id="">
{% for c in context %}
<option value="{{c.id}}">{{c.category_name}}</option>
{% endfor %}
</select>
</td>
</tr>
<tr>
<td>sub categories Name</td>
<td>
<input type="text" name="sub_categories_name" placeholder="sub categories ">
</td>
</tr>
<tr>
<td>Sub categories Description</td>
<td>
<textarea name="sub_categories_description" id="" cols="30" rows="10">
</textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Insert" />
</td>
<td>
{% if messages %}
{% for mess in messages %}
<b style="color:green;">{{mess}}</b>
{% endfor %}
{% endif %}
</td>
<tbody>
<tr>
<td><b>{{result.sub_categories_name}}</b></td>
<td><b>{{result.sub_categories_description}}</b></td>
<td style="position: relative;left:50px;">
<a href="sub_categories/edit_sub_categories/{{result.id}}">
<button class="btn btn-primary">
<i class="fa-solid fa-pen-to-square">EDIT</i>
</button>
</a>
</td>
<td>
<a href="{% url 'sub_categories:delete_sub_categories' result.id %}" onclick="return confirm('Are You Sure you want to delete?')">
<button class="btn btn-danger">
<i class="fa-solid fa-trash">DELETE</i>
</button>
</a>
</td>
</tr>
</tbody>
categories and sub categories serializer
class CategoriesSerializer(serializers.ModelSerializer):
class Meta:
model = Categories
fields = "__all__"
extra_kwargs = {'category_name': {'required': False}}
class SUBCategoriesSerializer(serializers.ModelSerializer):
class Meta:
model = SUBCategories
fields = "__all__"
where am I going wrong in the code?
Try this out and let me know, a few changes you'd require
def insert_sub_categories(request):
if request.method == "POST":
form = SUBCategoriesSerializer(data=request.POST)
if form.is_valid():
form.save()
messages.success(request, "Record Updated Successfully...!:)")
return redirect("sub_categories:show_sub_categories")
category_dict = Categories.objects.filter(isactive=True)
category = CategoriesSerializer(category_dict, many=True)
hm = {"context": category.data}
return render(request, "polls/insert_sub_categories.html", hm)
Form part
<form method="POST">
{% csrf_token %}
<table>
<thead>
<tr>
<td>category name</td>
<td>
<select name="category_name" id="">
{% for c in context %}
<option value="{{c.id}}">{{c.category_name}}</option>
{% endfor %}
</select>
</td>
</tr>
<tr>
<td>sub categories Name</td>
<td>
<input type="text" name="sub_categories_name" placeholder="sub categories ">
</td>
</tr>
<tr>
<td>Sub categories Description</td>
<td>
<textarea name="sub_categories_description" id="" cols="30" rows="10">
</textarea>
</td>
</tr>
<tr>
<td>Active</td>
<td>
<input type="checkbox" name="isactive" value="true" checked>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Insert" />
</td>
<td>
{% if messages %}
{% for mess in messages %}
<b style="color:green;">{{mess}}</b>
{% endfor %}
{% endif %}
</td>
</tr>
</thead>
</table>
<button class="btn btn-success">Go To Home</button>
</form>
model
class SUBCategories(models.Model):
category_name = models.ForeignKey(Categories, on_delete=models.CASCADE)
sub_categories_name = models.CharField(max_length=20)
sub_categories_description = models.CharField(max_length=20)
isactive = models.BooleanField(default=True)
def __str__(self):
return self.category_name.category_name
This error occurs because there is a chance in your function view, that it does not return proper Response or Redirect object. If you send POST request, but the form is not valid, then it will not return anything.
def insert_sub_categories(request):
if request.method == "POST":
...
if form.is_valid():
...
return redirect('sub_categories:show_sub_categories')
else:
print(form.errors)
# HERE YOU MISS REDIRECT/RENDER
else:
...
return render(request,'polls/insert_sub_categories.html',hm)
Also you don't pass SUBCategories.category_name to your serializer. It's required field, so it will never be valid without it. You may try form = SUBCategoriesSerializer(request.POST) instead of adding values one by one.

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%}

Trying to add a form to a DetailView

I am writing a Detail View - and the form that is displayed is the particular Track that the user is adding/updating to the CD Entry (It's a CD Library application). The trick is I want to see everything else about the CD on the page as well as the form for the particular track. Having trouble figuring out how to get the form to be just the trac I am adding/updating.
Basically you can enter a CD Title,Artist, and total time of the CD into the CD model. Then the Tracks are stored in the Track Model, with their Foreign Key being the CD they are on.
While looking at a Detail View of the CD, the user can add or update a Particular track via a button. I'm trying to get the update part working.
Model Looks like this:
from django.db import models
from datetime import datetime, timedelta
class Cd(models.Model):
artist_name = models.CharField(max_length=155)
cd_title = models.CharField(max_length=155)
cd_total_time = models.TimeField(default="00:00:00")
cd_total_time_delta = models.DurationField(default=timedelta)
cd_run_time = models.TimeField(default="00:00:00",blank=True)
cd_run_time_delta = models.DurationField(default=timedelta)
cd_remaining_time = models.TimeField(default="00:00:00",blank=True)
cd_remaining_time_delta = models.DurationField(default=timedelta)
def save(self, *args, **kwargs):
super().save(*args,**kwargs)
def __str__(self):
return f"{self.artist_name} : {self.cd_title}"
class Track(models.Model):
cd_id = models.ForeignKey(Cd, on_delete=models.CASCADE,
related_name='cd_tracks',
)
track_title = models.CharField(max_length=50)
track_number = models.IntegerField()
trk_length_time = models.TimeField(null=True,default=None, blank=True)
trk_length_time_delta = models.DurationField(default=timedelta)
trk_run_time = models.TimeField(default="00:00:00",blank=True)
trk_run_time_delta = models.DurationField(default=timedelta)
trk_remaining_time = models.TimeField(default="00:00:00",blank=True)
trk_remaining_time_delta = models.DurationField(default=timedelta)
def save(self, *args, **kwargs):
super().save(*args,**kwargs)
self.cd_id.save()
def __str__(self):
return f"{self.track_title}"
The views.py snippet:
class Track_update(UpdateView):
model = Track
template_name = 'track_update.html'
fields = [ 'cd_id', 'track_title',
'track_number', 'trk_length_time'
]
success_url = "/"
class Cd_DetailView(DetailView):
model = Cd
template_name = 'cd_detail.html'
fields = ['artist_name','cd_title','cd_total_time',
'cd_run_time','cd_remaining_time'
]
class Cd_MixedView(FormMixin, DetailView):
model = Cd
template_name = 'cd_mixed_view.html'
form_class = TrackForm
def get_success_url(self):
return reverse('cd_detail {id}')
def get_context_data(self, **kwargs):
context = super(Cd_MixedView,self).get_context_data(**kwargs)
context['form'] = TrackForm(initial={
'cd_id':self.object
})
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self,form):
form.save()
return super(Cd_MixedView, self).form_valid(form)
The urls.py looks like
from django.urls import path
from django.contrib import admin
from .views import (
HomePageView,
Cd_Create,
Cd_Update,
Cd_DetailView,
List_Cds,
Track_Create,
Cd_MixedView,
)
urlpatterns = [
path('', HomePageView.as_view(), name = 'home'),
path('admin/', admin.site.urls),
path('cd/add/', Cd_Create.as_view(), name='cd_new'),
path('cd/update/<int:pk>', Cd_Update.as_view(), name='cd_update'),
path('cd/detail/<int:pk>', Cd_DetailView.as_view(), name='cd_detail'),
path('track/add/', Track_Create.as_view(), name='track_new'),
path('track/add/<int:pk>', Cd_MixedView.as_view(), name='cd_mixed_view'),
path('list/', List_Cds.as_view(), name='list_cds'),
]
The template looks like this:
<!-- templates/cd_mixed_view.html -->
{% extends 'base.html' %}
{% load static %}
{% block title %} CD Details{% endblock title %}
{% block content %}
<h1>CD Update Track </h1>
<p>Artist Name: {{ cd.artist_name}}
<p>Cd Title: {{ cd.cd_title }}
<p>Cd Total Time: {{ cd.cd_total_time|time:"H:i:s" }}
<p>Cd Run Time: {{ cd.cd_run_time|time:"H:i:s" }}
<p>Cd Remaining Time:
{% if cd.cd_run_time_delta > cd.cd_total_time_delta %}
(-{{ cd.cd_remaining_time|time:"H:i:s" }})
{% else %}
{{ cd.cd_remaining_time|time:"H:i:s" }}
{% endif %}
<TABLE BORDER="0" TABLE_LAYOUT="fixed" WIDTH="100%">
<TR BGCOLOR="#B0B0FF">
<TD></TD>
<TD ALIGN="Center"> Track #</TD>
<TD ALIGN="Center"> Cut Title</TD>
<TD ALIGN="Center">Track Length</TD>
<TD ALIGN="Center" BGCOLOR="#CC99CC">Run Time</TD>
<TD ALIGN="Center" BGCOLOR="#CC99CC">Time Remaining</TD>
</TR>
{% for tracks in cd.cd_tracks.all %}
*** This is the part I am having trouble with ***
{% if tracks.id = track number that was clicked %}
{form_as_p}
{% else %}
<TR>
<TD ALIGN="Center" rowspan="1" height="33" width="33">
<TD ALIGN="Left" VALIGN="Top" WIDTH="10"> {{ tracks.track_number }}</TD>
<TD ALIGN="Left" VALIGN="Top"> {{ tracks.track_title }}</TD>
<TD ALIGN="Left" VALIGN="Top">{{ tracks.trk_length_time|time:"H:i:s" }}</TD>
<TD ALIGN="Left" VALIGN="Top">{{ tracks.trk_run_time|time:"H:i:s" }}</TD>
{% if tracks.trk_run_time_delta > cd.cd_total_time_delta %}
<TD BGCOLOR="#8DF1BF" ALIGN="Left"> (-{{ tracks.trk_remaining_time|time:"H:i:s" }})</TD>
{% else %}
<TD BGCOLOR="#8DF1BF" ALIGN="Left"> {{ tracks.trk_remaining_time|time:"H:i:s" }}</TD>
{% endif %}
</TR>
{% endfor %}
</TABLE>
</table>
{% endblock content %}
So, how do I pass the Track ID into the template, so that I can display the form for THAT track, otherwise
display the track information for all the other tracks.
Any information about how to approach this would be greatly appreciated.
Below is a picture of what the Detail Screen looks like before attempting to update the Track.
Thanks
Did you think about adding the tracking id as a slug, creating another function in views, to pass it? with an 'a' tag, and passing an href, with inside it the foreign key if the track referring to the CD. You could pass the values in the context of the view.

How to pass values from a dropdown list to the view in django

I have searched quite extensively for a clear answer to my problem but have not been able to find anything. I have am currently displaying the first 5 items from a database and want to add a feature that allows the user to toggle between ascending and descending order using the current rent value, but I am having trouble passing the value of the dropdown list to the views and altering the order of the table.
HTML file:
{% block content %}
<form method="GET" action="" >
{% csrf_token %}
{{ form.as_p }}
<select name="dropdown">
<option value="dsc">Descending</option>
<option value="asc">Ascending</option>
</select>
<input type="submit" value="order">
</form>
<table id="myTable" class="tablesorter">
<thead>
<th>Property Name</th>
<th>Property Address 1</th>
<th>Property Address 2</th>
<th>Property Address 3</th>
<th>Property Address 4</th>
<th>Unit Name</th>
<th>Tenant Name</th>
<th>Lease Start</th>
<th>Lease End</th>
<th>Lease Years</th>
<th>Rent</th>
</thead>
{% for data in list.all %}
<tr>
<td>{{data.property_name}}</td>
<td>{{data.property_address1}}</td>
<td>{{data.property_address2}}</td>
<td>{{data.property_address3}}</td>
<td>{{data.property_address4}}</td>
<td>{{data.unit_name}}</td>
<td>{{data.tenant_name}}</td>
<td>{{data.lease_start}}</td>
<td>{{data.lease_end}}</td>
<td>{{data.lease_years}}</td>
<td>{{data.current_rent}}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
Views.py
from django.db.models import Sum
from . import models
from .models import Stats
from django.views.generic import ListView,TemplateView,CreateView
# Create your views here.
class HomeView(TemplateView):
template_name = 'index.html'
class StatsListView(ListView):
context_object_name = 'list'
model = models.Stats
def get_queryset(self):
first_five = Stats.objects.all().order_by('current_rent')[:5]
return first_five
def PageObjects(self,request):
answer = request.GET['dropdown']
if request.method == 'POST':
if answer == 'dsc':
Stats.objects.all().order_by('-current_rent')[:5]
else:
Stats.objects.all().order_by('current_rent')[:5]
I would recommend sending your data with post:
{% block content %}
<form method="Post" action="" >
{% csrf_token %}
{{ form.as_p }}
<select name="dropdown">
<option value="dsc">Descending</option>
<option value="asc">Ascending</option>
</select>
<input type="submit" value="Select">
</form>
<table id="myTable" class="tablesorter">
<thead>
<th>Property Name</th>
<th>Property Address 1</th>
<th>Property Address 2</th>
<th>Property Address 3</th>
<th>Property Address 4</th>
<th>Unit Name</th>
<th>Tenant Name</th>
<th>Lease Start</th>
<th>Lease End</th>
<th>Lease Years</th>
<th>Rent</th>
</thead>
{% for data in list.all %}
<tr>
<td>{{data.property_name}}</td>
<td>{{data.property_address1}}</td>
<td>{{data.property_address2}}</td>
<td>{{data.property_address3}}</td>
<td>{{data.property_address4}}</td>
<td>{{data.unit_name}}</td>
<td>{{data.tenant_name}}</td>
<td>{{data.lease_start}}</td>
<td>{{data.lease_end}}</td>
<td>{{data.lease_years}}</td>
<td>{{data.current_rent}}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
Views.py
from django.db.models import Sum
from . import models
from .models import Stats
from django.views.generic import ListView,TemplateView,CreateView
# Create your views here.
class HomeView(TemplateView):
template_name = 'index.html'
class StatsListView(ListView):
context_object_name = 'list'
model = models.Stats
def get_queryset(self):
first_five = Stats.objects.all().order_by('current_rent')[:5]
return first_five
def PageObjects(self,request):
# Changes Begin Here: =========================>
if request.method == 'POST':
form = YourForm(request.POST)
if form.is_valid():
answer = form.cleaned_data['value']
# Changes End Here: =========================>
if answer == 'dsc':
Stats.objects.all().order_by('-current_rent')[:5]
else:
Stats.objects.all().order_by('current_rent')[:5]

Django: Trying to click on a link and remove an assigned client

Good morning. I am having an issue trying to remove a client from an assigned bed. I created a one-item form called "RoomUpdate" that will allow a user to add a client to a bed that is empty via a dropdown through a ModelChoiceField.
When the bed is full, it does not allow the access to the drop down, instead, I have a link that states "remove client." What I want to happen is when I click that button, it assigns the default value of None to that bed in that room.
What's tricky, at least to my new-ish to Django mind, is how I do this through multiple tables. Having looked for multiple answers and tried different things, I know I've lost track of what I'm doing so I definitely could use some help.
models.py
class Room(models.Model):
room_id = models.AutoField(primary_key=True)
room_number = models.CharField(max_length=5)
shelter_id = models.ForeignKey(Shelter)
max_occupancy = models.CharField(max_length=3)
floor_location = models.CharField(max_length=3)
def __str__(self):
return self.room_number
class Bed(models.Model):
bed_id = models.AutoField(primary_key=True)
room_id = models.ForeignKey(Room, related_name='beds')
bed_size = models.ForeignKey(BedSize)
client_assigned = models.ForeignKey(Clients, null=True, blank=True, default=None)
forms.py
class RoomUpdate(forms.ModelForm):
client_assigned = forms.ModelChoiceField(queryset=Clients.objects.all(), required=False)
#def __init__(self, *args, **kwargs):
#super(RoomUpdate, self).__init__(*args, **kwargs)
#self.fields['client_assigned'].choices.insert(0, ('','---------' ) )
class Meta:
model = Room
fields = ( 'client_assigned', )
views.py
def room_update(request, pk, template_name='shelter/room_edit.html'):
rooms = get_object_or_404(Room, pk=pk)
form = RoomUpdate(request.POST or None, instance=rooms)
beds = Bed.objects.filter(room_id=pk)
if form.is_valid():
form.save()
return redirect('/shelter/')
return render(request, template_name, {'form': form, 'rooms': rooms, 'beds':beds,})
def remove_client(request, pk):
rooms = get_object_or_404(Room, pk=pk)
bed = Bed.objects.filter(room_id=pk)
form = RoomUpdate(request.POST)
template_fail = 'clients/invalid_permissions.html'
if request.method=='POST':
if form.is_valid():
bed.objects.update(client_assigned=None)
bed.save()
else:
return redirect(request, template_fail)
return render_to_response(request, {'rooms': rooms, 'bed': bed})
template
<form action="" method="POST">
{% csrf_token %}
<div class="room box-shadow">
<h4>Room {{ rooms.room_number }}</h4>
<table>
{% for i in rooms.beds.all %}
<tr>
<td>Bed ID: </td>
<td>{{i.bed_id }}</td>
</tr>
<tr>
<td>Bed Size: </td>
<td>{{i.bed_size }}</td>
</tr>
<tr>
<td valign="top">Client: </td>
<td>
{% if i.client_assigned %}
{{ i.client_assigned }}
<br \>
Remove Client
{% else %}
{{ form.client_assigned }}
{% endif %}
</td>
</tr>
<tr>
<td colspan="2">
<hr class="style-two" />
</td>
</tr>
{% endfor %}
<tr>
<td><input type="submit" value="Submit" /></td>
<td></td>
</tr>
</table>
</div>
</form>
I've been playing around with this a bit and making some sort of progress. If I change the url from the same as the edit, I get it to work in that it deletes from the table and redirects the user to a new page.
I would prefer it not redirect the user to a new page, but rather, update the page that's there.
Thoughts?
The new view looks like this:
def remove_client(request, pk, template_name='shelter/test.html'):
bed = Bed.objects.filter(bed_id=pk).update(client_assigned=None)
return render(request, template_name, { 'bed':bed })
Further diving into this, I found a solution I rather like and actually works in a way I wanted but couldn't figure out. Instead of focusing on the room, I realized that I needed to focus on the smaller container -- the bed -- and since it can move around, it would be the better choice.
Currently, this functionality allows me to move beds to different rooms, remove clients by selecting the '----' selector, and allows me to add clients.
So here is the answer I came up with:
forms.py
class RoomUpdate(forms.ModelForm):
bed_id = forms.CharField()
room_id = forms.ModelChoiceField(queryset=Room.objects.all())
bed_size = forms.ModelChoiceField(queryset=BedSize.objects.all(), required=False)
client_assigned = forms.ModelChoiceField(queryset=Clients.objects.all(), required=False)
class Meta:
model = Bed
fields = ('bed_id', 'client_assigned', 'room_id', 'bed_size' )
views.py
def room_update(request, pk, template_name='shelter/room_edit.html'):
beds = get_object_or_404(Bed,pk=pk)
form = RoomUpdate(request.POST or None, instance=beds)
if form.is_valid():
form.save()
return redirect('/shelter/')
return render(request, template_name, {'form': form, 'beds':beds,})
room_edit.html
<form action="" method="POST">{% csrf_token %}
<div class="room box-shadow">
<h4>Room </h4>
<table>
<tr>
<td>Room: </td>
<td>{{ form.room_id }}</td>
</tr>
<tr>
<td>Bed ID: </td>
<td>{{ form.bed_id }}</td>
</tr>
<tr>
<td>Bed Size: </td>
<td>{{ form.bed_size }}</td>
</tr>
<tr>
<td valign="top">Client: </td>
<td>{{ form.client_assigned }}</td>
</tr>
<tr>
<td colspan="2"><hr class="style-two" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
<td></td>
</tr>
</table>
</div>
</form>

Categories

Resources