如何将数据从表单保存到django模型



我正在进行CS50W项目2-commerce,并且一直在进行创建清单点的工作。我有一个路由/创建,我必须在其中获取数据并将其保存在模型中。我将在下面留下代码片段。我尝试使用ModelForm类,然后验证数据并保存((,但它不保存数据。我还在shell中对模型运行查询,看看数据是否存在,但什么都没有。在代码片段中,我将只保留有用的部分以使其看起来更干净。我检查了一下,导入(将模型导入到视图、其他模块等(都很好。我想我在其他地方犯了一个错误,但我就是看不出来。如何解决这个问题?

模型窗体

class AuctionsForm(forms.ModelForm):
class Meta:
model = Auctions
fields = ['title' , 'description' , 'category' , 'image']

视图.py

@login_required
def create(request):
if request.method == "POST":
form = AuctionsForm(request.POST)

if form.is_valid():
form.save()
else: 
form = AuctionsForm()

return render(request, "auctions/create.html" , {"form" : AuctionsForm()} )

型号.py

class Auctions(models.Model):
CATEGORY = [
("No Category" , "No Category"),
("Fashion" , "Fashion"),
("Home" , "Home"),
("Toys" , "Toys"),
("Technology" , "Technology"),
]
title = models.CharField(max_length= 50)
description = models.TextField(max_length=150)
category = models.CharField(max_length = 40 , choices= CATEGORY , default="None")
image = models.URLField(default="" , blank=True)
is_active = models.BooleanField(default=True)
date = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey('auctions.User' , on_delete=models.CASCADE , related_name='user_auctions')
watchlist = models.ForeignKey('auctions.User' , on_delete=models.CASCADE , related_name='watchlist_auctions')
def __str__(self):
return self.title

create.html

{% extends "auctions/layout.html" %}
{% block body %}
<h1>Create Listing Here</h1>
<form method="POST" action="{% url 'index' %}">
{% csrf_token %}
{{form}}

<input type="submit" value="Create Listing">
</form>
{% endblock %}

index.html

{% extends "auctions/layout.html" %}
{% block body %}
<h2>Active Listings</h2>
{% for i in show%}
<p>{{i.title}}</p>
<p>{{i.description}}</p>
{% endfor%}
{% endblock %}

forms.py

class AuctionsForm(forms.ModelForm):
class Meta:
model = models.Auction
fields = ['title', 'description', 'category', 'image']

views.py

def create_auction(request):

if request.method == 'POST':
form = AuctionsForm(request.POST)

if form.is_valid():
auction = form.save(commit=False)
# do something if you but in the end
auction.save()
# do want you want here, or return in to creation page dunno
return render(request, "success?idk/", {"auction": auction})
else:
# maybe you want to render the errors?
# https://stackoverflow.com/questions/14647723/django-forms-if-not-valid-show-form-with-error-message
return render(request, "auctions/create.html", {"form": form})

form = AuctionForm()
return render(request, "auction/create.html", {"form":form})
# maybe you had listing view here

使用Auction而不是Auctions,Django将复数化

最新更新