我有一个Django表单,它与一个模型相对应,允许用户从他的观察列表中添加或删除一个项目。我希望提交按钮说";添加到监视列表";如果用户没有将该项目添加到他的观察列表中;从监视列表中删除";如果列表已经在用户的观察列表中。目前,按钮显示";从监视列表中删除";(无论是否已添加)并更改为";添加到监视列表";一旦点击一次。然后按钮不会改变。
html
<form action = "{% url 'listing' auction_listing.id %}" method = "POST">
{% csrf_token %}
{{ watchlistForm }}
{% if watchlist %}
<input type = "submit" value = "{{ watchlist }}">
{% else %}
<input type = "submit" value = "Remove from Watchlist">
{% endif %}
</form>
views.py
@login_required(login_url='login')
def listing(request, id):
#gets listing
listing = get_object_or_404(Listings.objects, pk=id)
#code for comment and bid forms
listing_price = listing.bid
sellar = listing.user
comment_obj = Comments.objects.filter(listing=listing)
#types of forms
comment_form = CommentForm()
bid_form = BidsForm()
watchlist_form = WatchListForm()
closelisting_form = CloseListingForm()
#comment_form = CommentForm(request.POST)
#watchlist_form = WatchListForm(request.POST)
#bid_form = BidsForm(request.POST)
#code for the bid form
bid_obj = Bids.objects.filter(listing=listing)
other_bids = bid_obj.all()
max_bid =0
for bid in other_bids:
if listing.bid > max_bid:
max_bid = listing.bid
#checks if request method is post for all the forms
if request.method == "POST":
comment_form = CommentForm(request.POST)
bid_form = BidsForm(request.POST)
watchlist_form = WatchListForm(request.POST)
closelisting_form = CloseListingForm(request.POST)
#checks if comment form is valid
if comment_form.is_valid():
comment = comment_form.save(commit=False)
comment.listing = listing
comment.user = request.user
comment.save()
#checks if bid form is valid
if bid_form.is_valid():
new_bid = bid_form.cleaned_data.get("bid")
if (new_bid >= listing_price) and (new_bid > max_bid):
bid = bid_form.save(commit=False)
bid.listing = listing
bid.user = request.user
bid.save()
else:
return render(request, "auctions/listing.html",{
"auction_listing": listing,
"form": comment_form,
"comments": comment_obj,
"bidForm": bid_form,
"bids": bid_obj,
"message": "Your bid needs to be equal or greater than the listing price and greater than any other bids.",
"watchlistForm": watchlist_form
})
#checks if watchlist form is valid
if watchlist_form.is_valid():
if watchlist_form.instance.add_to_watchlist == False:
watchlist_form.instance.user = request.user
watchlist_form.instance.add_to_watchlist = True
watchlist = watchlist_form.save()
watchlist.listings.add(listing)
return render(request, "auctions/listing.html",{
"auction_listing": listing,
"form": comment_form,
"comments": comment_obj,
"bidForm": bid_form,
"bids": bid_obj,
"watchlistForm": watchlist_form,
"watchlist": "Add to Watchlist"
})
#return redirect('listing', id=id)
else:
watchlist_form.instance.user = request.user
watchlist_form.instance.add_to_watchlist = False
watchlist = watchlist_form.save()
watchlist.listings.delete(listing)
return redirect('listing', id=id)
#checks if closelisting form is valid
if closelisting_form.is_valid():
return render(request, "auctions/listing.html",{
"auction_listing": listing,
"form": comment_form,
"comments": comment_obj,
"bidForm": bid_form,
"bids": bid_obj,
"watchlistForm": watchlist_form
})
#what to do if none of the forms are submitted
else:
return render(request, "auctions/listing.html",{
"auction_listing": listing,
"form": comment_form,
"comments": comment_obj,
"bidForm": bid_form,
"bids": bid_obj,
"watchlistForm": watchlist_form
})
return render(request, "auctions/listing.html",{
"auction_listing": listing,
"form": comment_form,
"comments": comment_obj,
"bidForm": bid_form,
"bids": bid_obj,
"watchlistForm": watchlist_form
})
型号.py
class Listings(models.Model):
CATEGORY = [
("Miscellaneous", "Miscellaneous"),
("Movies and Television", "Movies and Television"),
("Sports", "Sports"),
("Arts and Crafts", "Arts and Crafts"),
("Clothing", "Clothing"),
("Books", "Books"),
]
title = models.CharField(max_length=64)
description = models.CharField(max_length=500)
bid = models.DecimalField(max_digits=1000000000000, decimal_places=2)
image = models.URLField(null=True, blank=True)
category = models.CharField(max_length=64, choices=CATEGORY, default=None)
user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
class Comments(models.Model):
listing = models.ForeignKey(Listings, on_delete=models.CASCADE, default="")
user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
comment = models.CharField(max_length=500)
class Bids(models.Model):
listing = models.ForeignKey(Listings, on_delete=models.CASCADE, default="")
user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
bid = models.DecimalField(max_digits=1000000000000, decimal_places=2)
class WatchList(models.Model):
listings = models.ManyToManyField(Listings)
user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
add_to_watchlist = models.BooleanField(default=False)
class CloseListing(models.Model):
listings = models.ForeignKey(Listings, on_delete=models.CASCADE, default="")
user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
close_listing = models.BooleanField(default=False, null=False)
watchListForm
class WatchListForm(forms.ModelForm):
class Meta:
model = WatchList
fields = ['add_to_watchlist']
widgets = {'add_to_watchlist': forms.HiddenInput()}
以下是我正在使用的当前代码,它仍然不能解决更改按钮的问题。
views.py
@login_required(login_url='login')
def listing(request, id):
#gets listing
listing = get_object_or_404(Listings.objects, pk=id)
#code for comment and bid forms
listing_price = listing.bid
sellar = listing.user
comment_obj = Comments.objects.filter(listing=listing)
#types of forms
comment_form = CommentForm()
bid_form = BidsForm()
#watchlist_form = WatchListForm()
closelisting_form = CloseListingForm()
#watchlist code
add_or_remove_watchlist = ''
try:
has_watchlists = get_object_or_404(WatchList, Q(
user=request.user) & Q(listing=listing))
except:
has_watchlists = False
if has_watchlists:
add_or_remove_watchlist = True
else:
add_or_remove_watchlist = False
#code for the bid form
bid_obj = Bids.objects.filter(listing=listing)
other_bids = bid_obj.all()
max_bid =0
for bid in other_bids:
if listing.bid > max_bid:
max_bid = listing.bid
#watchlist code
if request.POST.get('add'):
WatchList.objects.create(user=request.user, listing=listing)
add_or_remove_watchlist = False
elif request.POST.get('remove'):
add_or_remove_watchlist = True
has_watchlist.delete()
#checks if request method is post for all the forms
if request.method == "POST":
comment_form = CommentForm(request.POST)
bid_form = BidsForm(request.POST)
closelisting_form = CloseListingForm(request.POST)
#checks if comment form is valid
if comment_form.is_valid():
comment = comment_form.save(commit=False)
comment.listing = listing
comment.user = request.user
comment.save()
#checks if bid form is valid
if bid_form.is_valid():
new_bid = bid_form.cleaned_data.get("bid")
if (new_bid >= listing_price) and (new_bid > max_bid):
bid = bid_form.save(commit=False)
bid.listing = listing
bid.user = request.user
bid.save()
else:
return render(request, "auctions/listing.html",{
"auction_listing": listing,
"form": comment_form,
"comments": comment_obj,
"bidForm": bid_form,
"bids": bid_obj,
"message": "Your bid needs to be equal or greater than the listing price and greater than any other bids."
})
#checks if closelisting form is valid
if closelisting_form.is_valid():
return render(request, "auctions/listing.html",{
"auction_listing": listing,
"form": comment_form,
"comments": comment_obj,
"bidForm": bid_form,
"bids": bid_obj
})
#what to do if none of the forms are submitted
else:
return render(request, "auctions/listing.html",{
"auction_listing": listing,
"form": comment_form,
"comments": comment_obj,
"bidForm": bid_form,
"bids": bid_obj
})
return render(request, "auctions/listing.html",{
"auction_listing": listing,
"form": comment_form,
"comments": comment_obj,
"bidForm": bid_form,
"bids": bid_obj
})
listing.html
{% block body %}
<img src ="{{ auction_listing.image }}" style = "height: 10%; width: 10%;">
<h4 class = "text">{{ auction_listing.title }}</h4>
<h6>Description: {{ auction_listing.description }}</h6>
<h6>Category: {{ auction_listing.category }}</h6>
<h6>By: {{ auction_listing.user }}</h6>
<h6>Price: ${{ auction_listing.bid }}</h6>
{% if closeListingForm %}
<form action = "{% url 'listing' auction_listing.id %}" method = "POST">
{% csrf_token %}
{{ closeListingForm }}
</form>
{% endif %}
<!--watchlist form-->
{% if watchlist_message %}
<div>{{ watchlist_message }}</div>
{% endif %}
<form action = "{% url 'listing' auction_listing.id %}" method = "POST">
{% csrf_token %}
{% if watchlist %}
<input type="submit" value='Remove from watchlist' name='remove'>
{% else %}
<input type="submit" value='Add to watchlist' name='add'>
{% endif %}
</form>
<br>
<!--bid form-->
{% if message %}
<div>{{ message }}</div>
{% endif %}
<form action = "{% url 'listing' auction_listing.id %}" method = "POST" name = "newBid">
{% csrf_token %}
{{ bidForm }}
<input type = "submit" value = "Place Bid">
</form>
<br>
{% for bid in bids %}
<h6>${{ bid.bid }} <div style = "font-family: monospace;">Bid By: {{ bid.user }}</div></h6>
{% endfor %}
<!--comment form-->
<br>
<form action = "{% url 'listing' auction_listing.id %}" method = "POST">
{% csrf_token %}
{{ form }}
<input type = "submit" value = "Add Comment">
</form>
<br>
{% for comment in comments %}
<h6> {{ comment.comment }} <div style = "font-family: monospace;">Comment By: {{ comment.user }}</div></h6>
{% endfor %}
{% endblock %}
我已删除WatchListForm。
我有另一种方法,通过在WatchList
模型中将listing
字段创建为ForeignKey
,而不需要使add_to_watchlist
字段。
型号.py
class WatchList(models.Model):
listing = models.ForeignKey(Listings, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE, default='')
管理员.py
from some_app_name.models import WatchList
@admin.register(WatchList)
class WatchListAdmin(admin.ModelAdmin):
list_display = ['id', 'listing', 'user']
listing.html或模板文件:
<form action = "{% url 'listing' auction_listing.id %}" method = "POST">
{% csrf_token %}
{% if watchlist %}
<input type="submit" value='Remove from watchlist' name='remove'>
{% else %}
<input type="submit" value='Add to watchlist' name='add'>
{% endif %}
</form>
views.py
def列表(请求,id):#获取列表listing=get_object_or_404(Listings,pk=id)#评论和投标表格代码listing_price=标价sellar=列出用户comment_obj=注释.objects.filter(listing=列表)#表单类型comment_form=CommentsForm()bid_form=投标表格()closelisting_form=CloseListingForm()""----------------下面的代码正在处理监视列表--------------------"">add_or_remove_watchlist=''尝试:has_watchlists=get_object_or_404(监视列表,Q(user=request.user)&Q(listing=listing))除了:has_watchlists=错误如果has_watchlists:add_or_remove_watchlist=真其他:add_or_remove_watchlist=False""----------------上面的代码正在处理监视列表--------------------""bid_obj=出价.objects.filter(列表=列表)other_bid=bid_obj.all()max_bid=0在其他出价(_B):如果listing.bid>max_bid:max_bid=listing.bid如果request.method=="POST":comment_form=注释表单(request.POST)bid_form=BidsForm(request.POST)closelisting_form=CloseListingForm(request.POST)""----------------下面的代码正在处理监视列表--------------------"">如果请求。POST.get("添加"):WatchList.objects.create(user=request.user,listing=listing)add_or_remove_watchlist=错误elif请求。POST.get("删除"):add_or_remove_watchlist=真has_watchlists.delete()""----------------以上代码正在处理监视列表--------------------""#检查注释表单是否有效如果comment_form.is_valid():comment=comment_form.save(commit=False)comment.listing=列表comment.user=请求.usercomment.save()#检查投标表格是否有效如果bid_form.is_valid():new_bid=bid_form.cleaned_data.get("bid")如果(new_bid>=listing_price)和(new_bid>max_bid):bid=bid_form.save(commit=False)bid.listing=列出bid.user=请求用户bid.save()其他:return render(请求,"拍卖/挂牌.html"{"auction_listing":挂牌,"form":comment_form,"comments":comment_obj,"bidForm":bid_form,"bids":bid_obj,"消息":"你的出价需要等于或大于挂牌价,并且大于任何其他出价。",})如果closelisting_form.is_valid():return render(请求,"拍卖/挂牌.html"{"auction_listing":挂牌,"form":comment_form,"comments":comment_obj,"bidForm":bid_form,"bids":bid_obj,})return redirect('listing',id=id)return render(请求,"拍卖/挂牌.html"{"auction_listing":挂牌,"form":comment_form,"comments":comment_obj,"bidForm":bid_form,"bids":bid_obj,"观察列表":add_or_remove_watchlist})
此外,无需制作WatchListForm
,因此完全删除它。
编辑:尝试以下视图
views.py
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django import forms
from django.contrib.auth.decorators import login_required
from .models import User, Listings, Comments, Bids, WatchList, CloseListing
from .forms import ListingsForm, CommentForm, BidsForm, CloseListingForm
from django.shortcuts import get_object_or_404, redirect
from django.db.models import Q #you have not import Q
@login_required(login_url='login')
def listing(request, id):
# gets listing
listing = get_object_or_404(Listings, pk=id)
# code for comment and bid forms
listing_price = listing.bid
sellar = listing.user
comment_obj = Comments.objects.filter(listing=listing)
# types of forms
comment_form = CommentForm()
bid_form = BidsForm()
#watchlist_form = WatchListForm()
closelisting_form = CloseListingForm()
# watchlist code
add_or_remove_watchlist = ''
try:
has_watchlists = get_object_or_404(WatchList, Q(
user=request.user) & Q(listing=listing))
print('--------------------------')
print(has_watchlists)
print('--------------------------')
except:
has_watchlists = False
if has_watchlists:
add_or_remove_watchlist = True
else:
print('it will from remove')
add_or_remove_watchlist = False
# code for the bid form
bid_obj = Bids.objects.filter(listing=listing)
other_bids = bid_obj.all()
max_bid = 0
for bid in other_bids:
if listing.bid > max_bid:
max_bid = listing.bid
# checks if request method is post for all the forms
if request.method == "POST":
comment_form = CommentForm(request.POST)
bid_form = BidsForm(request.POST)
closelisting_form = CloseListingForm(request.POST)
# watchlist code
if request.POST.get('add'):
WatchList.objects.create(user=request.user, listing=listing)
add_or_remove_watchlist = False
elif request.POST.get('remove'):
add_or_remove_watchlist = True
has_watchlists.delete()
# checks if comment form is valid
if comment_form.is_valid():
comment = comment_form.save(commit=False)
comment.listing = listing
comment.user = request.user
comment.save()
else:
return redirect('listing', id=id)
# checks if bid form is valid
if bid_form.is_valid():
new_bid = bid_form.cleaned_data.get("bid")
if (new_bid >= listing_price) and (new_bid > max_bid):
bid = bid_form.save(commit=False)
bid.listing = listing
bid.user = request.user
bid.save()
else:
return render(request, "auctions/listing.html", {
"auction_listing": listing,
"form": comment_form,
"comments": comment_obj,
"bidForm": bid_form,
"bids": bid_obj,
"message": "Your bid needs to be equal or greater than the listing price and greater than any other bids."
})
else:
return redirect('listing', id=id)
# checks if closelisting form is valid
if closelisting_form.is_valid():
return render(request, "auctions/listing.html", {
"auction_listing": listing,
"form": comment_form,
"comments": comment_obj,
"bidForm": bid_form,
"bids": bid_obj
})
else:
return redirect('listing', id=id)
return render(request, "auctions/listing.html", {
"auction_listing": listing,
"form": comment_form,
"comments": comment_obj,
"bidForm": bid_form,
"bids": bid_obj,
"watchlist": add_or_remove_watchlist
})
试试这个:
<form action = "{% url 'listing' auction_listing.id %}" method = "POST">
{% csrf_token %}
{{ watchlistForm }}
{% if auction_listing.add_to_watchlist == True %}
<button type="submit">Remove From Watchlist</button> //You may use input instead of button here, I just use button for customizability
{% elif auction_listing.add_to_watchlist == False %}
<button type="submit">Add to Watchlist</button>
{% endif %}
</form>