How to delete multiple objects in django? - django

I am trying to delete django model multiple objects using html checkboxes but i can't. Kindly guide me what I need to do complete my this task.
I try the following code for this purpose but i failed.
views.py
class DeleteProducts(SuccessMessageMixin, View):
success_url = reverse_lazy('stock:stock')
success_message = "Products are deleted successfully."
def post(self, request, *args, **kwargs):
products = self.request.POST.getlist('product')
Product.objects.filter(pk__in=products).delete()
messages.success(self.request, self.success_message, extra_tags='alert-danger')
return redirect('stock:stock')
In template i used checkboxes prefectly or not??
template.html
<form method="POST" action="{% url 'stock:deleteproducts' %}">
{% csrf_token %}
{% for product in page_obj %}
<div class="row" >
<input type="checkbox" value="{{ product.id }}">
<div class="col-sm-2" >
<h5>{{ product.id }}</h5>
<img src="{{ product.Picture.url }}" height="120px" />
</div>
<div class="col-sm-4" >
<h5><u>Product Name</u>: {{ product.pro_name }}</h5>
<h6><u>Company Name</u>: {{product.companyName}}</h6>
<div class="row" >
<div class="col-sm" >
<p>Purchase Price: <b>{{product.Purchase_Price}}</b></p>
</div>
<div class="col-sm" >
<p class="pt-0">Sale Price: <b>{{product.Sale_Price}}</b> </p>
</div>
</div>
<div class="row" >
<div class="col-sm" >
<p>Quantity <b>{{product.Quantity}}</b></p>
</div>
<div class="col-sm" >
<p> Added By: <b>{{product.saler}}</b> </p>
</div>
</div>
</div>
<div class="col-sm-4" >
<p><b>Added Date</b>:{{ product.pub_date }}</p>
<hr/>
<center>
<a href="{% url 'stock:editproduct' product.id %}" class="btn btn-success" >Edit</a>
</center>
</div>
</div>
<hr/>
{% endfor %}
<input type="submit" class="btn btn-danger" value="Delete" >
</form>
urls.py
path('delete/', login_required(DeleteProducts.as_view(), login_url='login'), name='deleteproducts'),

You need to assign name="product" attribute to checkboxes since you are trying to get it with self.request.POST.getlist('product'):
<input type="checkbox" value="{{ product.id }}" name="product">

Related

Problems with a backend part of search line in Django

who can explain me why my SearchView doesn't work. I have some code like this.It doesn't show me any mistakes, but it doesn't work. The page is clear. Seems like it doesn't see the input.
search.html
<div class="justify-content-center mb-3">
<div class="row">
<div class="col-md-8 offset-2">
<form action="{% url 'search' %}" method="get">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="Search..." />
<div class="input-group-append">
<button class="btn btn-dark" type="submit" id="button-addon2">Search</button>
</div>
</div>
</form>
</div>
</div>
</div>
search/urls.py
path('search/', SearchView.as_view(), name='search')
search/views.py
class SearchView(ListView):
model = Question
template_name = 'forum/question_list.html'
def get_queryset(self):
query = self.request.GET.get("q")
object_list = Question.objects.filter(
Q(title__icontains=query) | Q(detail__icontains=query)
)
return object_list
forum/question_list.html
{% extends 'main/base.html' %}
{% block content %}
{% for question in object_list %}
<div class="card mb-3">
<div class="card-body">
<h4 class="card-title">{{ question.title }}</h4>
<p class="card-text">{{ question.detail }}</p>
<p>
{{ question.user.username }}
5 answers
10 comments
</p>
</div>
</div>
{% endfor %}
{% endblock %}

django returns MultiValueDictKeyError at / 'q'

django returns MultiValueDictKeyError at /
'q' in my dashboard template when I'm trying to add search functionality into my app. I want when a user type something on the search input to return the value that user searched for. but i endup getting an error when i try to do it myself.
MultiValueDictKeyError at /
'q'
def dashboard(request):
photos = Photo.objects.all()
query = request.GET['q']
card_list = Photo.objects.filter(category__contains=query)
context = {'photos': photos, 'card_list':card_list}
return render(request, 'dashboard.html', context)
<div class="container">
<div class="row justify-content-center">
<form action="" method="GET">
<input type="text" name="q" class="form-control">
<br>
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
<br>
<div class="container">
<div class="row justify-content-center">
{% for photo in photos reversed %}
<div class="col-md-4">
<div class="card my-2">
<img class="image-thumbail" src="{{photo.image.url}}" alt="Card
image cap">
<div class="card-body">
<h2 style="color: yellowgreen; font-family: Arial, Helvetica,
sans-serif;">
{{photo.user.username.upper}}
</h2>
<br>
<h3>{{photo.category}}</h3>
<h4>{{photo.price}}</h4>
</div>
<a href="{% url 'Photo-view' photo.id %}" class="btn btn-warning btn-
sm m-1">Buy Now</a>
</div>
</div>
{% empty %}
<h3>No Files...</h3>
{% endfor %}
</div>
</div>
try this
query = request.GET['q']
query = request.GET.get('q', '') # use get to access the q
The get() method returns the value of the item with the specified key.

