Im having problem with one line of code... Im trying to check which decimal is greater, i checked few answers from stackoverflow and they didnt work (probably cuz they were from 7 years ago :P) anyways here is my view:
auction = all_auctions.objects.get(id= my_id)
comment_num = auction.comments.all().count()
all_comments = auction.comments.all()
context = {
"auction": auction,
"bid_auction": auction.bid.all(),
"comment_num": comment_num,
"all_comments": all_comments
}
if request.method == "POST" and "bid" in request.POST:
if request.user.is_authenticated:
highest_bid = request.POST["bid"]
if not Decimal(highest_bid) <= Decimal(int(auction.bid.all().reverse()[0])):
all_bid = bids.objects.create(bid = highest_bid)
auction.bid.add(all_bid)
if request.method == "POST" and "watch"in request.POST:
if request.user.is_authenticated:
if auction not in request.user.watchlist.all():
request.user.watchlist.add(auction)
else:
request.user.watchlist.remove(auction)
if request.method == "POST" and "comment" in request.POST:
comment = request.POST["comment"]
if request.user.is_authenticated:
comment_now = comments.objects.create(comment = comment)
auction.comments.add(comment_now)
return render(request, "auctions/dynamic_auction.html", context)
and there is the problematic line:
if not Decimal(highest_bid) <= Decimal(int(auction.bid.all().reverse()[0])):
in models:
from django.contrib.auth.models import AbstractUser
from django.db import models
class comments(models.Model):
comment = models.TextField(blank=False)
class bids(models.Model):
bid = models.DecimalField(decimal_places = 2, max_digits = 100000)
class all_auctions(models.Model):
category = models.CharField(max_length= 14, default = "none")
title = models.CharField(max_length= 14)
description = models.TextField(blank=False)
photo_url = models.CharField(max_length= 500000)
bid = models.ManyToManyField(bids, blank = True, related_name = "bid_auction")
comments = models.ManyToManyField(comments, blank = True, related_name = "comments")
class User(AbstractUser):
created = models.ManyToManyField(all_auctions, blank = True, related_name = "created")
watchlist = models.ManyToManyField(all_auctions, blank = True, related_name = "watchlist")
user_bid = models.ManyToManyField(bids, blank = True, related_name = "user_bid")
and in the template where i can place bids and view them:
{% extends "auctions/layout.html" %}
{% block body %}
<div>
<h2>{{auction.title}}</h2>
<div style = "width: 1400px; padding: 10px; margin: 10px;" class = auction_class>
<img src="{{auction.photo_url}}" alt="no image">
<div>
{{auction.description}}
<p></p>
{% for bid in bid_auction %}
{% if forloop.last %}
bid:{{bid.bid}}
{% endif %}
{% endfor %}
<p></p>
{{auction.category}}
<p></p>
{% if user.is_authenticated %}
<form method = "POST"> {% csrf_token %}
<input class="btn btn-primary" type="submit" name = "watch" value="Add to watchlist">
</form>
<form method = "POST"> {% csrf_token %}
<div>
<input style = "margin:10px;" class="form-control" name = "bid" type="text" placeholder= "Bid...">
<input class="btn btn-primary" type="submit" value="Place Bid">
</div>
</form>
<form method = "POST"> {% csrf_token %}
<div>
<input style = "margin:10px;" class="form-control" name = "comment" type="text" placeholder= "Comment...">
</div>
</form>
{% endif %}
<p></p>
comments:
<p></p>
{% if comment_num == 0 %}
no comments
{% endif %}
<p></p>
<p></p>
{% for com in all_comments %}
{{ com.comment }}
<p></p>
{% endfor %}
</div>
</div>
</div>
{% endblock %}
and yes i made it so the last object of the bids queryset is shown, i have no idea how to show the biggest one, so also i would appreciate help with that . thanks :D
I guess this:
if not Decimal(highest_bid) <= Decimal(int(auction.bid.all().reverse()[0].bid)):
should work (note .bid in the end).
And why you can't use [-1]?
Although I haven't worked with django alot but since you want to compare decimals you could technically create a class which inherits the class Decimal() and then return a float and compare that float. Although I think this won't work (I haven't tried it because I don't like django in particular) but this could be a possibility.
EDIT:
Use a function to return a float from the class.
Example Code:
class DecimalNumber(Decimal):
def __init__(self, value, par2...):
self.value = value
...
def return_float(self):
float = self.value
return float
Related
I have a problem adding a delete functionality to my simple django project which is a todoapp. The problem is when i press the delete button it redirect me to the same page but the item is not deleted. Can someone explain to me what is happening on my code?
This is my code solution but still does not work.
This is my views.py
def index(request, id):
ls = ToDoList.objects.get(id=id)
p = request.POST
if request.method == "POST":
if p.get("save"):
for item in ls.item_set.all():
item_id = str(item.id)
if "clicked" == p.get("c" + item_id):
item.complete = True
else:
item.complete = False
if p.get("text" + item_id) in p:
item.text = p.get("text" + item_id)
if p.get("d" + item_id) == "delete": # Solution
item.delete()
return HttpResponseRedirect("/%i" % ls.id)
item.save()
elif p.get("add"):
new_item = p.get("new")
if new_item:
ls.item_set.create(text=new_item)
else:
return HttpResponse("<strong>Invalid Input</strong>")
return render(request, "todoapp/index.html", {"ls": ls})
models.py
from django.db import models
class ToDoList(models.Model):
date = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Item(models.Model):
toDoList = models.ForeignKey(ToDoList, on_delete=models.CASCADE)
text = models.CharField(max_length=500)
complete = models.BooleanField(default=False)
def __str__(self):
return self.text
index.html
{% extends 'todoapp/base.html' %}
{% block title %}View List{% endblock %}
{% block content %}
<h2>{{ls.name}}</h2>
<form method="post", action="#">
{% csrf_token %}
{% for item in ls.item_set.all%}
<div class="input-group mb-3">
<div class="input-group-prepend">
<div class="input-group-text">
<input class="btn btn-danger btn-sm" type="submit" name="d{{item.id}}" value="delete"> <!-- Solution -->
<input type="checkbox" name="c{{item.id}}" value="clicked" aria-label="Checkbox for following text input" {% if item.complete %} checked {% endif %}>
</div>
</div>
<input type="text" name="text{{item.id}}" value="{{item.text}}" class="form-control" aria-label="Text input with checkbox">
</div>
{% endfor %}
<div class="input-group mb-3">
<div class="input-group-prepend">
<button name="add", value="add", type="submit", class="btn btn-success">Add New</button>
</div>
<input type="text" name="new" value="" class="form-control">
</div>
<br>
<button name="save", value="save", type="submit", class="btn btn-success">Save</button>
</form>
{% endblock %}
I think it should work if you include the delete logic inside another 'if' clause.
if p.get("delete"):
for item in ls.item_set.all():
item_id = str(item.id)
if p.get("d" + item_id) == "delete": # Solution
item.delete()
return HttpResponseRedirect("/%i" % ls.id)
However, I'm not sure what you are trying to achieve as the end result. Here, only one item would get deleted (the item for which 'delete' button was clicked).
My modelform is a dynamically generated modelform,I want to know the type of is_true in the modelForm. The type of the input tag is the checkbook type.
If I know the type=‘checkbox’ of the is_true field, add a class attr to him separately.
The default type='checkbox’ interface is too ugly
models
class Employee(AbstractBaseUser):
"""
用户表
"""
username = models.CharField(max_length=30, verbose_name='姓名')
email = models.EmailField(verbose_name='邮箱', unique=True)
is_true = models.BooleanField(default=False, verbose_name='是否超级用户')
views
class ModelFormDemo(ModelForm):
class Meta:
model = self.model
if self.list_editable:
fields = self.list_editable
else:
fields = '__all__'
excluded = self.excluded
def __init__(self, *args, **kwargs):
super(ModelFormDemo, self).__init__(*args, **kwargs)
def add_view(self, request):
form = ModelFormDemo()
if request.method == "POST":
res_dict = {'status': 1, 'msg': 'success'}
form = ModelFormDemo(request.POST)
if form.is_valid():
obj = form.save()
else:
res_dict['msg'] = form.errors
res_dict['status'] = 2
return JsonResponse(res_dict)
return render(request, "xadmin/add_view.html", locals())
html
<form class="layui-form" method="post">
{% csrf_token %}
{% for field in form %}
{% if field.name == 'employee' %}
<input type="hidden" name="employee" value="{{ user.id }}">
{% else %}
<div class="layui-form-item">
<label class="layui-form-label">{{ field.label }}</label>
<div class="layui-input-inline">
{{ field }}
</div>
</div>
{% endif %}
{% endfor %}
<div class="layui-form-item">
<div class="layui-input-block">
<input type="button" class="layui-btn" lay-filter="add" lay-submit="" value="add">
</input>
<button type="reset" class="layui-btn layui-btn-primary">reset</button>
</div>
</div>
</form>
You can use the Widget.attrs arg in your form __init__ method.
https://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs
How can i set only mine membership, instead of all in for-loop ?
template.html:
{% for g in gr %}
<div class="jumbotron">
<div class="jumbo2">
<form method="POST" class="post-form"> {% csrf_token %}
<p id="name"><b>Groups name:</b> {{g.name}}</p><br>
{% for membership in g.membership_set.all %}
<p><b>Member:</b> {{ membership.person }} - {{ membership.role }}</p>
{% endfor %}
<br>
<span class="desc2">Groups description:</span>
<p id="desc">{{g.description}}</p><br>
{% for membership in g.membership_set.all %}
{% if membership.leader == False %}
<button style="float: right" type="submit" name = "leave" value = "{{g.name}}" class="save btn btn-default">Leave</button>
{% elif membership.leader == True %}
<button style="float: right" type="submit" name = "delete" value = "{{g.name}}" class="save btn btn-default">Delete</button>
{% endif %}
{% endfor %}
</form>
<br><br>
<p></p>
</div>
</div>
{% endfor %}
models.py:
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self): # __unicode__ on Python 2
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
description = models.TextField(max_length=350)
def __str__(self): # __unicode__ on Python 2
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person)
leader = models.BooleanField(default=False)
group = models.ForeignKey(Group)
role = models.CharField(max_length=50)
My buttons are displeyed as many as i have users in some group.
I want to display only 1 button, and i need to precise ForLoop only for my membership in this group. How can i do this?
I don't think you can do this just by using standard template code. You would need to get your Membership object by filtering the memberships like so:
membership = my_person.membership_set.get(group=my_group)
To do this in the template, you would have to write your own template filter that works on the my_person object and takes the my_group object as parameter. The filter could then apply the above query and return the membership object.
{% with membership=my_person|get_group_membership:g %}
{% if membership.leader == False %}
<button style="float: right" type="submit" name = "leave" value = "{{g.name}}" class="save btn btn-default">Leave</button>
{% elif membership.leader == True %}
<button style="float: right" type="submit" name = "delete" value = "{{g.name}}" class="save btn btn-default">Delete</button>
{% endif %}
{% endwith %}
I'm using django auth for users. Every user can create one row - based on Client model. But i have problem because I cant assign in form.is_valid to field id request.user.id.
Because id is required I exclude this field in form class Meta.
Please give me some advice how i can assign user.id to my OneToOneField field.
I'm using PyCharm and when i put form. i dont see any of fields in my Model so i thing that i make some mistake in my code :(
Model:
class Client(models.Model):
id = models.OneToOneField(User, on_delete=models.CASCADE, unique=True, primary_key=True)
name = models.CharField(max_length=256, unique=True)
vat = models.CharField(max_length=12, unique=True)
address = models.CharField(max_length=64)
zip_code = models.CharField(max_length=10, help_text='Zip Code')
city = models.CharField(max_length=64)
country = models.CharField(max_length=6, default='US')
forwarding_address = models.CharField(max_length=64, blank=True)
forwarding_zip_code = models.CharField(max_length=10, blank=True)
forwarding_city = models.CharField(max_length=64, blank=True)
forwarding_country = models.CharField(max_length=6, blank=True)
phone = models.CharField(max_length=20)
def __str__(self):
re = self.name + ' [' + str(self.id) + ']'
return re
Form:
class ClientProfileForm(forms.ModelForm):
class Meta:
model = Client
exclude = ['id']
View:
def profile_create(request):
if request.method == 'POST':
form = ClientProfileForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.id = request.user.id
form.save()
return HttpResponseRedirect('/client/profile/')
dict = {}
dict['form'] = form
return render(request, 'client/profile_edit.html', dict)
else:
if Client.objects.filter(id=request.user.id).exists():
return HttpResponseRedirect('/client/profile/edit/')
else:
dict = {}
dict['form'] = ClientProfileForm()
return render(request, 'client/profile_edit.html', dict)
Template:
{% extends 'registration/base.html' %}
{% block title %} Client profile {% endblock %}
{% block content %}
{{ form.non_field_errors }}
<form role="form" action="" method="post">{% csrf_token %}
{{ form.name.errors }}
<div class="form-group login-input">
<i class="fa fa-envelope overlay"></i>
<input type="text" class="form-control text-input"
{% if form.name.value != nulls %} value="{{ form.name.value }}" {% endif %}
id="{{ form.name.name }}" name="{{ form.name.name }}">
</div>
{{ form.vat.errors }}
<div class="form-group login-input">
<i class="fa fa-envelope overlay"></i>
<input type="text" class="form-control text-input"
{% if form.vat.value != nulls %} value="{{ form.vat.value }}" {% endif %}
id="{{ form.vat.name }}" name="{{ form.vat.name }}">
</div>
{{ form.address.errors }}
<div class="form-group login-input">
<i class="fa fa-envelope overlay"></i>
<input type="text" class="form-control text-input"
{% if form.address.value != nulls %} value="{{ form.address.value }}" {% endif %}
id="{{ form.address.name }}" name="{{ form.address.name }}">
</div>
(....)
<div class="row">
<div class="col-sm-12">
<button type="submit" class="btn btn-default btn-block">Create</button>
</div>
</div>
</form>
{% endblock %}
Cheers!
That's not the right pattern. It should be:
if form.is_valid():
obj = form.save(commit=False)
obj.id = request.user.id
obj.save()
I am working in ang django project onlinevoting. In my template I use
looping to loop all the positions and also the candidates. I have trouble in saving many data at once in one attribute for example in my model I have:
class Vote(models.Model):
candidate_id = models.ForeignKey('Candidate', blank=True, null=True)
election_id = models.ForeignKey('Election', blank=True, null=True)
user_id = models.ForeignKey('User', blank=True, null=True)
def __str__(self):
return "%s %s" % (user_id.first_name, election_id.year)
and in my template vote.html:
<form method="POST" class="form-horizontal" role="form">
{% if success %}
<div class="alert alert-success">
×
<strong>Success!</strong> {{ success }}
</div>
{% endif %}
{% if exist %}
<div class="alert alert-warning">
×
<strong>Warning!</strong> {{ exist }}
</div>
{% endif %}
{% csrf_token %}
<div class="form-group ">
{% for position in positions %}
<label for="cname" class="control-label col-lg-2">{{ position }}<span class="required">*</span></label>
{% for candidate in candidates %}
{% if position.pk == candidate.position_id.pk %}
<div class="col-lg-3">
<input type="checkbox" name="candidate_id" value="{{ candidate.pk }}">{{ candidate }}<br>
</div>
{% endif %}
{% endfor %}
</div>
{% endfor %}
<button class="btn btn-primary" type="submit">Save</button>
<button class="btn btn-default" type="button">Cancel</button>
</div>
</div>
</form>
How can I add/save all the candidates? because the user can select many candidates and I want to save them at once. This is my views.py
def vote(request):
if request.user.is_authenticated and request.user.is_admin:
candidates = Candidate.objects.all()
election = Election.objects.all().filter(is_active=True)
positions = Position.objects.all()
user = get_object_or_404(User, pk=request.user.pk)
try:
if request.method == 'POST':
candidate_id = request.POST['candidate_id']
vote = Vote.objects.create(candidate_id=candidate_id)
vote.save()
vote.election_id = election
vote.save()
vote.user_id = user
vote.save()
else:
form = VoteForm()
return render(request,'system/vote.html', {'form':form, 'candidates': candidates,
'election': election, 'user': user,
'positions': positions})
except:
exist = "ERROR!"
form = VoteForm()
return render(request,'system/vote.html', {'form':form, 'exist': exist})
elif not request.user.is_authenticated:
return redirect('system.views.user_login')