Django Custom User update with one to one to Customer model - python

I'm trying to create Update view for Customer model which have Onetoone relation with User(django model. After five hours and trying function base and class views I'm unable to get this working. Where am I making a mistake?
my models.py
class Customer(Model):
user = OneToOneField(User, on_delete=CASCADE)
mobile = CharField(max_length=12,null=True)
dob = DateField(null=True)
def __str__(self):
return self.user.username
my views.py
class ProfileUpdateView(UpdateView):
template_name = 'forms.html'
form_class = AdminUserUpdateForm
model = User
success_url = reverse_lazy('controls')
def get_object(self, queryset=None):
return Customer.objects.get(pk=self.kwargs['pk']).user
# Not working
def customer_list_view(request):
customer = Customer.objects.filter(user__groups__name='customer')
premium = Customer.objects.filter(user__groups__name='premium')
context = {'customer': customer, 'premium': premium}
return render(request, 'customercontrol.html', context)
my forms.py
class AdminUserUpdateForm(UserChangeForm):
class Meta:
model = User
fields = ['username', 'email', 'groups']
mobile = CharField(max_length=30)
dob = DateField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for visible in self.visible_fields():
visible.field.widget.attrs['class'] = 'form-control'
#atomic
def save(self, commit=True):
user = super().save(commit)
mobile = self.cleaned_data['mobile']
dob = self.cleaned_data['dob']
customer = Customer.objects.get(user__pk=user.pk)
customer.mobile = mobile
customer.dob = dob
if commit:
customer.save()
return user
my templates, where I get PK for the queries.
{% extends "base.html" %}
{% block content %}
<h1 class="font1">Our premium customers:</h1>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">User ID</th>
<th scope="col"><a class="btn btn-secondary" href="">Username</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Name</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Email</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Phone</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Date of Birth</a></th>
</tr>
</thead>
<tbody>
{% for c in premium %}
<tr>
<td>{{c.id}}</td>
<td>
{{ c.user.username }}</td>
<td>{{c.user.first_name}} {{c.user.last_name}} </td>
<td>{{ c.user.email}}</td>
<td>{{ c.mobile}}</td>
<td>{{ c.dob}}</td>
<td><ul>{% for item in c.user.groups.all %}<li>{{ item}}</li>{% endfor %}</ul></td>
<td><a class="btn btn-danger" href="{% url 'user-delete' c.id %}">Delete</a></td>
<td><a class="btn btn-success" href="{% url 'user-update' c.pk %}">Update</a></td>
</tr>
{% endfor %}
</tbody>
</table>
<h1 class="font1">Our customers:</h1>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">User ID</th>
<th scope="col"><a class="btn btn-secondary" href="">Username</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Name</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Email</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Phone</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Date of Birth</a></th>
</tr>
</thead>
<tbody>
{% for c in customer %}
<tr>
<td>{{c.id}}</td>
<td>
{{ c.user.username }}</td>
<td>{{c.user.first_name}} {{c.user.last_name}} </td>
<td>{{ c.user.email}}</td>
<td>{{ c.mobile}}</td>
<td>{{ c.dob}}</td>
<td><ul>{% for item in c.user.groups.all %}<li>{{ item}}</li>{% endfor %}</ul></td>
<td><a class="btn btn-danger" href="{% url 'user-delete' c.id %}">Delete</a></td>
<td><a class="btn btn-success" href="{% url 'user-update' c.pk %}">Update</a></td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
the one with form
{% extends "base.html" %}
{% block content %}
<form method="post">
{% csrf_token %}
<table>{{ form }}</table>
<input type="submit" value="Submit" class="btn btn-primary">
</form>
{% endblock %}
urls.py
path('<int:pk>/groupupdate', GroupUpdateView.as_view(), name='groupdate'),
path('customercontrol', customer_list_view, name='customercontrol'),

