我之前对此发表了另一篇文章,但我认为我自己解释错了。 我的班级叫做“ Empresa”。网页的用户可以通过在视图中填充ModelForm来注册自己的公司(“ Empresa”)。 问题是我找不到语法。 我有:
models.py:
from django.db import models
class EmpresaManager(models.Manager):
def create_empresa(self):
empresa = self.create()
return empresa
class Empresa(models.Model):
codigo = models.CharField(max_length=3, null=False, default='000')
nombre = models.CharField(max_length=100, null=False, default='Sin nombre')
email = models.EmailField(null=False, default='email@empresa.com')
direccion = models.CharField(max_length=100, null=False, default='Sin direccion')
localidad = models.CharField(max_length=100, null=False, default='Sin localidad')
codDgi = models.SmallIntegerField(null=True)
docDgi = models.CharField(max_length=13, null=True)
sIva = models.CharField(max_length=1, null=True, default='1')
mesCierre = models.IntegerField(null=True, default=0)
fecIni = models.DateField(null=True)
ruca = models.IntegerField(null=True)
novedad = models.CharField(max_length=50, null=True, default='')
fecNovedad = models.DateTimeField(null=True)
ultVersion = models.CharField(max_length=20, null=True, default='')
logo = models.ImageField(null=True)
habilitado = models.CharField(max_length=1, null=True, default='S')
codEmpresa = models.CharField(max_length=3, null=True)
codComp = models.CharField(max_length=3, null=True, default='')
objects = EmpresaManager()
forms.py:
from django import forms
from django.forms import ModelForm
from .models import Empresa
class RegistroEmpresaForm(ModelForm):
class Meta:
model = Empresa
fields = ["nombre", "docDgi", "email"]
views.py:
from django.shortcuts import render
from Empresa.forms import RegistroEmpresaForm
from Empresa.models import Empresa
from django.http import HttpResponse
def registrado(request):
form = RegistroEmpresaForm(request.POST or None)
titulo = "Registro SIG | ERZ Software"
context = {
"form": form,
"titulo": titulo,
}
empresa = Empresa.objects.create_empresa()
empresa.nombre = form.cleaned_data.get('nombre')
empresa.docDgi = form.cleaned_data.get('docDgi')
empresa.email = form.cleaned_data.get('email')
empresa.save(nombre=empresa.nombre, docDgi=empresa.docDgi, email=empresa.email)
return HttpResponse("Gracias por registrarse.")
def registro(request):
form = RegistroEmpresaForm(request.POST or None)
titulo = "Registro SIG | ERZ Software"
context = {
"form": form,
"titulo": titulo,
}
return render(request, "registro.html", context)
registro.html :(的一部分)
</style>
<!-- Custom styles for this template -->
<link href="{% static 'css/SIG.css' %}" rel="stylesheet">
</head>
<body class="text-center">
{% block content %}
<form class="form-signin" method="POST" action="registrado" enctype="application/x-www-form-urlencoded">{% csrf_token %}
<img class="mb-4" src="/docs/4.2/assets/brand/bootstrap-solid.svg" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal">Panel de registro</h1>
{{ form }}
<button class="btn btn-lg btn-primary btn-block" type="submit">Registrarme</button>
<p class="mt-5 mb-3 text-muted">© ERZSoftware 2019 - Todos los derechos reservados</p>
</form>
{% endblock %}
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
</body>
</html>
我知道我的观点有误,问题是我找不到语法。 我知道如何使用ModelForm填充视图,但是我无法使用ModelForm中的填充数据创建新的empresa对象。 我将不胜感激,谢谢!!
答案 0 :(得分:1)
每个ModelForm都有一个save()方法。此方法从绑定到表单的数据创建并保存数据库对象。 ModelForm的子类可以接受现有的模型实例作为关键字参数实例。如果提供了此参数,则save()将更新该实例。如果未提供,则save()将创建指定模型的新实例:
还请注意,您应该对GET和POST请求使用相同的视图-Django中的规范“表单”视图功能如下所示:
def myview(request):
if request.method == "POST":
form = MyModelForm(request.POST)
if form.is_valid():
my_instance = form.save()
# you can redirect wherever you want,
# as long as you redirect - cf
# https://en.wikipedia.org/wiki/Post/Redirect/Get
# You may also want to use tyhe messages framework
# to notify the user the action has been succesful
return redirect(my_instance.get_absolute_url())
else:
# GET method, provide an empty form
form = MyModelForm()
return render(request, "mytemplate.html", {"form": form})