我已经阅读了多篇文档和文章,但未能解决此问题。 我将直接看代码,这样我们就不会浪费时间:
models.py
from django.db import models
from ckeditor.fields import RichTextField
class Acusacion(models.Model):
LICHESS = 'lichess.com'
CHESS = 'chess.com'
CHESS24 = 'chess24.com'
MY_CHOICES = [
(LICHESS, 'lichess.com'),
(CHESS, 'chess.com'),
(CHESS24, 'chess24.com')
]
NombreyApellido = models.CharField(max_length=40)
NickName = models.CharField(max_length=40, default='')
Fecha = models.DateField()
Torneo = models.CharField(max_length=60)
NombreyApellidodeAcusado = models.CharField(max_length=40)
NicknamedeAcusado = models.CharField(max_length=40)
Sitio = models.CharField(choices=MY_CHOICES, max_length=20)
Descripcion = RichTextField()
Pruebas = models.FileField()
def __str__(self):
return self.NombreyApellido
forms.py
from django import forms
from django.contrib import admin
from django.forms import ModelForm
from .models import Acusacion
from ckeditor.widgets import CKEditorWidget
# Create your models here.
class AcusacionForm(forms.ModelForm):
class Meta:
model = Acusacion
fields = ('NombreyApellido' , 'NickName', 'NombreyApellidodeAcusado', 'NicknamedeAcusado', 'Fecha', 'Sitio' , 'Torneo' , 'Descripcion', 'Pruebas')
labels = { 'NombreyApellido': 'Nombre y Apellido', 'Fecha': 'Fecha', 'NombreyApellidodeAcusado': 'Nombre y Apellido del acusado', 'NicknamedeAcusado': 'Nickname del acusado', 'Descripcion': 'Explicación'}
views.py
from django.shortcuts import render
from .forms import AcusacionForm
from django.views import View
from.models import Acusacion
from django.shortcuts import HttpResponse
def home(request):
if request.method == "POST":
new_acusacion = AcusacionForm(request.POST)
if new_acusacion.is_valid():
new_acusacion.save(commit=True)
form = AcusacionForm()
context = {
'form': form
}
return render(request, 'form.html', context)
form.html
{% extends 'base.html' %}
{% block content %}
<div style="text-align: center;">
<h1>Acusación de Trampa</h1>
<div class="col-4 offset-4 mb-5 mt-5">
<form action="." method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="submit"/>
</form>
</div>
</div>
{% endblock content %}
模板正确呈现,我可以从django-admin添加对象的实例,但不能从表单本身(用户端)添加对象。 任何帮助将不胜感激