Django Model Form未保存到数据库

时间:2019-11-29 08:30:34

标签: django django-models django-forms django-templates django-views

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

models.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

views.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)

forms.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 %}

0 个答案:

没有答案