Flask - Delete image from static (boostrap card)

I'm trying to create a functionnality where the user is able to upload and delete some images on the fly. The deleting part works but not completely... it successfully deletes an image from my static folder, but for some reason it only deletes the first image it finds, and not the one that linked to the bootrap card.
For some reason it is not properly identifying the correct value and I can't figure out why :
1. Flask
#app.route('/deleteImg', methods=['GET', 'POST'])
def deleteImg(row):
if request.method == 'POST':
image_to_del = request.values.get('image_to_del', None)
print(f'image_to_del:{image_to_del}')
os.remove(os.path.join(UPLOAD_FOLDER,image_to_del))
return redirect('/uploadimg')
return render_template('uploadimg.html')
2. HTML
<form action="{{url_for('deleteImg')}}" method="POST">
<div class="row">
{% for row in pics %}
<div class="col-md-3 mt-3">
<div class="card">
<img src="{{ url_for('static', filename='pics/'+row)}}" alt="{{row}}" class="card_img_top" height="200">
<input type="hidden" name="image_to_del" class="image_to_del" value="{{row}}">Filename : {{row}}</input>
<h5 class="text-cent" >Filename : {{row}}</h5>
</div>
<div class="card-footer text-center">
<input type="submit" value="Delete" class="btn btn-success" />
</div>
</div>
{% endfor %}
</div>
</form>
I found this solution for those who might be interested. This is based on the work of "Cairocoders" Flask delete image from db
1. FLASK
#app.route('/deletelogo/<string:get_ig>', methods=['GET', 'POST'])
def deletelogo(get_ig):
print(f'get_ig :{get_ig}')
os.remove(os.path.join(LOGO_FOLDER,get_ig))
return redirect('/logoimg')
2. HTML
<div class="row">
{% for row in pics %}
<div class="col-md-3 mt-3">
<div class="card">
<img src="{{ url_for('static', filename='logo/'+row)}}" alt="{{row}}" class="card_img_top" height="200">
<input type="hidden" name="image_to_del" class="image_to_del" value="{{row}}">Filename : {{row}}</input>
<h5 class="text-cent" >Filename : {{row}}</h5>
</div>
<div class="card-footer text-center">
<td><p><span class="glyphicon glyphicon-trash"></span></p></td>
</div>
</div>

Dictionary not passing to the template django

I'm trying to read a cookie and pass the data into the template but it returns a string /cart on the template.
view.py
def cart(request):
# exception no cookie named 'cart'
try:
cart = json.loads(request.COOKIES['cart'])
except:
cart = {}
context = {
'data': [],
'cart': cart,
}
for item in cart:
product_detail = ProductImage.objects.select_related(
'product'
).filter(product=item[0], place='Main Product Image')
context['data'].append(product_detail)
return render(request, 'store/cart.html', context)
I've checked whether the cart variable contains data and it does contain a dictionary. Following is the context variable,
{'data': [<QuerySet [<ProductImage: Product 1-22>]>], 'cart': {'1': {'unit_price': '980.00', 'quantity': 3}}}
when I tried to print the cart in the template using {{ cart }} it returns /cart but the data key contains all the data and can be displayed in the template.
template
{{ cart }} <!-- for testing -->
{% for item in data %}
{% if forloop.counter|divisibleby:2 %}
<div class="row border-bottom pb-3 pt-1 cart-item">
{% else %}
<div class="row border-bottom pb-3 pt-1 cart-item" style="background-color: #F8F8F8">
{% endif %}
<div class="col-sm-1 d-md-flex justify-content-center align-items-center remove-btn">
<button type="button" class="btn bg-transparent"
data-action="delete" data-product="{{ item.0.product.id }}_{{ item.0.product.get_sale_price|floatformat:2 }}">
<i class="fa fa-trash" aria-hidden="true"></i>
</button>
</div>
<div class="col-sm">
<img class="img-fluid img-thumbnail" src="{{ item.0.image.url }}" alt="" />
</div>
<div class="col-sm">
<a href="product/{{ item.0.product.id }}" class="cart-product-link">
<h5> {{ item.0.product.name }}</h5>
<p class="module fades">
{{ item.0.product.desc }}
</p>
</a>
</div>
<!-- quantity -->
<div class="col col-sm input-group my-auto text-center">
<div class="quantity ml-5">
<input type="number" class="update-quantity" data-action="q_add" min="1" max="20" step="1"
value="{{ cart|get_quantity:item.0.product.id }}" style="width: 50px"
data-product="{{ item.0.product.id }}_{{ item.0.product.get_sale_price|floatformat:2 }}">
</div>
</div>
<!-- cost -->
<div class="col col-sm mt-lg-5 text-center cost-container">
<span class="cost">{{ cart|get_cost:item.0.product.id }}</span>
</div>
</div>
{% endfor %}
So hoping to know what's going on here thanks in advance.
Update(wierd scenario)
The same thing happened again in a different file and I tried to do the solution bellow mentioned. Unfortunately, it didn't work. After hours of trying, I decided to rename the key of the dict {'cart': cart,...} to {'crt':cart} and it worked.
If you want to pass a context dict variable in the template. All you need to do is :
return render(request, 'store/cart.html', {'context' : context})
By this we are passing the context to html template. And the you can retrieve the context data by :
{{context.cart}}

