简体   繁体   中英

View returning None and not returning a response object django

What I am working on is saving a new listing that is created by a given user on my commerce site, and displaying/redirecting the user to my index page. For some reason, the view keeps returning None and I'm not exactly sure why. Here is the code snippets below:

views.py

def createListing(request):
    if request.method == "POST":
        listing = NewListingForm(request.POST)
        if listing.is_valid():
            creator = request.user
            title = listing.cleaned_data['title']
            price = listing.cleaned_data['price']
            description = listing.cleaned_data['description']
            image = listing.cleaned_data['image']
            category = listing.cleaned_data['category']

            # Using .objects.create much simpler solution
            auction = Listing.objects.create(
                creator=creator,
                title=title, 
                description=description, 
                price=price,
                category=category,
                image=image,
            )

            starting_bid = auction.price
            bid = Bid.objects.create(
                bid=starting_bid,
                user=creator,
                auction=auction
            )

            return render(request, "auctions/index.html", {
                "message": "Listing Created Successfully."
            })
    if request.method == "GET":
        return render(request, "auctions/create.html", {
            "create_form": NewListingForm()
        })

models.py

class User(AbstractUser):
    pass

class Comment(models.Model):
    comment = models.CharField(max_length=64)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_comment")

class Listing(models.Model):
    
    CATEGORIES = [
    ('Toys', 'Toys'),
    ('Electronics', 'Electronics'),
    ('Lifestyle', 'Lifestyle'),
    ('Home', 'Home'),
    ('Fashion', 'Fashion'),
    ('Other', 'Other')
    ]   

    creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="creator")
    title = models.CharField(max_length=64, blank=False, null=False)
    price = models.DecimalField(max_digits=10, decimal_places=2, blank=False, null=True)
    description = models.CharField(blank=True, max_length=1064, null=True)
    category = models.CharField(max_length=64, blank=True, choices=CATEGORIES)
    image = models.URLField(default='https://user-images.githubusercontent.com/52632898/161646398-6d49eca9-267f-4eab-a5a7-6ba6069d21df.png')
    starting_bid = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    bid_counter = models.IntegerField(default=0)
    active = models.BooleanField(default=True)
    winner = models.CharField(max_length=64, blank=True, null=True)

    def _str__(self):
        return f"{self.title} by {self.creator}"

class Bid(models.Model):
    bid = models.DecimalField(decimal_places=2, max_digits=10)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_bid")
    date_created = models.DateTimeField(auto_now=True)
    auction = models.ForeignKey(Listing, on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.bid} made by {self.user}"

The new listing form:

# Creating a new listing form
class NewListingForm(forms.Form):
    title = forms.CharField(label='', min_length=2, widget=forms.TextInput(
        attrs={"class": "form-control", "style": "margin-bottom: 10px", "placeholder": "Title"}))
    description = forms.CharField(label='', widget=forms.Textarea(
        attrs={"class": "form-control", "style": "margin-bottom: 10px", "placeholder": "Description"}))
    price = forms.DecimalField(label='', widget=forms.NumberInput(
        attrs={"class": "form-control", "style": "margin-bottom: 10px", "placeholder": "Starting Bid ($)"}))
    image = forms.ImageField(label="Choose an Image for your Listing")
    category = forms.MultipleChoiceField(
        label='Pick a Category', widget=forms.CheckboxSelectMultiple, choices=Listing.CATEGORIES)

I have tried looking into urls.py to ensure I was calling the right view with its according name and using 'return redirect('index')' but it doesn't seem to work either. I'm relatively new to django so any help would be appreciated. Let me know if there are any other files that are required to help clarify the problem.

Django handled http GET method automatically not needing to write it, and also need to remove the unwanted stuff.

your code becomes like this...

from django.shortcuts import render,redirect
from django.contrib import messages
def createListing(request):
    listing =NewListingForm()
    if request.method == "POST":
        listing = NewListingForm(request.POST)
        if listing.is_valid():
            creator = request.user
            title = listing.cleaned_data['title']
            price = listing.cleaned_data['price']
            description = listing.cleaned_data['description']
            image = listing.cleaned_data['image']
            category = listing.cleaned_data['category']

            # Using .objects.create much simpler solution
            auction = Listing.objects.create(
                creator=creator,
                title=title,
                description=description,
                price=price,
                category=category,
                image=image,
            )

            starting_bid = auction.price
            bid = Bid.objects.create(
                bid=starting_bid,
                user=creator,
                auction=auction
            )
            messages.success(request,"Listing Created Successfully")
            return redirect("/home/")
    context = {
        "listing": listing
    }
    return render(request, "auctions/create.html", context)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM