Django add to wishlist

makim

i have to do wishlist, i have done wishlist page,model and html.But when i click on the button bellow my post, im redirected to wishlist page and post didnt saved in my wishlist.So thats my code: models.py

class Wishlist(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    wished_item = models.ForeignKey(Posts, on_delete=models.CASCADE)


def __str__(self):
    return self.wished_item.title

class Posts(models.Model):
    TYPE = Choices(
        ('private', _('private')),
        ('business', _('business')),
    )
    STATUS = Choices(
        ('active', _('active')),
        ('deactivated', _('deactivated'))
    )
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='posts',
                              on_delete=models.CASCADE, verbose_name='owner')
    phone_number = PhoneNumberField(verbose_name=_('Phone_number'), null=False, blank=False, unique=True)
    title = models.CharField(verbose_name=_('Title'), max_length=100)
    text = RichTextField(verbose_name=_('Text'))
    image = models.ImageField(upload_to='images/%Y/%m/%d/', null=True, blank=True, validators=[file_size])
    price = models.DecimalField(verbose_name=_('Price'), decimal_places=2, max_digits=9)
    status = models.CharField(choices=STATUS, max_length=50)
    created = models.DateTimeField(auto_now=True)
    type = models.CharField(choices=TYPE, max_length=50)

    def __str__(self):
        return self.title

views.py

class WishListView(generic.View):
    def get(self, *args, **kwargs):
        wish_items = Wishlist.objects.filter(user=self.request.user)
        context = {
            'wish_items': wish_items
        }
        return render(self.request, 'wishlist/wishlist.html', context=context)


def addToWishList(request):
    if request.method == 'POST':
        post_var_id = request.POST.get('object-id')
        post_var = Posts.objects.get(id=post_var_id)
        print(post_var)

        try:
            wish_item = Wishlist.objects.get(user=request.user, post=post_var)
            if wish_item:
                wish_item.save()

        except:
            Wishlist.objects.create(user=request.user, post=post_var)

        finally:
            return HttpResponseRedirect(reverse('wishlist'))

wishlist.html

{% extends 'posts/base.html' %}
{% load thumbnail %}
{% block content %}
<div>
  {% for item in wish_items %}
  {% if item.wished_item.image1 %}
  <img src="{{item.wished_item.image.url}}" alt="">
  {% endif %}
</div>
<div>
  <li>{{item.wished_item.title}}</li>
  <li>{{item.wished_item.text}}</li>
  <li>{{item.wished_item.price}}</li>
  <li>{{item.wished_item.phone_number}}</li>
  {% if item.wished_item.image %}
      <img src="{% thumbnail item.wished_item.image 200x200 crop %}" alt="" />
  <p></p>
  {% endif %}
</div>
{% endfor %}
{% endblock %}

urls.py

urlpatterns = [
    path("wishlist/", WishListView.as_view(), name='wishlist'),
    path("add-to-wishlist", addToWishList, name='add-to-wishlist'),
]

and allposts template with add to wishlist button

<ul>
    {% for object in object_list %}
    <li>Owner: {{ object.owner }}</li>
    <li>Phone: {{ object.phone_number }}</li>
    <li>Title: {{ object.title }}</li>
    <li>Text: {{ object.text }}</li>
    <li>Type: {{ object.type }}</li>
    <li>Price: {{ object.price }}</li>
    <li>Date: {{ object.created }}</li>
    <p>
      {% if object.image %}
      <img src="{% thumbnail object.image 200x200 crop %}" alt="" />
      {% endif %}
      </p>
  <form action="{% url 'add-to-wishlist' %}" method="POST">
    {%csrf_token%}
    <input type="hidden" name="object-id" value="{{object.id}}">
    <input type="submit" value="Add to Wishlist">
  </form>
  <hr/>

Probably problem with posts ID,but im not sure in that

enes islam

You can use get_or_create instead of the if else statement for if exist or not. And use get_object_or_404 to make code more clear

from django.shortcuts import get_object_or_404

def addToWishList(request):
    if request.method == 'POST':
        post_obj = get_object_or_404(Post, pk=request.POST.get('object-id'))
        Wishlist.objects.get_or_create(user=request.user, post=post_obj)
        return HttpResponseRedirect(reverse('wishlist'))

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Trying to add a "add to wishlist button" in my Django web application

Adding items to Wishlist | Django

Add to wishlist button on Category Page Opencart:2.3.0.2

Replace Add To Wishlist text with Heart icon WooCommerce

add catalog product in wishlist programmatically in magento

Add custom class to wishlist top link

Add wishlist button to Virtuamart product list

Execute action without redirecting(Add to wishlist)

How to delete product from Wishlist in Django?

How do you add toggle functionality to a wishlist button to add and remove items from a wishlist?

Is there any way to add a Wishlist that is toggled than data is displayed in specified by id as Wishlist area

Shopware 6 - Change Fill-Color of "Add to Wishlist Icon"

Django: NOT NULL constraint failed: wishlist_wish.user_id

Message: no such element: Unable to locate element Selenium Python:{"method":"xpath","selector":"//input[@value='Add to wishlist']"}

Swift make wishlist feature

Ignite Woo Wishlist

Magento 1.9.2.3 - Wishlist issue

show date in wishlist magento 1.9

Where to store the simple data? As example: wishlist

WishList Member wishlistmember_shoppingcart_register (action)

Magento 2 display only 5 products in wishlist

Jquery and php wishlist - how to retrieve data?

Why the data in wishlist can't show

Magento: Product Move from cart to Wishlist

How to retrieve users wishlist with product in magento

Overriding Mage_Wishlist_IndexController::addAction() in Magento

How to check if YITH Woocommerce Wishlist is activated in theme

How to display for user that his wishlist is empty?

why my items are not showing in wishlist in android studio

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  6. 6

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  7. 7

    Do Idle Snowflake Connections Use Cloud Services Credits?

  8. 8

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  9. 9

    Binding element 'string' implicitly has an 'any' type

  10. 10

    BigQuery - concatenate ignoring NULL

  11. 11

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  12. 12

    In Skype, how to block "User requests your details"?

  13. 13

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  14. 14

    Pandas - check if dataframe has negative value in any column

  15. 15

    flutter: dropdown item programmatically unselect problem

  16. 16

    Generate random UUIDv4 with Elm

  17. 17

    Is it possible to Redo commits removed by GitHub Desktop's Undo on a Mac?

  18. 18

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  19. 19

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  20. 20

    EXCEL: Find sum of values in one column with criteria from other column

  21. 21

    How to use merge windows unallocated space into Ubuntu using GParted?

HotTag

Archive