How to filter out Friends of user in search users function Django

I'm trying to filter out the friends of a user and also the current logged in user from a "search_users" function, I've tried using exclude() but keep getting an error I'm not sure whats wrong. I also wanted to add a "add friend" button next to the users, which I think I've done correctly on 'search_users.html.
Error
views.py
#login_required
def search_users(request):
query = request.GET.get('q')
object_list = User.objects.filter(username__icontains=query).exclude(friends=request.user.profile.friends.all())
context ={
'users': object_list
}
return render(request, "users/search_users.html", context)
search_users.html
{% extends "feed/layout.html" %} {% load static %}
{% block searchform %}
<form
class="form-inline my-2 my-lg-0 ml-5"
action="{% url 'search_users' %}"
method="get"
>
<input name="q" type="text" placeholder="Search users.." />
<button class="btn btn-success my-2 my-sm-0 ml-10" type="submit">
Search
</button>
</form>
{% endblock searchform %} {% block content %}
<div class="container">
<div class="row">
<div class="col-md-8">
{% if not users %}
<br /><br />
<h2><i>No such users found!</i></h2>
{% else %}
<div class="card card-signin my-5">
<div class="card-body">
{% for user_p in users %}
<a href="{{ user_p.profile.get_absolute_url }}"
><img
src="{{ user_p.profile.image.url }}"
class="rounded mr-2"
width="40"
height="40"
alt=""
/></a>
<a class="text-dark" href="{{ user_p.profile.get_absolute_url }}"
><b>{{ user_p }}</b></a
>
<small class="float-right">
<a
class="btn btn-primary mr-2"
href="/users/friend-request/send/{{ user_p.username }}"
>Add Friend</a>
</small>
<br/><br />
{% endfor %}
</div>
</div>
{% endif %}
</div>
<div class="col-md-4">
<div class="card card-signin my-5">
<a href="{{ request.user.profile.get_absolute_url }}"
><img
class="card-img-top"
src="{{ request.user.profile.image.url }}"
alt=""
/></a>
<div class="card-body">
<h5 class="card-title text-center">{{ request.user }}</h5>
<h6 class="text-center">
{{ request.user.profile.friends.count }}
<p class="text-muted">Friends</p>
</h6>
<p class="card-text text-center">{{ request.user.profile.bio }}</p>
</div>
</div>
</div>
</div>
{% endblock content %}
</div>
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.png', upload_to='profile_pics')
slug = AutoSlugField(populate_from='user')
bio = models.CharField(max_length=255, blank=True)
friends = models.ManyToManyField('Profile', blank=True)
I would have done like this :
object_list = User.objects\
.filter(username__icontains=query)\
.exclude(profile__friends__in=request.user.profile.friends.all())\
.exclude(id=request.user.id)
It should be
User.profile.objects.filter(username__icontains=query).exclude(friends=request.user.profile.friends.all())
You were getting an error earlier because you referred to the user object earlier and not the profile itself. User.profile gives the one to one related model profile instead.
You can read more about one to one relationships here. https://docs.djangoproject.com/en/3.1/topics/db/examples/one_to_one/