表单不使用Django在数据库中创建新条目

时间:2018-08-09 08:37:56

标签: database python-3.x forms django-2.0

我尝试创建一个表单来创建新玩家。打开url效果很好,当我单击“提交”按钮时,我没有收到任何错误,但重定向到了home项目。 当我签入管理部分时,我看不到以前在表单中发布的数据。而且,我在媒体目录中看不到以前发送的图片。 在Django 2.1中使用表单发布信息时,不会更新数据库。

我不知道我是否正确设置了POST请求。

也许是错误或我错过了什么?

template.py

<h1>Add a new player</h1>

{% if saved %}

    <p>Player has been saved</p>

{% endif %}

<p>
    <form method="post" enctype="multipart/form-data" action=".">
       {% csrf_token %}
       {{ form.as_p }}
       <input type="submit" value="submit" />
    </form>
</p>

view.py

from game.models import Scenario, Player
from .forms import ScenarioForm, NewPlayerForm
def newplayer(request):
    saved = False
    form = NewPlayerForm(request.POST or None, request.FILES)

    if form.is_valid():
        player = Player()
        player.pseudo = form.cleaned_data['pseudo']
        player.gender = form.cleaned_data['gender']
        player.picture = form.cleaned_data['picture']
        player.save()
        saved = True

    return render(request, 'game/newplayer.html', {
        'form': form, 
        'saved': saved
    })

model.py

class Player(models.Model):
    pseudo = models.CharField(max_length=100)
    GENDER_CHOICES = (
        ('M', 'Homme'),
        ('F', 'Femme'),
        ('O','Other'),
    )
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    picture = models.ImageField(upload_to="images/")

    class Meta:
        verbose_name = "player"
        ordering = ['pseudo']

    def __str__(self):
        """ 
        Cette méthode que nous définirons dans tous les modèles
        nous permettra de reconnaître facilement les différents objets que 
        nous traiterons plus tard dans l'administration
        """
        return self.pseudo

Form.py

from django import forms
from .models import Scenario, Player
class NewPlayerForm(forms.Form):

    pseudo = forms.CharField(required=True)
    GENDER_CHOICES = (
        ('M', 'Homme'),
        ('F', 'Femme'),
        ('O', 'Other'),
    )
    gender = forms.ChoiceField(choices=GENDER_CHOICES, required=True)
    picture = forms.ImageField()

1 个答案:

答案 0 :(得分:0)

我会发表评论,但是直到有50个声誉我才能这样做,但是...

在您看来,在<form>元素上有action=".",这意味着如果您提交它,它将在当前URL处通过该函数运行。您的newplayer()的urlpattern是否指向同一页面?因为您说要 重定向 到您的家庭项目,但是您的函数没有返回redirect()。返回的render()并不表示它会进入index.html之类的文件,就我所知,这是典型的主目录。

介意将您的网址格式放在这里吗?

此外,由于您的视图具有saved变量,并且由于控制流程的原因,无论您执行什么操作,由于当前设置始终使页面始终以<p>Player has been saved</p>返回存在。如果您执行了以下操作,则会正确显示该页面上的更新(但我仍然需要查看url模式):

views.py

def newplayer(request):
    # You might have to change some of the parameters in the form object below.
    # Example: I know if you made your own validation instead of django's,
    # object.photo = request.FILES.get('uploadphoto', False) would get the picture fine,
    # but I'm not sure about django forms.
    form = NewPlayerForm(request.POST or None, request.FILES)
    if request.method == 'POST' and form.is_valid():
        player = Player()
        player.pseudo = form.cleaned_data['pseudo']
        player.gender = form.cleaned_data['gender']
        player.picture = form.cleaned_data['picture']
        player.save()
        saved = 'Player has been saved!'
        return render(request, 'success.html', {'saved': saved})
    else:
        return render(request, 'create_player.html', {'form': form})

template.html

{% if saved %}
    <p>{{ saved }}</p>
{% else %)
   <form method="post" enctype="multipart/form-data" action=".">
       {% csrf_token %}
       {{ form.as_p }}
       <input type="submit" value="submit" />
   </form>
{% endif %}