I found solution to my own problem, I had to add function into my view which is passing initial data into form:
def get_initial(self):
initial = super().get_initial()
initial['dob'] = Customer.objects.get(pk=self.kwargs['pk']).dob
initial['mobile'] = Customer.objects.get(pk=self.kwargs['pk']).mobile
return initial

Related

Django/PostgreSQL not displaying search result

I am unable to retrieve any search results when searching for items. I am using Postgresql and Django. Below is my code. I am not sure if I am not doing the search query right or I just cannot display the results.
I have the search bar in "inventory_management.html". I am trying to get it to where the user searches for an item, and then a list of the displayed items are shown.
models.py
class Inventory(models.Model):
product = models.CharField(max_length=50)
description = models.CharField(max_length=250)
paid = models.DecimalField(null=True, max_digits=5, decimal_places=2)
bin = models.CharField(max_length=4)
listdate = models.DateField(null=True, blank=True)
listprice = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True)
solddate = models.DateField(null=True, blank=True)
soldprice = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True)
shipdate = models.DateField(null=True, blank=True)
shipcost = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateField(auto_now=True)
def __str__(self):
return self.product + "\n" + self.description + "\n" + self.paid + self.bin + "\n" + self.listdate + "\n" + self.listprice + "\n" + self.solddate + "\n" + self.soldprice + "\n" + self.shipdate + "\n" + self.shipcost
views.py
#login_required(login_url="/login")
def search(request):
q = request.GET.get('q')
if q:
vector = SearchVector('product', 'description')
query = SearchQuery(q)
searchinv = Inventory.objects.annotate(search=vector).filter(search=query)
else:
searchinv = None
return render(request, 'portal/search.html', {"searchinv": searchinv})
inventory_management.html (where the search bar is located)
{% extends 'portal/base.html' %}
{% block title %}{% endblock %}
{% block content %}
<br>
<div class="row">
<div class="col">
<form class="d-flex" role="search" action="/search" method="get">
<input class="form-control me-2" type="text" name="q" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success">Search</button>
</form>
</div>
<div class="col">
<a class="btn btn-primary me-md-2" href="/newitem" type="button">Input New Purchase</a>
</div>
</div>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>Update Item</th>
<th>Product ID</th>
<th>Product</th>
<th>Description</th>
<th>Purchase Price</th>
<th>Location</th>
<th>List Date</th>
<th>List Price</th>
<th>Sold Date</th>
<th>Sold Price</th>
<th>Ship Date</th>
<th>Ship Cost</th>
</tr>
</thead>
{% for inventory in inventory %}
<tr>
<td><a class='btn btn-success btn-sm' href='/update/{{inventory.id}}'>Update</a>
<td>{{inventory.id}}</td>
<td>{{inventory.product}}</td>
<td>{{inventory.description}}</td>
<td>{{inventory.paid}}</td>
<td>{{inventory.bin}}</td>
<td>{{inventory.listdate}}</td>
<td>{{inventory.listprice}}</td>
<td>{{inventory.solddate}}</td>
<td>{{inventory.soldprice}}</td>
<td>{{inventory.shipdate}}</td>
<td>{{inventory.shipcost}}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
search.html
{% extends 'portal/base.html' %}
{% block title %}{% endblock %}
{% block content %}
<br>
<div class="row">
<div class="col">
<form class="d-flex">
<input class="form-control me-2" type="text" name="q" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success">Search</button>
</form>
</div>
<div class="col">
<a class="btn btn-primary me-md-2" href="/newitem" type="button">Input New Purchase</a>
</div>
</div>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>Update Item</th>
<th>Product ID</th>
<th>Product</th>
<th>Description</th>
<th>Purchase Price</th>
<th>Location</th>
<th>List Date</th>
<th>List Price</th>
<th>Sold Date</th>
<th>Sold Price</th>
<th>Ship Date</th>
<th>Ship Cost</th>
</tr>
</thead>
{% for inventory in inventory %}
<tr>
<td><a class='btn btn-success btn-sm' href='/update/{{inventory.id}}'>Update</a>
<td>{{inventory.id}}</td>
<td>{{inventory.product}}</td>
<td>{{inventory.description}}</td>
<td>{{inventory.paid}}</td>
<td>{{inventory.bin}}</td>
<td>{{inventory.listdate}}</td>
<td>{{inventory.listprice}}</td>
<td>{{inventory.solddate}}</td>
<td>{{inventory.soldprice}}</td>
<td>{{inventory.shipdate}}</td>
<td>{{inventory.shipcost}}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
You don't have inventory in your view's context, yet you try to use it in template:
{% for inventory in inventory %}
Change it to:
{% for inventory in searchinv %}
And it should be better.

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.

