在Django中保存提交时的Bootstrap模式表单涉及几个基础概念和技术点。以下是详细的解答:
# models.py
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
# forms.py
from django import forms
from .models import MyModel
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['name', 'email']
<!-- templates/my_template.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bootstrap Form</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Submit Form</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
# views.py
from django.shortcuts import render, redirect
from .forms import MyModelForm
def my_view(request):
if request.method == 'POST':
form = MyModelForm(request.POST)
if form.is_valid():
form.save()
return redirect('success_url') # 重定向到成功页面
else:
form = MyModelForm()
return render(request, 'my_template.html', {'form': form})
form.is_valid()
和form.save()
调用正确。检查数据库配置是否正确。{% csrf_token %}
。{% csrf_token %}
。通过以上步骤和示例代码,你应该能够在Django中成功保存提交时的Bootstrap模式表单。
领取专属 10元无门槛券
手把手带您无忧上云