I'm trying to get the users that I'm marking as True on my website in data['checked_users']:
models.py
class Player(models.Model):
jucator = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, related_name='jucator')
porecla = models.CharField(max_length=50, null=True, blank=True)
selectat = models.BooleanField(default=False)
def __str__(self):
return u'%s' % self.jucator
views.py
def check_user(request):
data = dict()
data['players'] = Player.objects.all()
if request.method == 'POST':
list_of_checks = request.POST.getlist('checks[]')
# data['checked_users'] = list_of_checks
data['checked_users'] = Player.objects.filter(jucator__in=list_of_checks)
return render(request, 'checkbox.html', data)
checkbox.html
<body>
{% block content %}
<form action="" method="POST">{% csrf_token %}
<table>
{% if request.user.is_superuser %}
{% for user in players %}
<tr>
<td><input type="checkbox" name="checks[]" value="{{ user.jucator }}" title="selected_players">{{ user.jucator }}<br></td>
</tr>
{% endfor %}
<tr>
<td><input type="submit" name="submit" value="Submit"></td>
</tr>
{% else %}
{% for user in players %}
<tr><td>{{ user.jucator }}</td></tr>
{% endfor %}
{% endif %}
</table>
{% for player in checked_users %}
{{ player }}
{% endfor %}
</form>
{% endblock %}
</body>
If I try this, it shows the players:
data['checked_users'] = list_of_checks
If I try with filter, I get this error:
invalid literal for int() with base 10: 'Stalone'
You need to put inside value="{{ user.jucator }}" the actual id of the jucator object. Not the jucator object itself.
So, change to this: value="{{ user.jucator.id }}". Now you can query with Player.objects.filter(jucator__in=list_of_checks) since list_of_checks containts a list of integers (the ids of jucators).
Related
How can I set my function in views.py so that a form redirects to the same page after submitting?
For example, I want to add time slots:
In my views.py:
#login_required
def post_available_timeslots(request):
print("Check")
if not check_existing_timeslot(request):
print("Time slot does not exist")
instance = TimeSlot()
data = request.POST.copy()
data["time_slot_owner"] = request.user
# data["food_avail_id"] = FoodAvail.objects.get(author=request.user).pk
form = TimeSlotForm(data or None, instance=instance)
if request.POST and form.is_valid():
form.save()
return redirect("food_avail:view_food_avail_res")
else:
print("Time slot does not exist")
messages.info(request, "Time Slot Already Exists")
return render(request, "food_avail/view_food.html", {"time_slot": form})
in models.py
class TimeSlot(models.Model):
time_slot_owner = models.ForeignKey(User, on_delete=models.CASCADE)
# food_avail_id = models.ForeignKey(FoodAvail, on_delete=models.CASCADE)
start_time = models.TimeField()
end_time = models.TimeField()
def __str__(self):
return str(self.start_time) + "-" + str(self.end_time)
In forms.py:
class TimeSlotForm(ModelForm):
class Meta:
model = TimeSlot
fields = ["start_time", "end_time"]
In urls.py:
from django.urls import path
from food_avail import views
app_name = "food_avail"
urlpatterns = [
path("post_food_avail/", views.post_available_food, name="post_food_avail"),
# path("post_food_avail/", views.FoodAvailCreateView.as_view(), name="post_food_avail"),
# path("update_food_avail/", views.post_available_food, name="update_food_avail"),
path("food_avail_all/", views.check_food_availibility, name="view_food_avail"),
path("food_avail_res/", views.view_available_food, name="view_food_avail_res"),
# path("food_avail_res/", views.post_available_timeslots, name="create_timeslots"),
]
in my html template:
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
{{ field.label }} <strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
{{ field.label }} <strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
{% if user.is_authenticated %}
<div>
<div>
<div>
<div>
<h4>
{{ food.author.username }}<br>
</h4>
</div>
<div>
Food Available: {{ food.food_available }}<br>
Description: {{ food.description }}<br>
{% endif %}
</div>
</div>
<div>
<h4>Add Time Slot</h4>
<br><br>
</div>
<div>
<div>
<form method="post">
{{ time_slot.as_p }}
<button type="submit" class="button btn-success">Submit</button>
</form>
</div>
{% if time_slot %}
<h4> List Of Time Slots </h4>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-hover ">
<thead>
<tr>
<th>Start Time</th>
<th>End Time</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{% for x in time_slot %}
<tr>
<td>{{x.start_time | time:'H:i:s'}}</td>
<td>{{x.end_time | time:'H:i:s'}}</td>
<td>
{% endfor %}
{% endif %}
I have been stuck on this problem for a minute now so any help would be much appreciated. This is how it currently shows up on my HTML template:
I am new in Django, I'm making an item-category exercise. each item belongs to a category via a foreign key.I'm not able to understand problem in my code during submission of item detail. I'm getting an error "FOREIGN KEY constraint failed".
I wrote the code for models.py which is working fine in the admin dashboard of Django, but if same thing I'm trying to implement by HTML form page, I'm getting error.
models.py
class ColorCat(models.Model):
name = models.CharField(max_length=20, default="other")
def __str__(self):
return self.name
class ListItems(models.Model):
name = models.CharField(max_length=25, default='item')
item_cat = models.ForeignKey(ColorCat, on_delete=models.CASCADE, default=0, null=True,blank=True)
views.py
def index(request):
list = ListItems.objects.all()
cat = ColorCat.objects.all()
return render(request, 'colorlist.html', {'color': cat, 'item':list })
def colorlist(request):
new_list = ListItems
new_cate = ColorCat
if request.method=="POST":
item = str(request.POST["item"])
cat = str(request.POST["category"])
f_key = ColorCat.objects.filter(name="orange").get()
new_list(name="item").save()
new_list(item_cat=f_key.id).save()
item = ListItems.objects.all()
color = ColorCat.objects.all()
return render(request, 'colorlist.html', {"item": item, "color": color})
def addcat(request):
if request.method=="POST":
newcat = str(request.POST["name"])
ColorCat(name = newcat).save()
item = ListItems.objects.all()
color = ColorCat.objects.all()
return render(request, 'colorlist.html', {"item":item, "color":color})
colorlist.html
{% extends 'base.html'%}
{% block content%}
<h2>Welcome in color cards</h2>
<form action="addcat" method="POST">
{% csrf_token %}
<lable>add new cat<input type="text" name="name"></lable><br>
<label>submit<input type="submit"></label>
</form>
<form action="colorlist" method="post">
{% csrf_token %}
<label>new item<input type="text" name="item"></label><br>
<label>cat<input type="text" name="category"></label><br>
<label>add item<input type="submit"></label>
</form>
<!--see saved result-->
<table>
<tr>
<th>categories</th>
</tr>
{% for cat in color %}
<tr>
<td>{{cat.name}}</td>
</tr>
{% endfor %}
</table>
<table>
<tr>
<th>category item </th>
</tr>
{% for clr in color %}
{% for itm in item %}
<tr>
{% if clr.name == itm.category %}
<td>{{itm.name}}</td>
{%endif%}
</tr>
{% endfor %}
{% endfor %}
</table>
{% endblock %}
Error
IntegrityError at /color/colorlist
FOREIGN KEY constraint failed
I haven't gone allof your code - there's lots of irrelevant stuff - but I've noticed a couple of errors:
definition of ListItems model, it doesn't make sense to define a default value for field item_cat, it'll try to link the instance with a ColorCat instance with id 0 which probably doesn't exist
item_cat = models.ForeignKey(ColorCat, on_delete=models.CASCADE, null=True, blank=True)
saving a new_list - use ColorCat instance instead of its id
new_list(item_cat=f_key).save()
This is my models.py file.
class CustomerInfo(models.Model):
customer_name=models.CharField('Customer Name', max_length=50)
customer_mobile_no = models.CharField('Mobile No', null=True, blank=True,max_length=12)
customer_price=models.IntegerField('Customer Price')
customer_product_warrenty = models.CharField('Product Warrenty',null=True, blank=True,max_length=10)
customer_sell_date = models.DateTimeField('date-published', auto_now=True)
customer_product_id=models.CharField('Product ID',max_length=150,null=True, blank=True)
customer_product_name=models.CharField('Product Name', max_length=50)
customer_product_quantity=models.IntegerField('Quantity',default=1)
def __str__(self):
return self.customer_name
Now I want to search in muliple fieds like as customer_name, customer_mobile_no,customer_product_id etc. So I created views.py file
def customerPage(request):
customers = CustomerInfo.objects.all()
if request.method =="GET":
customerid = request.GET['customer_id']
try:
customers = CustomerInfo.objects.get(pk=customerid)
cus_name = CustomerInfo.objects.filter(customer_name__contains=customerid)
mobile_number = CustomerInfo.objects.filter(customer_mobile_no__contains=customerid)
return render(request, 'shop/customer.html', {"cus_name": cus_name,"mobile_number": mobile_number, "customers": 'customers', "site_name": "Moon Telecom"})
except:
return render(request, 'shop/customer.html', {"error": "Not found any info"})
return render(request, 'shop/customer.html', {'customers': customers})
and this is my html file
{% extends "shop/base.html" %}
{% block content_area %}
<div class="col-lg-4">
<div class="customer_search" >
<form action="{% url "shop:customerPage" %}" method="GET">
{% csrf_token %}
<div class="form-group">
<label for="customer_id">Id:</label>
<input type="text" class="form-control" id="customer_id" placeholder="Enter customer ID" name="customer_id">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
<div class="col-lg-8 customers_info">
{% if error %}
<div class="alert alert-danger">
<strong>{{error}}</strong>
</div>
{% endif %}
{% if cus_name %}
{% for x in cus_name %}
<p>{{x.customer_name}}</p>
{% endfor %}
{% else %}
<p>nothing foung</p>
{% endif %}
{% if customers %}
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Mobile No</th>
<th>Product Name</th>
<th>Price</th>
<th>Date</th>
<th>Product ID</th>
<th>Warrenty</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{customers.customer_name}}</td>
<td>{{customers.customer_mobile_no}}</td>
<td>{{customers.customer_product_name}}</td>
<td>{{customers.customer_price}} TK</td>
<td>{{customers.customer_sell_date}}</td>
<td>{{customers.customer_product_id}}</td>
<td>{% if customers.customer_product_warrenty == '' %}
<b>No Warrenty</b>
{% else %}
<b>{{customers.customer_product_warrenty}}</b> Month
{% endif %}
</td>
</tr>
</tbody>
</table>
{% else %}
<p>nothing found</p>
{% endif %}
</div>
{% endblock %}
I got results If I use POST method and customers = CustomerInfo.objects.get(pk=customerid) When I searched one field, I have got my results but When I start multiple search query from the database. I cant get any info. I want to search multiple fields within CustomerInfo model. Also, I was trying others mehtod but not working.
You need to search using multiple fields in one query. And looking at your code, i presume that the conditions are joined using OR.
This problem can be solved using django ORM's Q object
What it allows you do is to chain multiple filtering conditions together and connect them logically.
So, if you have 3 conditions and they are logically connected as :
Condition 1 OR Condition 2 AND Condition 3 using Q you can write them as :
Q(Condition1) | Q(Conditon2) & Q(Condition2).
In your case the 3 different searches of filterings can be performed as:
filtered_customers = CustomerInfo.objects.filter( Q(pk = int(customerid)) | Q(customer_name__contains = str(customerid)) | Q(customer_mobile_no__contains = str(customerid)))
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 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')