Django model methods(Date filter)

Been struggling for weeks now with this issue, starting to feel like I will never solve it.
I have these methods under my model.
def sfget_totals(self):
return self.agent_sale.filter(Date_created__range=["2022-03-01","2022-04-02"]).count()
def sfget_confirmed(self):
return self.agent_sale.filter(State="Confirmed",Date_created__range=["2022-03-01","2022-04-02"]).count()
def sfget_debi(self):
return self.agent_sale.filter(AcknowledgeQA=True,State="Confirmed",Debi_status="Accepted",Date_created__range=["2022-03-01","2022-04-02"]).count()
def sfget_requested(self):
return self.agent_sale.filter(Debi_status="Requested",Date_created__range=["2022-03-01","2022-04-02"]).count()
def sfget_cancelled(self):
return self.agent_sale.filter(State="Cancelled",Date_created__range=["2022-03-01","2022-04-02"]).count()
def sfget_pending(self):
return self.agent_sale.filter(State="Pending",Date_created__range=["2022-03-01","2022-04-02"]).count()
in the above example i am putting the dates in manually(it works and returns the correct query)
problem is I still don't know how to make the user plug these dates in through the site.
This is my view.
def Team_stats(request,pk):
sd = request.GET.get("from")
ed = request.GET.get("to")
start_date = datetime.datetime.strptime(sd, "%Y-%m-%d").date()
end_date = datetime.datetime.strptime(ed, "%Y-%m-%d").date()
if start_date == None or end_date == None:
sales_agent = SalesAgent.objects.filter(Team_leader=pk)
return render(request,"Sales/Team_detail_page.html",{"sales_agent":sales_agent})
else:
sales_agent = SalesAgent.objects.filter(Team_leader=pk,agent_sale__Date_created__range=[start_date,end_date]).distinct()
print(type(start_date))
return render(request,"Sales/Team_detail_page.html",{"sales_agent":sales_agent})
This is my template.
I need to render all the agents under the team leader and the particular field of another model. For example State,Date_Created,Debi_status.
<form method="GET" action=".">
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Start date</label>
<input type="date" format='%Y-%m-%d' name="from" class="form-control" id="inputEmail4" placeholder="Start Date">
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">End date</label>
<input type="date" format='%Y-%m-%d' name="to" class="form-control" id="inputEmail4" placeholder="End date">
</div>
</div>
<button type="submit" class="btn btn-primary">Search</button>
</form>
<!-- <p>THERE SHOULD BE A GRAPH IN HERE FOR THE AGENTS STATS</p> -->
<br>
<br>
<div class="container">
<table class="table table-dark table-striped table-bordered">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Agent Name</th>
<th scope="col">Total sales</th>
<th scope="col">Total debis</th>
<th scope="col">Total confirmed</th>
<th scope="col">Total requested</th>
<th scope="col">Total pending</th>
<th scope="col">Total cancelled</th>
</tr>
</thead>
{% for entry in sales_agent %}
<tbody>
<td>{{forloop.counter}}</td>
<td>{{entry.SA_name}}</td>
<td>{{entry.sfget_totals}}</td>
<td>{{ entry.sfget_debi}}</td>
<td>{{ entry.sfget_confirmed}}</td>
<td>{{ entry.sfget_requested}}</td>
<td>{{ entry.sfget_cancelled}}</td>
<td>{{ entry.sfget_pending}}</td>
{%endfor%}
</table>
<div>
<a type="button" class="btn btn-dark btn-m" href="{%url 'Sales:salesdash'%}">Go back</a>
{%endblock%}
I don't know how to do it better. It's not the best answer because you have to iterate through the entire queryset. But I think it works:
1- Change your models methods adding the variables "from" and "to":
#example
def sfget_totals(self, from, to): #
return self.agent_sale.filter(Date_created__range=[from,to]).count()
2- In your views.py, iterate and add the new properties to each item of the queryset:
def Team_stats(request,pk):
sd = request.GET.get("from")
ed = request.GET.get("to")
start_date = datetime.datetime.strptime(sd, "%Y-%m-%d").date()
end_date = datetime.datetime.strptime(ed, "%Y-%m-%d").date()
if start_date == None or end_date == None:
sales_agent = SalesAgent.objects.filter(Team_leader=pk)
return render(request,"Sales/Team_detail_page.html",{"sales_agent":sales_agent})
else:
sales_agent = SalesAgent.objects.filter(Team_leader=pk,agent_sale__Date_created__range=[start_date,end_date])
for s in sales_agent:
s.sfget_totals_prop = s.sfget_totals(start_date,end_date)
s.sfget_confirmed_prop = s.sfget_confirmed(start_date,end_date)
s.sfget_debi_prop = s.sfget_debi(start_date,end_date)
....
....
return render(request,"Sales/Team_detail_page.html",{"sales_agent":sales_agent})
3- In your templates, change the methods name by the new properties:
<td>{{entry.sfget_totals_prop}}</td>
<td>{{ entry.sfget_debi_prop}}</td>
<td>{{ entry.sfget_confirmed_prop}}</td>
<td>{{ entry.sfget_requested_prop}}</td>
<td>{{ entry.sfget_cancelled_prop}}</td>
<td>{{ entry.sfget_pending_prop}}</td>
Probably, you can solve the problem using Django Managers https://docs.djangoproject.com/en/4.0/topics/db/managers/ and you will find a better way.

