简体   繁体   中英

Submit Django Form with Foreign Key

I am trying to send a form which would add a new "item"/row in my table Listing using Django.

I am sure the issue lays in the fact that I am using a ForeignKey and keep on receiving the following error :

ValueError: Cannot assign "'2'": "Listing.category" must be a "Category" instance.

Note that the value 2 above is just one of 7 options i have.

My "Category" Table defined in Models.py is currently filled as followed:

(id) : (category)
    7 : Book
    6 : Technology
    5 : Beauty
    4 : Clothing
    3 : Health
    2 : Sports
    1 : Grocery

Models.py :

class Category(models.Model):
    category = models.CharField(max_length=16)
    
    def __str__(self):
        
        return f"{self.id} : {self.category}"

class Listing(models.Model):
    owner = models.CharField(max_length=64)
    title = models.CharField(max_length=64)
    description = models.CharField(max_length=256)
    startingBid = models.IntegerField()
    link = models.CharField(max_length=1024,blank=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category_id")
    time = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'"{self.title}" added by {self.owner}'

Views.py

    class Create(forms.Form):
        CHOICES = (
            (1, 'Grocery'),
            (2, 'Sports'),
            (3, 'Health'),
            (4, 'Clothing'),
            (5, 'Beauty'),
            (6, 'Technology'),
            (7, 'Book'),
        )
        owner = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Your Username'}))
        title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What is your item?'}))
        description = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Max 256 characters'}))
        link = forms.URLField(required=False)
        startingBid = forms.IntegerField()
        category = forms.ChoiceField(choices=CHOICES)
    
    @login_required
    def create_listing(request):
        if request.method == "POST":
            form = Create(request.POST)
            if form.is_valid():
                owner = form.cleaned_data["owner"]
                title = form.cleaned_data["title"]
                description = form.cleaned_data["description"]
                link = form.cleaned_data["link"]
                startingBid = form.cleaned_data["startingBid"]
                category = form.cleaned_data["category"]
    
                item = Listing(owner=owner, title=title, description=description, link=link, startingBid=startingBid, category=category)
                item.save()
    
        else:
            return render(request, "auctions/create_listing.html", {
                    "create": Create()
                    })

For troubleshooting purposes, I manually hardcoded an id, or the english word for the category instead of passing category=category (ex category='Sports' or category='4'), but this does not do the trick.

I have also looked through several similar post but I am not able to make an offered suggestion work on my end.

I am sure my issue is fairly basic but I cannot seem to understand the root cause of the issue.

Looking forward to receiving your assistance !

Try this:

item = Listing(owner=owner, title=title, description=description, link=link, startingBid=startingBid, category_id=category)

Category expects an object, whereas you are passing an id, therefore category_id should do the trick if what you are passing is it's id.

If you are passing category choice, then you should try:

item = Listing(owner=owner, title=title, description=description, link=link, startingBid=startingBid, category__category=category)

In model Listing category is a is foreign key and as the error suggests you should store the the instance of Category .

Try this:

category = Category.object.filter(id = form.cleaned_data["category"]).first()

item = Listing(owner=owner, title=title, description=description, link=link, startingBid=startingBid, category=category)

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