如何将表单模型中的数据导入Djang的数据库

2024-06-12 01:11:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从模型表单中获取数据,然后将其放入数据库。我已经找到了制作表单的方法,但是当单击submit按钮时,它似乎没有放到数据库中的任何地方。是我做错了什么,还是我没有在数据库中找到正确的位置。你知道吗

你知道吗表单.py你知道吗

from django import forms
from sxsw.models import Account

class AccountForm(forms.ModelForm):
    class Meta:
        model = Account
        fields = ['firstName', 'lastName', 'email']

你知道吗视图.py你知道吗

from django.shortcuts import render
from django.shortcuts import redirect
from .forms import AccountForm
from .models import Account 

def sxsw(request):
    if request.method == 'POST':
        form = AccountForm(request.POST)
        if form.is_valid():
            form.save()
        else:
            print form.errors
    else:
        form = AccountForm()

    return render(request, 'sxsw/sxsw.html', {'form': form})

def formSubmitted(request):
    return render(request, 'sxsw/formSubmitted.html',{})

你知道吗型号.py你知道吗

from __future__ import unicode_literals

from django.db import models

# Create your models here.

class Account(models.Model):
    firstName = models.CharField(max_length = 50)
    lastName = models.CharField(max_length = 50)
    email = models.EmailField()

    def __unicode__(self):
        return self.firstName

class Module(models.Model):
    author = models.ForeignKey(Account, on_delete = models.CASCADE)
    nameOfModule = models.CharField(max_length = 150) #arbitrary number
    moduleFile = models.FileField(upload_to = 'uploads/')#Not exactly sure about the upload_to thing
    public = models.BooleanField()

    def __unicode__(self):
        return self.nameOfModule

你知道吗sxsw.html文件你知道吗

{% extends "base.html" %}

{% block content %}
    <div class="container-fluid">
        <div class="jumbotron text-center">
          <h3>SXSW Form</h3> 
        </div>

    </div>

    <div align="center">
        <h1>New Form</h1>
        <form role='form' action="/sxsw/formSubmitted/" method="post">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit">Submit</button>
        </form>
    </div>


  </div>
{% endblock %}

你知道吗表单提交.html你知道吗

{% extends "base.html" %}

{% block content %}
    <div class="container-fluid">
        <div class="jumbotron text-center">
          <h3>Form Successfully submitted</h3> 
        </div>

    </div>

    <div align="center">
        <a href="{% url 'sxsw' %}" class="btn">Submit Another Response</a>
    </div>


  </div>
{% endblock %}

Tags: djangofromimportdivform表单returnmodels
2条回答

看起来表单的action被设置为/sxsw/formSubmitted/,它总是简单地返回提交的页面,而不是调用表单save方法的sxsw视图的url。你知道吗

你的表格是张贴到什么我猜是错误的网址

 <form role='form' action="/sxsw/formSubmitted/" method="post">

应该使用sxsw视图的url

 <form role='form' action="/sxsw/" method="post">

一旦提交,您可能需要重定向到提交的视图

 return redirect('/sxsw/formSubmitted/')  # Preferably use the url pattern name here

相关问题 更多 >