How to select/unselect/delete multiple django items in a table with the same checkbox?

I have this table of items with their details, and I have implemented a method to 'select' a few items using a submit button, which submits all checked checkboxes on each item.
This is the code for the checkbox:
<input name='quiz-pids' id='checkbox-{{ quiz.id }}' type="checkbox" value="{{ quiz.id }}" required>
As you can see, I have passed the quiz.id in the checkbox value. This is my submit button I am using:
<input type="submit" class="btn btn-primary select-btn myitems-select-btn"
value='Finalize Items'
required>
Here, I have not mentioned what this button will do except than submit. This is the function which processes the data input by submit button.
class UploadedItems(ListView):
model = ItemBatch
ordering = ('uploaded',)
context_object_name = 'plan'
template_name = 'classroom/teachers/item_list.html'
def post (self, request, *args, **kwargs):
# get the selected quizs
quizs = request.POST.getlist('quiz-pids')
# retrieves thoses quizes from the database:
print("pids returned are ", quizs)
# items = ItemBatch.objects.filter(pid__in=quizs)
for i in quizs:
print("before", i)
i = get_object_or_404(ItemBatch, id=i)
i.rtd = 'True'
i.save()
print("after", i.truck_type) # print("items are",items)
return redirect('teachers:upload_batch')
As you can see, my function 'post' accepts only quiz-pids because of this line request.POST.getlist('quiz-pids'). Now my question is, I also want to delete and unselect my items. But, because my function can only accept quiz-pids, I cannot just create another button for that.
What I tried
I tried adding more functions:
def post (self, request, *args, **kwargs):
# get the selected quizs
quizs = request.POST.getlist('quiz-pids')
deleted_items = request.POST.getlist('delete-pids')
unselect_items = request.POST.getlist('unselect-pids')
# retrieves thoses quizes from the database:
print("pids returned are ", quizs)
# items = ItemBatch.objects.filter(pid__in=quizs)
for i in quizs:
print("before", i)
i = get_object_or_404(ItemBatch, id=i)
i.rtd = 'True'
i.save()
print("after", i.truck_type) # print("items are",items)
for j in unselect_items:
j = get_object_or_404(ItemBatch, id=i)
j.rtd = 'False'
j.save()
for k in deleted_items:
k = get_object_or_404(ItemBatch, id=i)
k.delete()
k.save()
But, because every checkbox I have in front of my items, has the name name='quiz-pids', I am not able to generate a deleted_items list or unselect_items list. I cannot possibly give three different checkboxes to every item. What should I do?
Here is my complete html and views function:
#method_decorator([login_required, teacher_required], name='dispatch')
class UploadedItems(ListView):
model = ItemBatch
ordering = ('uploaded',)
context_object_name = 'plan'
template_name = 'classroom/teachers/item_list.html'
def get_queryset (self):
return ItemBatch.objects.filter(uploaded_by=self.request.user)
def get_context_data (self, **kwargs):
context = super().get_context_data(**kwargs)
latest = ItemBatch.objects.filter(uploaded_by=self.request.user).order_by('-time').annotate(
truncated_time=Trunc('time', 'minute', output_field=DateTimeField()))
context['last'] = ItemBatch.objects.filter(uploaded_by=self.request.user).annotate(
truncated_time=Trunc('time', 'minute', output_field=DateTimeField())).filter(
truncated_time=Subquery(latest.values('truncated_time')[:1])).order_by('-rtd')
return context
def post (self, request, *args, **kwargs):
# get the selected quizs
quizs = request.POST.getlist('quiz-pids')
deleted_items = request.POST.getlist('delete-pids')
unselect_items = request.POST.getlist('unselect-pids')
# retrieves thoses quizes from the database:
print("pids returned are ", quizs)
# items = ItemBatch.objects.filter(pid__in=quizs)
for i in quizs:
print("before", i)
i = get_object_or_404(ItemBatch, id=i)
i.rtd = 'True'
i.save()
print("after", i.truck_type) # print("items are",items)
for j in unselect_items:
j = get_object_or_404(ItemBatch, id=i)
j.rtd = 'False'
j.save()
for k in deleted_items:
k = get_object_or_404(ItemBatch, id=i)
k.delete()
k.save()
print("pids converted are ", quizs)
return redirect('teachers:upload_batch')
HTML template:
{% extends 'base2.html' %}
{% load static %}
{% load tz humanize %}
{% timezone "Asia/Kolkata" %}
{% block content %}
<h2>Orders</h2>
{% include 'classroom/teachers/inventory_header.html' with active='myitems' %}
<h2 class="align-left"> Your Last Uploaded Items</h2>
{#Post New Bid#}
<div class="card last-items">
<form method="post" novalidate>
{% csrf_token %}
<table class="table table-striped mb-0" id="items">
<thead>
<tr>
<th>Select</th>
<th>Name</th>
<th>SKU ID</th>
<th>Quantity</th>
<th>Dimensions</th>
<th>Volume/Weight</th>
<th>Origin</th>
<th>Destination</th>
<th>Type</th>
<th>Uploaded</th>
<th>Dispatch Status</th>
</tr>
</thead>
<tbody>
<input type="checkbox" id="selectall" class="css-checkbox btn btn-primary" name="selectall"/>Select
All
{% for quiz in last %}
<input type="submit" class="btn btn-primary select-btn myitems-select-btn"
value='Finalize Items'
required>
<input type="submit" class="btn btn-primary select-btn myitems-select-btn"
value='Unselect Items'
required>
<input type="submit" class="btn btn-primary select-btn myitems-select-btn"
value='Delete Items'
required>
<a href="{% url 'teachers:pack_it' %}"
class="btn btn-primary mb-3 myitems-select-btn {% if quiz.rtd == 0 %} disabled {% endif %}"
role="button">Plan Vehicles</a>
<tr class="{% if quiz.rtd == True %} active{% endif %} {% if quiz.is_dispatched == True %} dispatched{% endif %}">
<td class="align-middle"><input name='quiz-pids' id='checkbox-{{ quiz.id }}'
type="checkbox" value="{{ quiz.id }}" required
{% if quiz.is_dispatched == 1 %} disabled{% endif %} ></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|truncatechars:8 }}/{{ quiz.weight }}</td>
<td class="align-middle">{{ quiz.origin }}</td>
<td class="align-middle">{{ quiz.destination }}</td>
<td class="align-middle">{{ quiz.truck_type }}</td>
<td class="align-middle">{{ quiz.time|naturaltime }}</td>
<td class="align-middle">{{ quiz.is_dispatched|yesno:"Dispatched,Ready to Dispatch" }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
</div>
<br>
<br>
<h2 class="align-left">All your Uploaded Items</h2>
<br>
<div class="card">
<table class="table table-striped mb-0" id="items">
<thead>
<tr>
<th>Select</th>
<th>Name</th>
<th>SKU ID</th>
<th>Quantity</th>
<th>Dimensions</th>
<th>Volume/Weight</th>
<th>Origin</th>
<th>Destination</th>
<th>Type</th>
<th>Uploaded</th>
<th>Dispatch Status</th>
</tr>
</thead>
<tbody>
<form method="post" novalidate>
{% csrf_token %}
{% for quiz in plan %}
<input type="submit" class="btn btn-primary select-btn myitems-select-btn"
value='Finalize Items'
required>
<a href="{% url 'teachers:pack_it' %}"
class="btn btn-primary mb-3 myitems-select-btn {% if quiz.rtd == 0 %} disabled {% endif %}"
role="button">Plan Vehicles</a>
<tr class="{% if quiz.rtd == True %} active{% endif %} {% if quiz.is_dispatched == True %} dispatched{% endif %}">
<td class="align-middle"><input name='quiz-pids' id='checkbox-{{ quiz.id }}'
type="checkbox" value="{{ quiz.id }}" required
{% if quiz.is_dispatched == 1 %} disabled{% endif %} ></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.truck_type }}</td>
<td class="align-middle">{{ quiz.time|naturaltime }}</td>
<td class="align-middle">{{ quiz.is_dispatched|yesno:"Dispatched,Ready to Dispatch" }}</td>
</tr>
<tr>
{% empty %}
<td class="bg-light text-center font-italic" colspan="9">You haven't uploaded any items yet.
</td>
</tr>
{% endfor %}
</form>
</tbody>
</table>
</div>
<link rel="stylesheet" href="http://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">
{# <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>#}
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#items').DataTable({
"pagingType": "full_numbers",
"bDestroy": true
});
});
</script>
<script>
$('#selectall').click(function () {
var checkedStatus = this.checked;
$('input:checkbox').each(function () {
$(this).prop('checked', checkedStatus);
});
});
</script>
{% endblock %}
{% endtimezone %}
Anybody has any doubts? or need more information?

