Home > Software design >  I am confused while rendering my views.py "Django"
I am confused while rendering my views.py "Django"

Time:11-07

My vews.py:

if you want me to share another piece of information feel free to ask! I just have a problem with the bidding system !!, I tried the bidding but when I add the new number into the input field and click the place bid button the page just reloads which means the function doesn't work!! I have another problem when I try to close the bid I git this Django error

ValueError at /bidding/26
 The view auctions.views.bidding didn't return an HttpResponse object. 
 It returned None instead.

The code:

 def viewList(request, id):
        # check for the watchlist
        listing = Post.objects.get(id=id)
        user = User.objects.get(username=request.user)
        if listing.watchers.filter(id=request.user.id).exists():
                is_watched = True
        else:
                is_watched = False

        if not listing.activate:
              if request.POST.get('button') == "Close":
                  listing.activate = True
                  listing.save()
        else:
            price = request.POST.get('bid', 0)
            bids = listing.bids.all()
        if user.username != listing.creator.username:
            if price <= listing.price:
                return render(request, 'auctions/item.html', {
                    "listing": listing,
                    'form': BidForm(),
                    "message": "Error! Your bid must be largest than the current bid!",
                    'comment_form': CommentForm(),
                    'comments': listing.get_comments.all(),
                    'is_watched': is_watched,
                })
            form = BidForm(request.POST)
            if form.is_valid():
                bid = form.save(commit=False)
                bid.user = user
                bid.save()
                listing.bids.add(bid)
                listing.bid = price
                listing.save()
            else:
                return render(request, 'acutions/item.html', {'form'})
        context = {
          'listing': listing,
          'comment_form': CommentForm(),
          'comments': listing.get_comments.all(),
          'is_watched': is_watched,
          'form': BidForm()}
        return render(request, 'auctions/item.html', context)

models.py

class Bid(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    bid = models.DecimalField(max_digits=10, decimal_places=2)
    time = models.DateTimeField(default=timezone.now)


class Post(models.Model):
    # data fields
    title = models.CharField(max_length=64)
    textarea = models.TextField()

    # bid
    price = models.FloatField(default=0)
    currentBid = models.FloatField(blank=True, null=True)

    imageurl = models.CharField(max_length=255, null=True, blank=True)
    category = models.ForeignKey(
        Category, on_delete=models.CASCADE, default="No Category Yet!", null=True,  blank=True)

    creator = models.ForeignKey(
        User, on_delete=models.PROTECT, related_name="all_creators_listings")

    watchers = models.ManyToManyField(
        User, blank=True, related_name='favorite')
    date = models.DateTimeField(auto_now_add=True)

    # for activated the Category
    activate = models.BooleanField(default=False)

    bids = models.ManyToManyField(Bid, )

    def __str__(self):
        return f"{self.title} | {self.textarea} |  {self.date.strftime('%B %d %Y')}"

item.html

            <div class="card-body">
            <ul class="list-group">
                <div class="info">
                    <li class="list-group-item mb-2">Description:<br>{{listing.textarea}}</li>
                    <li class="list-group-item mb-2">category: {{listing.category.name}}</li>
                    <li class="list-group-item mb-2"><h5>Start bid: {{listing.price}}$</h5></li>
                </div>

                <div class="newbid">
                <p>{{ message }}</p>
                <form action="{% url 'viewList' listing.id %}" method="POST">
                    {% csrf_token %}
                    <div class="form-group">
                    <label for="bid">{{ listing.bids.count }} bid(s) so far. Your bid is the current bid</label>
                    </div>
                    <div class="form-group">
                    {{ form }}
                    </div>
                    <div class="form-group">
                    <input type="submit" name="button" class="btn btn-primary" value="Place Bid">
                    </div>
                </form>
                    {% if listing.activate %}
                        <li><strong>Winner: </strong>{{ listing.bids.last.user.username }}</li>
                    {% endif %}

                    {% if user.username == listing.creator.username and not listing.activate %}
                    <form action="{% url 'viewList' listing.id %}" method="POST">
                        {% csrf_token %}
                        <button type="submit" name="button" class="btn btn-danger" value="Close">Close</button>
                    </form>
                    {% endif %}

                </div>

            </ul>
        </div>

inside this view, I added a punch of my project requirement (comments/watchlist(bookmark)/and the last thing(that what I have a lot of problem with it) is the system of Bid) that lets users add bids on such posts and let the creator of that post the ability to close it.... please help I am sticking in this zone, I tried many times to understand! Note I am new at Back-end Development!

CodePudding user response:

There is the two problem in you code first one is hi-lighted by Husam user = User.objects.get(username=request.user.username) and the other one is in the return statement in the else part

render(request, 'acutions/item.html', {'form'}) instead of context object you pass the string in which is consider as set object in python and thats why you are getting None type error.

here is the refactored code :-

def viewList(request, id):
        # check for the watchlist
        listing = Post.objects.get(id=id)
        user = User.objects.get(username=request.user.username)
        form = BidForm()
        is_watched = listing.watchers.filter(id=request.user.id).exists():
        context = {}
        if not listing.activate:
              if request.POST.get('button') == "Close":
                  listing.activate = True
                  listing.save()
        else:
            price = request.POST.get('bid', 0)
            bids = listing.bids.all()
        if user.username != listing.creator.username:
            if price <= listing.price:
                context.update({'message':"Error! your bid must be largest than the current bid !"})
            else:    
                form = BidForm(request.POST)
                if form.is_valid():
                    bid = form.save(commit=False)
                    bid.user = user
                    bid.save()
                    listing.bids.add(bid)
                    listing.bid = price
                    listing.save()
                else:
                    return render(request, 'acutions/item.html', {'form': form})

        context.update({'listing': listing,
          'comment_form': CommentForm(),
          'comments': listing.get_comments.all(),
          'is_watched': is_watched,
          'form': form})
        return render(request, 'auctions/item.html', context)

CodePudding user response:

The error you face in bidding view and the view you have shared is view list, it would be better if you shared the bidding view and highlight the error line/s

Anyway I have noticed that this line has one mistake: user = User.objects.get(username=request.user)

Which suppose to be : user = User.objects.get(username=request.user.username)

Hope this can help you little bit

  • Related