Python社区  »  Django

Django模型窗体未保存到数据库

GTA.sprx • 4 天前 • 21 次点击  

我有一个汽车经销商的模型,我试图有一个表格来创建他们。由于某种原因,表单没有保存到数据库,但是它确实到达了重定向。也不显示错误。

模型.py

class Dealer(models.Model):
    name = models.CharField(max_length=50)
    phone = models.CharField(max_length=50)
    website = models.CharField(max_length=100)
    address = models.CharField(max_length=100)
    featured_image = models.ImageField(upload_to="dealers/")

    class Meta:
        verbose_name_plural = "Dealers"

    def __str__(self):
        return self.name

视图.py

def create_dealer_view(request):
    if request.method == "POST":
        form = CreateDealerForm(request.POST)
        if form.is_valid():
            dealer = form.save(commit=False)
            dealer.save()
            return redirect('main:homepage_view')
    else:
        form = CreateDealerForm
    context = {
        "title": "Create - Dealer",
        "form": form,
    }
    return render(request=request, template_name="main/create/create_dealer.html", context=context)

表单.py

class CreateDealerForm(forms.ModelForm):
    class Meta:
        model = Dealer
        fields = ('name', 'phone','website', 'address', 'featured_image',)
        widgets = {
            'name': forms.TextInput(attrs={'class': 'dealer-name-field', 'placeholder': 'Dealer name'}),
            'phone': forms.TextInput(attrs={'class': 'dealer-phone-field', 'placeholder': 'Dealer phone'}),
            'website': forms.TextInput(attrs={'class': 'dealer-website-field', 'placeholder': 'Dealer website'}),
            'address': forms.TextInput(attrs={'class': 'dealer-address-field', 'placeholder': 'Dealer address'}),

        }

create-dealer.html网站

{% block content %}
<div class="container text-center">
    <form method="POST">
        {% csrf_token %}
        {{ form.name }}
        {{ form.phone }}
        {{ form.website }}
        {{ form.address }}
        {{ form.featured_image }}
        <br>
        <button type="submit" class="btn btn-primary"><i class="fa fa-plus" aria-hidden="true"></i> Create
            Dealer</button>
    </form>
</div>
{% endblock content %}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52866
 
21 次点击  
分享到微博