can't add values from field into database Django

I would like to add data filled into database and output it. But i have no idea where is wrong because my data was't saved into database at all. In views.py, Scholarship is just one scholarship object, LScholarship is displaying all the data in Scholarship. I have similar code for other models and views but i have no idea what i did wrong in here, making the data can't be saved into database. Could anyone please advice me where am i wrong
add_remove_scholarship.html
<div align="center" >
<form method="POST" onsubmit="return validation()" action="">
{% csrf_token %}
{{ form.errors }}
<p>Upload File: {{scholarship.doc}} <input id="doc" type="text" name="doc"> </p>
<p>Faculty: {{scholarship.faculty}} <input id="faculty" type="text" name="faculty"> </p>
<p>Opening date: {{scholarship.openDate}} <input id="odate" type="date" name="openDate"> </p>
<p>Closing date: {{scholarship.closeDate}} <input id="edate" type="text" name="closeDate"> </p>
<input type="submit" name="AddScholarship" value="Add Scholarship" >
</form>
</div>
<br></br>
<button id="button" type="button">Delete Selected Scholarship</button>
<br></br>
<form method="POST" action="">
{% csrf_token %}
<table id="example" class="display" cellspacing="0" width="100%" border="1.5px">
<tr align="center">
<th> Scholarship </th>
<th> Faculty </th>
<th> Open Date </th>
<th> Close Date </th>
</tr>
{% for item in query_results %}
<tr align="center">
<td>{{item.doc}}</td>
<td>{{item.faculty}}</td>
<td>{{item.openDate}}</td>
<td>{{item.closeDate}}</td>
</tr>
{% endfor %}
</table>
</form>
models.py
#consists of all the details of the scholarship under the 'Add/Remove
Scholarship'
class Scholarship(models.Model):
doc = models.TextField("Doc", max_length=1000)
faculty = models.TextField("Faculty", max_length=1000)
openDate = models.DateField("Opening Date", max_length=8)
closeDate = models.TextField("CLosing Date", max_length=18)
def __str__(self):
return self.doc
#consists of all the details of the scholarship under the 'Add/Remove
Scholarship'
class LScholarship(models.Model):
scholarship = models.ForeignKey(Scholarship, on_delete=models.CASCADE)
views.py
def scholarship(request):
if request.method == "POST":
form = ScholarshipForm(request.POST)
if form.is_valid():
scholarship = form.save(commit=False)
scholarship.save()
else:
form = ScholarshipForm()
return render(request, 'hrfinance/add_remove_scholarship.html', {'form': form})
def lscholarship(request):
query_results = Scholarship.objects.all()
data={'query_results':query_results}
return render(request, 'hrfinance/add_remove_scholarship.html', data)
class ScholarshipForm(forms.ModelForm):
class Meta:
model = Scholarship
fields = '__all__'
You are using two views to render a single template.
You can merge your views into a single one and maybe reduce the logic.
If I have understood your problem correctly you could use your view more like this,
def scholarship(request, id=None):
query_results = []
if request.method == "POST":
form = ScholarshipForm(request.POST)
if form.is_valid():
scholarship = form.save(commit=False)
scholarship.save()
else:
form = ScholarshipForm()
id = request.GET.get('scholarship')
query_results = Scholarship.objects.all()
data = {
'query_results':query_results,
'form': form,
}
return render(request, 'hrfinance/add_remove_scholarship.html', data)
In your template,
<div align="center" >
<form method="POST" onsubmit="return validation()" action="">
{% csrf_token %}
{{ form.errors }}
<p>Upload File: {{ form.doc }}</p>
<p>Faculty: {{ form.faculty }} </p>
<p>Opening date: {{ form.startDate }} </p>
<p>Closing date: {{ closeDate }} </p>
<button type="submit" name="AddUser" value="Add Scholarship" onclick="add()" >Add Scholarship</button>
</form>
</div>
<table id="example" class="display" cellspacing="0" width="100%" border="1.5px">
<tr align="center">
<th> Scholarship </th>
<th> Faculty </th>
<th> Open Date </th>
<th> Close Date </th>
</tr>
{% for item in query_results %}
<tr align="center">
<td>{{item.doc}}</td>
<td>{{item.faculty}}</td>
<td>{{item.openDate}}</td>
<td>{{item.closeDate}}</td>
</tr>
{% endfor %}
</table>

Categories

Resources