模型
from .BaseModel import BaseModel
from django.db import models
from django.urls import reverse
class AdvPosition(BaseModel):
name = models.CharField(max_length=255, help_text = "广告位名称")
def get_absolute_url(self):
return reverse('backend:adv-position-index')
class Meta(BaseModel.Meta):
db_table = 'adv_position'
模型中需要设定跳转地址,在保存成功后会根据这个地址跳转。
url
path('adv-position/create', AdvPositionCreateView.as_view(), name = 'adv-position-create'),
由于model使用了app_name
所以需要再urls.py中添加
app_name = 'backend'
create.html
<form class="form-horizontal" action="{{ request.get_full_path }}" method="post">
{% csrf_token %}
<div class="card-body">
{{ form.as_ul }}
</div>
<div class="card-footer">
<input type="submit" class="btn btn-info" value="submit" />
</div>
</form>
view
为什么把view放最后呢,因为view有很多中方式
可以用面向过程的方式,在view.py中直接写,主要说下面向对象方式
diango提供了一个CreateView,使用这个可以很方便的做form的添加
方式1:
class AdvPositionCreateView(CreateView):
model = AdvPosition # 指定模型
template_name = 'adv-position/create.html'
fields = ['name']
fields指定表单字段。
方式2:
需要ModelForm,
from django import forms
from common.models import AdvPosition
class AdvPositionForm(forms.ModelForm):
class Meta:
model = AdvPosition
fields = ['name']
ModelForm需要指定fields,用于指定表单字段。
class AdvPositionCreateView(CreateView):
model = AdvPosition # 指定模型
template_name = 'adv-position/create.html'
form_class = AdvPositionForm
方式3:
使用get,post
class AdvPositionCreateView(CreateView):
model = AdvPosition # 指定模型
template_name = 'adv-position/create.html'
form_class = AdvPositionForm
def get(self, request, *args, **kwargs):
form = self.form_class()
return render(request, 'adv-position/create.html', {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
form.save()
return redirect('/backend/adv-position/index')
return render(request, 'adv-position/create.html', {'form': form})
方式4:
使用get,post
class AdvPositionCreateView(CreateView):
model = AdvPosition # 指定模型
template_name = 'adv-position/create.html'
def get(self, request, *args, **kwargs):
form = AdvPositionForm()
return render(request, 'adv-position/create.html', {'form': form})
def post(self, request, *args, **kwargs):
form = AdvPositionForm(request.POST)
if form.is_valid():
form.save()
return redirect('/backend/adv-position/index')
return render(request, 'adv-position/create.html', {'form': form})