python 查看返回None和不返回响应对象django

watbbzwu  于 2023-01-12  发布在  Python
关注(0)|答案(1)|浏览(137)

我正在做的是保存一个由某个用户在我的商务网站上创建的新列表,并将该用户显示/重定向到我的索引页面。由于某种原因,视图总是返回None,我不知道为什么。下面是代码片段:

查看次数.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()
        })

型号.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}"

新的登录表:

# 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)

我试过查看urls.py来确保我调用了正确的视图名称,并使用了'return redirect(' index ')',但似乎也不起作用。我对django比较陌生,所以任何帮助都将不胜感激!如果需要任何其他文件来帮助澄清这个问题,请让我知道。

pprl5pva

pprl5pva1#

Django自动处理了http GET方法,而不需要编写它,并且还需要删除不需要的东西。
你的代码会变成这样。

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)

相关问题