我已经创建了我的模型,但我对创建视图以将提交表单中的数据保存到数据库中感到困惑

2024-05-03 07:42:24 发布

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

models.py

from django.db import models
class Aganwadi(models.Model):
    name= models.CharField(max_length=30)
    email= models.EmailField()
    district=models.TextField()
    phone=models.IntegerField()

    def __str__(self):
        return self.name

我在users/templates/users/aganwadi.html中有一个名为aganwadi.html的表单模板 views.py

from django.shortcuts import render,redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required

def Aganwadi(request):
    return render(request,'users/aganwadi.html')

url.py

from django.urls import path,include
from users import views as user_views
from django.contrib.auth import views as auth_views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
    path('admin/', admin.site.urls),
     path('login/',auth_views.LoginView.as_view(template_name='users/login.html'),name='login'),
     path('logout/',auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'),
     path('aganwadi/',user_views.Aganwadi,name='aganwadi'),
     path('', include('pmmvyapp.urls')),

]

我想将表单上提交的数据存储在数据库中


2条回答

在views.py函数中,您可以执行您想要的操作

def Aganwadi(request):
    if request.method == 'POST': # considering html form has action=post
          username = request.POST.get('username') # provided that your form has field named username
          new_user = User.objects.create(username=username)
          new_user.save()
    return render(request,'users/aganwadi.html')

但这个例子远不是一个产品 只是给小费。更推荐使用django表单而不是html表单

如果要使用模型保存数据,首先必须创建一个表单:

form.py

from django.forms import models
from .models import YourModel
class YourForm(models.ModelForm):
    class Meta:
        model = YourModel

现在您可以在视图中使用ModelForm。 view.py

from .forms import YourForm
def Aganwadi(request):
    form = YourForm(request.POST or None) # initialize form or get POST data
    if request.method == 'POST': # considering html form has action=post
          if form.is_valid()
             form.save()
    return render(request,'users/aganwadi.html', context={'form':form})

最后,您必须使用html文件中的表单。。。 aganwadi.html

<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save     </button>
</form>

我强烈要求你通过django tutorial

相关问题 更多 >