【问题标题】:cs50w commerce project : IntegrityError UNIQUE constraint failedcs50w 商业项目:IntegrityError UNIQUE 约束失败
【发布时间】:2021-09-29 15:30:01
【问题描述】:

我正在处理 cs50w 的商业项目,试图创建一个新列表,但我不断收到此错误:

IntegrityError at /new
UNIQUE constraint failed: auctions_listings.user_id

这是我的用户和列表模型:


class User(AbstractUser):
    pass
    #def __str__(self):
        #return f"{self.username}"

class Listings(models.Model):
    title = models.CharField(max_length=30)
    desc = models.TextField()
    #starting_bid = models.FloatField(validators = [MinValueValidator(1)])
    img = models.URLField(blank=True)
    category = models.CharField(blank=True,max_length=20)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner", primary_key=True)

这是我对新列表的看法:


def new(request):
    if request.method == "POST":
        
        if not request.user.is_authenticated:
            return render(request, "auctions/new_listing.html", {
                "message": "Try logging in first"
            })
        user = request.user

######################################################
        for u in User.objects.all():
            print(f" UID  = =  {u.pk} | Name = = {u}")
######################################################

        title = request.POST["title"]
        img = request.POST["image"]
        category = request.POST["category"]
        #starting_bid = request.POST["starting_bid"]
        description = request.POST["description"]

        listing = Listings.objects.create(
            user = user,
            title = title,
            img = img,
            category = category, 
            #starting_bid = starting_bid,
            desc = description
        )

        if listing is not None:
            listing.save()

        return redirect("index")

    return render(request, "auctions/new_listing.html")

以及用于创建新列表的表单:

<form action="{% url 'new' %}" method="post" class="form-horizontal" style="width: 50%; margin: auto;">
    {% csrf_token %}

    <div class="form-group">
        <label for="title">Title: </label>
        <input type="text" name="title" id="title" class="form-control" autofocus required>
    </div>
    
    <div class="form-group">
        <label for="image">Image URL: </label>
        <input type="url" name="image" class="form-control" id="image" autofocus>
    </div>

    <div class="form-group">
        <label for="exampleFormControlSelect1">Category: </label>
        <select class="form-control" id="exampleFormControlSelect1" name="category">

            <option>clothing</option>
            <option>electronics</option>
            <option>collectables</option>
            <option>appliances</option>
            <option>furniture</option>
            <option>other</option>
            
        </select>
    </div>
    
    <!--
    <div class="form-group">
        <label for="starting_bid">Starting Bid: </label>
        <input type="number" id="starting_bid" name="starting_bid" class="form-control" autofocus>
    </div>
    -->
    
    <div class="form-group">
        <label for="description">Description: </label>

        <textarea class="form-control" id="description" name="description" rows="6" autofocus required>
        </textarea>
    </div>

    <div class="form-group">
        <input type="submit">
    </div>


</form>

我已经在提到的所有地方注释掉了起拍价,因为我也遇到了问题,但我现在并不担心,现在我只想能够创建一个列表或两个。

我已经运行了python manage.py makemigrationspython manage.py migrate

这个错误发生在我的 4 个用户中,每个用户都有一个自动递增的 ID。

我可以打印出用户和他们的 id 就好了。

我也收到此警告:

auctions.Listings.user: (fields.W342) Setting unique=True on 
a ForeignKey has the same effect as using a OneToOneField.   
        HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.

但是在使用一对一字段或多对一字段时,我仍然会遇到同样的错误。最终,我希望每个用户都有许多列表,但现在,我只是想成功创建至少一个列表。

【问题讨论】:

    标签: python django django-errors


    【解决方案1】:

    这不是必需的:

    if not request.user.is_authenticated:
                return render(request, "auctions/new_listing.html", {
                    "message": "Try logging in first"
                })
    

    这也可能是问题所在。 试试这个:

    @login_required
    

    编辑: 我认为这就是问题所在。 您已将外键设置为主键。您应该删除“primary_key=True”,django 会自己创建一个。

    【讨论】:

    • 好吧,感谢您的尝试,但这些都不起作用。这仍然会导致相同的错误。
    • 你在 urls.py 中指定了 /new 路由吗?
    • 是的,我有,但现在我重新开始了。我写的太少了,似乎从头开始最好。
    • 难道我不推荐它
    • 大声笑太晚了,我确实重新开始了,我已经完成了。但是,现在我很确定我不必重新开始,我想我可以删除最后一次迁移并重写模型,但无论哪种方式,这都是一次非常棒的学习体验。当我尝试为用户使用外键时,我才真正遇到问题。我最终只使用了 CharField 和用户名,因为用户名必须是唯一的,而且效果很好,即使这不是最佳实践......(可能是这样,我不知道)
    猜你喜欢
    • 2021-06-29
    • 2016-12-22
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2019-07-17
    • 2019-05-27
    • 2018-11-17
    • 1970-01-01
    相关资源
    最近更新 更多