0
我試圖在Django中設置一個表單並將數據保存到我的數據庫,而不使用ModelForm。我的表單正在工作,但我堅持的部分是如何處理表單數據並將其保存在視圖中。正如你所看到的,在'if form.is_valid()'之後:'我被困住了,無法想到正確的代碼。在Django保存表單數據
# models.py
from django.db import models
class Listing(models.Model):
business_name = models.CharField(max_length=80)
business_email = models.EmailField()
business_website = models.CharField(max_length=80)
business_phone = models.CharField(max_length=80)
# forms.py
from django import forms
class NewBusinessForm(forms.Form):
business_name = forms.CharField(label='Business Name', max_length=100)
business_phone = forms.CharField(label='Phone Number', max_length=100)
business_email = forms.EmailField(label='Email Address', max_length=100)
business_website = forms.CharField(label='Web Site', max_length=100)
# views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import NewBusinessForm
def new_business(request):
if request.method == 'POST':
form = NewBusinessForm(request.POST)
if form.is_valid():
# process form data
return HttpResponseRedirect('/')
else:
form = NewBusinessForm()
return render(request, 'directory/new.html', {'form': form})
不要忘記導入上市模型 –
這工作,謝謝!大多數人把這個邏輯放到views.py中嗎?或者更好地將它包含在forms.py中作爲一個函數? – Casey
@Casey,大多數情況下這應該使用模型表單來完成。或者,如果你想要,你可以把這個邏輯放在'form.save()'方法中。 – Rohan