I am trying to retrieve the is_winning_bid value of a query set that returns:
<QuerySet [{'id': 33, 'user_id_id': 3, 'listing_id_id': 33, 'bid_amount': Decimal('13.00'), 'bid_time': datetime.datetime(2021, 4, 9, 16, 15, 9, 120168, tzinfo=<UTC>), 'is_winning_bid': False}]>
Views.py
#login_required(login_url="/login")
def listing(request, listing_id):
listing = Listing.objects.get(pk=listing_id)
bids = Bid.objects.filter(listing_id=listing_id)
user_id = request.user
# time_posted = Comment.time_posted
comments = Comment.objects.filter(listing_id=listing_id, user_id=user_id).order_by("-time_posted")
current_user = request.user
return render(request, "auctions/listing.html", {
"listing": listing,
"watchlist": Watchlist.objects.filter(user_id=request.user).count(),
"current_user": current_user,
"comments": comments,
"bids": bids.values()
})
template extract:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="block my-3">
<div class="row my-1">
<div class="col-sm-2">
{{ bids }}
</div>
<div class="col-sm-4">
<strong>Number of bids:</strong> {{ listing.number_of_bids }}<br>
<strong>Starting Bid:</strong> {{ listing.starting_bid }}<br>
{% if listing.current_bid == 0 %}
<strong>Current Bid:</strong> <span class="current_bid">No Bid Yet!</span><br>
{% else %}
<strong>Current Bid:</strong> <span class="current_bid">{{ listing.current_bid }}</span><br>
{% endif %}
</div>
<div class="col-sm-5 text-center">
<form action="{% url 'auctions:bid' listing.id %}" method="post">
{% csrf_token %}
<input type="number" name="bid_amount" id="bid_input" required>
<button class="btn btn-primary" type="submit">Bid</button>
<br>
</form>
<a href="{% url 'auctions:add_to_watchlist' listing.id %}" style="background-color: black"
class="badge badge-secondary">
Add to Watchlist
</a>
<div class="col-sm-2"></div>
</div>
</div>
</div>
</body>
</html>
As I understand you want to retrieve only is_winning_bid values from database. To do so, look at the below codes.
In view:
bid_winnings = Bid.objects.filter(listing_id=listing_id).values('is_winning_bid')
In template:
{% for w in bid_winnings %}
{{ w.is_winning_bid }}
{% endfor %}
Related
I am having a problem in categorize Posts. I have categories in Post Model, Please help me solve this issue!
MODELS.PY
html= "html"
css= "css"
python= "python"
javascript = "javascript"
Lang=(
(html,"HTML"),
(css,"CSS"),
(python,"PYTHON"),
(javascript,"JAVASCRIPT")
)
Broilerplate = "Broilerplate"
Simple_Tags = "Simple Tags"
Elements = "Elements"
Webpages = "Webpages"
Category = (
(Broilerplate,"BROILERPLATE"),
(Simple_Tags,"Simple tags"),
(Elements,"Elements"),
(Webpages,"Webpages")
)
class Post(models.Model):
title = models.CharField(max_length=75)
subtitle = models.CharField(max_length=150)
language_1 = models.CharField(max_length=100, choices=Lang, default=html)
content_1= models.TextField(blank=True)
language_2 = models.CharField(max_length=100, choices=Lang,blank=True)
content_2= models.TextField(blank=True)
language_3 = models.CharField(max_length=100, choices=Lang,blank=True)
content_3= models.TextField(blank=True)
language_4 = models.CharField(max_length=100, choices=Lang,blank=True)
content_4= models.TextField(blank=True)
language_5 = models.CharField(max_length=100, choices=Lang,blank=True)
content_5= models.TextField(blank=True)
category= models.CharField(max_length=100, choices=Category, default=Broilerplate)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.title
# def update(self):
# updated_at = timezone.now()
# self.save(updated_at)
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk':self.pk})
VIEWS.PY
def search_by_category(request, category):
if request.post.objects.filter(pk=request.post.id).first().category == 'Broilerplate':
nor = request.post.objects.filter(pk=request.post.id).first().category
print(nor)
posts = Post.objects.filter(category='Broilerplate')
category = posts.first().category
print(category)
context = {'posts': posts, 'title': category , 'category': category}
return render(request, 'category.html', context)
else:
context = {'title': category , 'category': category}
return render(request, 'category.html', context)
URLS.PY
urlpatterns = [
path('html/',PostListView.as_view(), name='CodeWriter_Homepage'),
path('python/',views.CodeWriter_homepage_python, name='CodeWriter_Homepage_python'),
path('search/', views.search, name='search'),
path('categroize-by/<str:category>/', views.search_by_category, name='search_by_category'),
path('post-details/<int:pk>/',PostDetailView.as_view(), name='Post_details_page'),
path('post-update/<int:pk>/',PostUpdateView.as_view(), name='Post_update_page'),
path('post-delete/<int:pk>/',PostDeleteView.as_view(), name='Post_delete_page'),
path('user/<str:username>/', UserPostListView.as_view(), name='user-post'),
path('new-post/',PostCreateView.as_view(), name='New-post_page')
]
CATEGORY.html
How can I get the data of the post category in views.py?That will help me very much!
{% block main_post_body %}
<main class="post-body normal" >
<p class="post-heading"> Post for <b>{{ category }}</b> :</p>
{% comment %} <h1 class="mb-3">Search results for <b>{{category}}</b>: </h1> {% endcomment %}
{% comment %} {% if posts|length < 1 %}
<h3>No search results found</h3>
<p>Your search results for <b>{{ query }}</b> is not found.</p>
{% endif %} {% endcomment %}
{% for post in posts %}
<div class="row">
<div class="col span-8-of-12 card">
<div class="row">
<!-- <div class="triangle"></div>
<div class="person-info-card">
<div class="row">
<div class="col"><img src="{% static 'resoures/css/img/Me.jpg' %}" alt=""></div>
<div class="col">
<p>Ketan Vishwakarma</p>
<p class="post-no">126 Posts | 1k Followers</p>
</div>
</div>
</div> -->
<div class="col span-1-of-12">
<div class="person-img" id="person-info-card-toggle">
<img src="{{ post.author.profile.image.url }}" alt="" />
</div>
</div>
<div class="col span-7-of-12">
<h3>{{ post.title }} </h3>
<h4>{{ post.subtitle }}</h4>
</div>
<div class="col span-1-of-12">
<span class="ion-md-heart-empty"></span>
</div>
<div class="col span-1-of-12">
<span class="ion-md-add-circle-outline"></span>
</div>
<div class="col span-1-of-12 share">
<span class="ion-md-share"></span>
<ul class="dropdown-list-share">
<li><span class="ion-md-copy"> Copy</span></li>
<li><span class="ion-logo-whatsapp"> Share on Whatsapp</span></li>
<li><span class="ion-logo-facebook"> Share on facebook</span></li>
<li><span class="ion-md-more"> More</span></li>
</ul>
</div>
<div class="col span-1-of-12">
<span class="ion-md-menu"></span>
<ul class="dropdown-list">
<li>Doesn't work</li>
<li>Report</li>
<li>Report</li>
</ul>
</div>
</div>
<div class="tabs">
<ul class="tabs-list">
<li class="active">{{ post.language_1 }}</li>
{% if post.content_2 == "" %}
{% else %}
<li class="not-clickable hint--info" aria-label="To view this click Read more">{{ post.language_2 }}</li>
{% endif %}
{% if post.content_3 == "" %}
{% else %}
<li class="not-clickable hint--info" aria-label="To view this click Read more">{{ post.language_3 }}</li>
{% endif %}
{% if post.content_4 == "" %}
{% else %}
<li class="not-clickable hint--info" aria-label="To view this click Read more">{{ post.language_4 }}</li>
{% endif %}
{% if post.content_5 == "" %}
{% else %}
<li class="not-clickable hint--info" aria-label="To view this click Read more">{{ post.language_5 }}</li>
{% endif %}
<ul class="categories">
<abbr title="Categiores">
<a href="">
<span class="ion-md-code-working"></span>
{{ post.category }}
</a>
</abbr>
<!-- <li>Broilerplate</li> -->
</ul>
</ul>
<div id="tab1" class="tab active">
<p>
<pre><code class="language-{{ post.language_1 }}">
{{ post.content_1 }}
</code></pre>
</p>
</div>
<div id="tab2" class="tab">
<p>
<pre><code class="language-{{ post.language_2 }}">
{{ post.content_2 }}
</code></pre>
</p>
</div>
<div id="tab3" class="tab">
<p>
<pre><code class="language-{{ post.language_3 }}">
{{ post.content_3 }}
</code></pre>
</p>
</div>
<div id="tab4" class="tab">
<p>
<pre><code class="language-{{ post.language_4 }}">
{{ post.content_4 }}
</code></pre>
</p>
</div>
<div id="tab5" class="tab">
<p>
<pre><code class="language-{{ post.language_5 }}">
{{ post.content_5 }}
</code></pre>
</p>
</div>
</div>
<span class="ion-md-arrow-round-down"> Read More</span>
<h6>{{ post.date_posted|date:"F d, Y" }}</h6>
</div>
<div class="col span-4-of-12 main-card ">
<div class="card-small">
<h1>Result: </h1>
<div class="result-box">
<iframe src="" frameborder="0">just for fun</iframe>
</div>
<h6>{{ post.date_posted|date:"F d, Y" }}</</h6>
</div>
</div>
</div>
{% endfor %}
</main>
{% if is_paginated %}
{% if page_obj.has_previous %}
<a class="btn btn-outline-info mb-4" href="?page=1">First</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a>
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
<a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a>
{% endif %}
{% endif %}
{% endblock main_post_body %}
NoteI have registered the Post model in admin.py
Tell me the solution to this problem I cannot get the solution I have been trying it for so long and am stuck on this.
I am using bootstrap tabs navigation bar and I want to retrieve the id of the tag and pass it to my view but my main issue though is I am not using them in my urls.py. Here is my urls.py file.
from django.urls import path
from .views import (
index, add_task, update_task,
delete_task, update_categories,
delete_all_task
)
urlpatterns = [
path('', index, name="home"),
path('add-task/', add_task, name="add-task"),
path('update-task/<int:pk>/', update_task, name="update-task"),
path('delete-task/<int:pk>/', delete_task, name="delete-task"),
path('update-category/', update_categories, name="update-category"),
path('delete_all_tasks/', delete_all_task, name="delete_all_tasks"),
]
And here is the views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.forms import modelformset_factory
from .models import Tasks, Category
from .forms import AddTaskForm, UpdateTaskForm, UpdateCategoryForm
def get_task_minid(categories):
id_list = []
for task in categories:
id_list.append(task.id)
min_id = min(id_list)
return min_id
def index(request):
tasks = Tasks.objects.all()
categories = Category.objects.all()
if len(categories) > 1:
min_id = get_task_minid(categories)
if request.method == "POST":
category = request.POST.get('category')
cat = Category.objects.create(name=category)
cat.save()
return redirect('home')
context = {
'tasks': tasks,
'categories': categories,
'min_id': min_id,
}
return render(request, 'Todo/index.html', context)
and here is the index.HTML
<div class="" id="Todo-tasks">
<div class="card card-primary card-outline">
<div class="card-body">
<div class="row">
<div class="col-5 col-sm-3">
<div class="card-header">
<span>All Categories</span>
</div>
<div class="nav flex-column nav-tabs h-100" id="vert-tabs-tab" role="tablist" aria-orientation="vertical">
{% for cat in categories %}
{% if cat.id == min_id %}
<a class="nav-link active" id="vert-tabs-{{cat}}-tab" data-toggle="pill" href="#vert-tabs-{{cat}}"
role="tab" aria-controls="vert-tabs-{{cat}}" aria-selected="true">{{cat}}</a>
{% else %}
<a class="nav-link" id="vert-tabs-{{cat}}-tab" data-toggle="pill" href="#vert-tabs-{{cat}}"
role="tab" aria-controls="vert-tabs-{{cat}}" aria-selected="false">{{cat}}</a>
{% endif %}
{% endfor %}
<div class="card-footer mt-3">
<form action="" method="POST">
{% csrf_token %}
<input type="text" name="category" placeholder="Add category" class="new-input cat" aria-label="Add new category" />
<button type="submit" class="new">+</button>
</form>
</div>
Manage Categories
</div>
</div>
<div class="col-7 col-sm-9">
<div class="tab-content" id="vert-tabs-tabContent">
{% for cat in categories %}
{% if cat.id == min_id %}
<div class="tab-pane text-left fade show active" id="vert-tabs-{{cat}}" role="tabpanel" aria-labelledby="vert-tabs-{{ cat }}-tab">
<ul class="list-unstyled border pb-4">
<div class="card-header d-flex justify-content-between justify-content-center">
{{ cat }}
<div class="form-group">
<form action="" class="p-0 justify-content-end" method="post">
<input type="text" name="search" class="form-input pl-3" placeholder="Search for tasks..."/>
</form>
</div>
</div>
{% for task in cat.tasks.all %}
<li class="align-content-center"><a>{{task.text}}
<small class="badge bg-success">{{task.due_date|timeuntil|upto:','}}</small>
<span class=""></i></span>
<span class=""></i></span>
</a>
</li>
{% empty %}
<h3 class="alert alert-info m-5"><i class="fas fa-alert-outline"></i> Please add new tasks to categories</h3>
{% endfor %}
</ul>
</div>
{% else %}
<div class="tab-pane text-left fade show" id="vert-tabs-{{cat}}" role="tabpanel" aria-labelledby="vert-tabs-{{ cat }}-tab">
<ul class="list-unstyled border pb-4">
Now, how I am thinking of a way to get the h ref in the like(h ref="vert-tabs-{{cat}}" I want to get the value of the cat variable anytime I switch to a different sort of view or tab content.
Any help would be so appreciated even JavaScript or j query.
Thank you in advance...
I am trying to create a edit form to update the database using Django model Forms but the problem is that edit form part of the sizeProductMap.html page is not rendering when edit form (sizeProductMap_edit) request is made.
My models are as shown below.
models.py
class Product(models.Model):
prod_ID = models.AutoField("Product ID", primary_key=True)
prod_Name = models.CharField("Product Name", max_length=30, null=False)
prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
prod_img = models.ImageField("Product Image", null=True)
def __str__(self):
return "{}-->{}".format(self.prod_ID,
self.prod_Name)
class Size(models.Model):
size_id = models.AutoField("Size ID", primary_key=True, auto_created=True)
prod_size = models.CharField("Product Size", max_length=20, null=False)
def __str__(self):
return "{size_id}-->{prod_size}".format(size_id=self.size_id,
prod_size=self.prod_size)
class SizeProductMapping(models.Model):
size_p_map_id = models.AutoField("Size & Product Map ID", primary_key=True, auto_created=True)
size_id = models.ForeignKey(Size, null=False, on_delete=models.CASCADE, verbose_name="Size ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
def __str__(self):
return ".`. {}_____{}".format(self.size_id,
self.prod_id)
This is the form I used to add and edit the model.
forms.py
from django import forms
from user.models import SizeProductMapping
class SizeProductMapForm(forms.ModelForm):
class Meta:
model = SizeProductMapping
fields = ['size_id', 'prod_id']
Here is the view I created to add ,update and delete the record.
views.py
def sizeProductMap(request):
form = SizeProductMapForm(request.POST, request.FILES)
if request.method == 'POST':
if form.is_valid():
form.save()
return redirect("/admin1/sizeProductMap/")
else:
sizeProductMap_show = SizeProductMapping.objects.all()
# start paginator logic
paginator = Paginator(sizeProductMap_show, 3)
page = request.GET.get('page')
try:
sizeProductMap_show = paginator.page(page)
except PageNotAnInteger:
sizeProductMap_show = paginator.page(1)
except EmptyPage:
sizeProductMap_show = paginator.page(paginator.num_pages)
# end paginator logic
return render(request, 'admin1/sizeProductMap.html', {'sizeProductMap_show': sizeProductMap_show, 'form': form})
def sizeProductMap_delete(request, id):
sizeProductMap_delete = SizeProductMapping.objects.filter(size_p_map_id=id)
sizeProductMap_delete.delete()
return redirect('/admin1/productSizeMap')
def sizeProductMap_edit(request, id):
instance = SizeProductMapping.objects.get(size_p_map_id=id)
form = SizeProductMapForm(instance=instance)
if request.method == 'POST':
form = SizeProductMapForm(request.POST, instance=instance)
if form.is_valid():
form.save()
return redirect('/admin1/sizeProductMap')
return render(request, 'admin1/sizeProductMap.html', {'form': form})
This is my urls.
urls.py
from django.urls import path
from admin1 import views
urlpatterns = [
path('sizeProductMap/', views.sizeProductMap, name="admin-size-product-map"),
path('sizeProductMap_delete/<int:id>', views.sizeProductMap_delete, name="admin-size-product-map-delete"),
path('sizeProductMap_edit/<int:id>', views.sizeProductMap_edit, name="admin-size-product-map-edit"),
]
This is the Html page where I want to display the form according to the page request.
sizeProductMap.html
{% extends 'admin1/layout/master.html' %}
{% block title %}Size Product Map{% endblock %}
{% block main %}
<h1>
<center>Size Product Map</center>
</h1>
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10">
{% if sizeProductMap_show %}
<button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add
Size Product Mapping
</button>
<div class="modal fade" id="modal-primary">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Size Product Mapping</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body mt-2">
<form action="{% url 'admin-size-product-map'%}" method="POST"
enctype="multipart/form-data">
{% csrf_token %}
<table border="1" class="table table-bordered border border-info">
<tr>
<th>
{{form.size_id.label_tag}}
</th>
<td>{{form.size_id}}</td>
</tr>
<tr>
<th>
{{form.prod_id.label_tag}}
</th>
<td>
{{form.prod_id}}
</td>
</tr>
</table>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-outline-light" data-dismiss="modal">Close
</button>
</div>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<div class="container-fluid ">
<div class="row">
<div class="card mt-2 border border-secondary">
<div class="card-header">
<h3 class="card-title ">Size Product Map Table</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table class="table table-bordered border border-info">
<thead>
<tr>
<th>Size Product Mapping Id</th>
<th>Product ID</th>
<th>Size ID</th>
<th>Action</th>
</tr>
</thead>
<tbody class="justify-content-center">
{% for x in sizeProductMap_show %}
<tr>
<td>{{x.size_p_map_id}}</td>
<td>{{x.prod_id}}</td>
<td>{{x.size_id}}</td>
<td><a href="{% url 'admin-size-product-map-edit' x.size_p_map_id %}"
class="btn btn-outline-primary mt-2"><i
class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<a href="{% url 'admin-size-product-map-delete' x.size_p_map_id %}"
class="btn btn-outline-danger mt-2"><i
class="fa fa-trash" aria-hidden="true"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer clearfix ">
<ul class="pagination pagination-sm m-0 justify-content-center">
{% if sizeProductMap_show.has_previous %}
<li class="page-item"><a class="page-link"
href="?page={{sizeProductMap_show.previous_page_number}}">
Previous </a>
</li>
{% endif%}
{% for x in sizeProductMap_show.paginator.page_range %}
{% if sizeProductMap_show.number == x %}
<li class="page-item active"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% else%}
<li class="page-item"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% endif %}
{% endfor %}
{% if sizeProductMap_show.has_next %}
<li class="page-item"><a class="page-link"
href="?page={{sizeProductMap_show.next_page_number}}">
Next </a>
</li>
{% endif %}
</ul>
</div>
</div>
<!-- /.card -->
</div>
</div>
{% endif %}
{% if sizeProductMap_edit %}
<form action="{% url 'admin-size-product-map-edit' x.size_p_map_id %}" method="POST">
{% csrf_token %}
{{form.size_id}}
{{form.prod_id}}
</form>
{% endif %}
</div>
</div>
</div>
{% endblock %}
And if it is possible to reduce the number of line of code please also help. Thanks in advance.
I've found out the answer. There was a really a silly mistake by me.
In the sizeProductMap.html there is a mistake let me point out that:
sizeProductMap.html
{% if sizeProductMap_edit %}
<form action="{% url 'admin-size-product-map-edit' x.size_p_map_id %}" method="POST">
{% csrf_token %}
{{form.size_id}}
{{form.prod_id}}
</form>
{% endif %}
Here I am checking for instance {% if sizeProductMap_edit %} this is the wrong thing.
I have to check {% if instance %} according to my views.py.
In my django project, I have an HTML that renders questions header, and inside the question headers I have question items. In my model, Question headers and items are two different entities. I need to show for every header, just the items related to that header. As it shows all items for all questions without any filters. Greatly appreciate any help!
Model:
class Question(models.Model):
question = models.CharField(max_length=240)
mission_section = models.ForeignKey('Mission_Section', on_delete=models.CASCADE)
type_question = models.ForeignKey('Type_Question', on_delete=models.CASCADE)
categories_question = models.ForeignKey('Categories_Question', on_delete=models.CASCADE, default=1)
order = models.IntegerField(default=1)
def __str__(self):
return self.question
class Question_Option(models.Model):
question = models.ForeignKey('Question', on_delete=models.CASCADE,default=1)
option = models.CharField(max_length=240)
correct = models.BooleanField()
order = models.IntegerField(default=1)
View:
class Questions(LoginRequiredMixin, FormView):
template_name = "questions.tmpl"
def get(self, request, pk):
context = {
'pk': pk,
'section': Mission_Section.objects.get(pk = pk ),
'questions_items': Question_Option.objects.filter(question__mission_section__pk=pk).order_by('order','pk'),
'questions': Question.objects.filter(mission_section__pk = pk ),
'question_types' : Type_Question.objects.all(),
'questions_categories': Categories_Question.objects.all()}
return render(self.request, self.template_name, context)
HTML
<input type="hidden" class="form-control" id="section" name="section" value="{{section.id}}" required>
<h1>{{ section.name }}</h1>
<div id="contentDiv">
<ol>
{% for question in questions %}
<div name="question" class="form-group" id="question-{{question.id}}" >
<form class='my-ajax-form' id="form-question-{{question.id}}" method='GET' action='.' data-url='{{ request.build_absolute_uri|safe }}'>
<li><div class="input-group">
{% csrf_token %}
{{ form.as_p }}
<input type="text" value= "{{question.id}}" id="question" name="question-hidden" class="form-control">
<input type="text" value= "{{question.question}}" id="question_name_{{question.id}}" class="form-control" aria-label="Amount" onchange="UpdateQuestion({{question.id}})">
</div>
</form>
<br>
<!-- Options -->
<div id = "question_content_{{question.id}}" name="question-options" class="collapse">
<ol class="example list-group">
{% for qi in questions_items %}
<li class="list-group-item d-flex justify-content-between align-items-center" id={{qi.id}} name="opt-{{question.id}}-{{qi.id}}" onclick="setCorrect({{qi.id}},{{question.id}})" contenteditable="true">{{ qi.option }}
<span class="badge badge-warning badge-pill">-</span>
</li>
{% endfor %} </ol>
<div>
<div class="d-flex justify-content-center">Add Option</div>
<div class="d-flex justify-content-center"> <br><i class="fa fa-plus-circle fa-1x" aria-hidden="true"></i></div>
</div>
</div>
</div></li>
{% endfor %} </ol>
using this answer I figured it out Double loop in Django template
What I need is:
<div id = "question_content_{{question.id}}" name="question-options" class="collapse">
{% csrf_token %}
{{ form.as_p }}
<form class='ajax-form-option' id="form-option-{{question.id}}" method='GET' action='.' data-url='{{ request.build_absolute_uri|safe }}'>
<ol class="example list-group">
{% for qi in question.question_option_set.all %}
<li class="list-group-item d-flex justify-content-between align-items-center" id=option-{{qi.id}} name="opt-{{question.id}}-{{qi.id}}">
<div contenteditable="true">{{ qi.option }}</div>
<div>
<button type="button" name='option-check' class="btn btn-light" value={{qi.id}} id="check-option-{{question.id}}-{{qi.id}}">
<i class="fas fa-check"></i>
</button>
<button type="button" class="btn btn-warning" id="delete-option-{{question.id}}-{{qi.id}}" onclick="deleteOption({{qi.id}})">
<i class="fa fa-trash" aria-hidden="true"></i>
</button>
</div>
</li>
{% endfor %} </ol>
<div onclick="CreateOption({{question.id}})">
<div class="d-flex justify-content-center">Add Option</div>
<div class="d-flex justify-content-center"> <br><i class="fa fa-plus-circle fa-1x" aria-hidden="true"></i></div>
</div>
</form>
views.py
#login_required()
def Info_anlegen(request, id=None):
item = get_object_or_404(Kunden, id=id)
kontaktform_form = InfoForm(request.POST or None, instance=item)
if WindowsHome.objects.filter(KN=item.KN).exists():
item1 = WindowsHome.objects.get(KN=item.KN)
winform_form = InfoWinForm(request.POST or None, instance=item1)
if kontaktform_form.is_valid():
return redirect('/Verwaltung/KontaktAnlegen')
else:
form = acroniform(instance=item)
return render(request, 'blog/infokontakt.html',
{'kontaktform_form': kontaktform_form, 'winform_form': winform_form})
infokontakt.html
{% extends 'blog/base.html' %}
{% load bootstrap4 %}
{% block supertitle %} InfoPage {% endblock %}
{% block Content %}
{% load static %}
<html>
<div class="p-2 mb-1 bg-white text-black">
<head>
<div class="d-flex justify-content-center align-items-center container ">
<img src="{% static 'blog/Gubler.jpeg' %}" alt="Gubler" height="300" width="700">
</div>
</head>
<br>
<body>
<form class="form-row" action="" method="post">
<div style="margin-left: 2.5em;">
<font color="black">
<div class="col-sm-10 col-form-label">
{% csrf_token %}
{% bootstrap_form kontaktform_form %}
</div>
</font>
</div>
</form>
<form class="form-row" action="" method="post">
<div style="margin-left: 2.5em;">
<font color="black">
<div class="col-sm-10 col-form-label">
{% csrf_token %}
{% bootstrap_form winform_form %}
</div>
</font>
</div>
</form>
My Problem is:
if WindowsHome.KN exists it gets displayed
but if it does not exist i get the error
UnboundLocalError at /Verwaltung/InfoKontakt/6
local variable 'winform_form' referenced before assignment
Request Method: GET
Request URL: http://127.0.0.1:8000/Verwaltung/InfoKontakt/6
Django Version: 3.0.1
Exception Type: UnboundLocalError
Exception Value:
local variable 'winform_form' referenced before assignment
How do i say that if the db entry does not exist it should not display the form ?
OR
if the db entry does not exist just display a spacing " "
You try to send winform_form to your template but it is not set when WindowsHome.objects.filter(KN=item.KN).exists() is false.
You should probably do something like this:
#login_required()
def Info_anlegen(request, id=None):
context = {}
item = get_object_or_404(Kunden, id=id)
kontaktform_form = InfoForm(request.POST or None, instance=item)
if WindowsHome.objects.filter(KN=item.KN).exists():
item1 = WindowsHome.objects.get(KN=item.KN)
winform_form = InfoWinForm(request.POST or None, instance=item1)
context['winform_form'] = winform_form
if kontaktform_form.is_valid():
return redirect('/Verwaltung/KontaktAnlegen')
else:
form = acroniform(instance=item)
context['kontaktform_form'] = kontaktform_form
return render(request, 'blog/infokontakt.html', context)
You can initialize winform_form as None in the begining of your method, so that it will not throw that error. (i.e)
def Info_anlegen(request, id=None):
winform_form = None # Do like this
item = get_object_or_404(Kunden, id=id)
and also in your template you can use django template tags {% if %} ... {% endif %}
i.e
{% if winform_form %}
<form class="form-row" action="" method="post">
<div style="margin-left: 2.5em;">
<font color="black">
<div class="col-sm-10 col-form-label">
{% csrf_token %}
{% bootstrap_form winform_form %}
</div>
</font>
</div>
</form>
{% endif %}