简体   繁体   English

如何在 Django 的数据库中将表单响应保存为 object?

[英]How do I save form response as an object in Django's database?

I am unable to save my form responses to the database as an object in Django.我无法将我的表单响应保存为 Django 中的 object。 Everytime I click on submit to submit my form, I am just logged out of my website and the object isnt saved in the database either.每次我点击提交提交我的表单时,我都只是退出了我的网站,并且 object 也没有保存在数据库中。 Can anyone tell me where I am going wrong?谁能告诉我哪里出错了? This is my models in models.py.这是我在 models.py 中的模型。

class Chain(models.Model):
    name = models.CharField(max_length=255)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    year = models.CharField(max_length=10, default="20XX")
    sem = models.CharField(max_length=30, default="Default Semester")
    code = models.CharField(max_length=10, default="SUB-CODE")
    slot = models.CharField(max_length=10, default="EX+EX")
    last_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

This is my view in views.py file.这是我在views.py 文件中的观点。

@login_required(login_url='/')
def create_course(request):
    if request.method == 'GET':
        return render(request, 'create_course.html', {})
    elif request.method == 'POST':    
        name=request.POST['name']
        year=request.POST['year']
        sem=request.POST['sem']
        code=request.POST['code']
        slot=request.POST['slot']
        newchain = Chain(
            name=name,
            year=year,
            sem=sem,
            code=code,
            slot=slot,
        )
        newchain.user = request.user
        newchain.save()
        return redirect('success')

This is my HTML code for the form.这是表格的 HTML 代码。

{% extends 'authmain.html' %}

{% block content %}
<h3> <p class="text-center"> Create a new Course Blockchain: </p> </h3>

<div class="card border-dark mb-3 mx-auto" align="center" style="width: 40rem;">
  <div class="card-body">
    <h5 class="card-title">
      <form method='POST'>
        {% csrf_token %}
        <label for="year">Year: </label>
        <input type="text" id="year" name="year" value=""><br>
        <label for="code">Course Code: </label>
        <input type="text" id="code" name="code" value=""><br>
        <label for="name">Course Name: </label>
        <input type="text" id="name" name="name" value=""><br>
        <label for="slot">Slot: </label>
        <input type="text" id="slot" name="slot" value=""><br>
        <label for="sem">Semester: </label>
        <input type="text" id="sem" name="sem" value=""><br>
        <button class="btn btn-outline-primary" type="Submit"> Create </button>
      </form>
    </h5>
    </div>
</div>

{% endblock %}

This is my urls.py.这是我的 urls.py。

from django.urls import path, include
from . import views

urlpatterns = [
    path('', views.home, name="home"),
    path('register/', views.register, name="register"),
    path('logout/', views.logoutuser, name="logoutuser"),
    path('dashboard/', views.dashboard, name="dashboard"),
    path('create_course/', views.create_course, name="create_course"),
    path('success', views.success, name="success"),
]

This is the view function for success.这是function成功的看法。


@login_required(login_url='/')
def success(request):
    return render(request, 'success.html', {})

To save directly in the database in Django use Model.objects.create()要直接保存在 Django 的数据库中,请使用Model.objects.create()

Chain.objects.create(user=request.user, name=name, year=year, sem=sem, 
                      code=code, slot = slot)

The issue is that you are not closing form tag in the authmain.html .问题是您没有关闭authmain.html中的form标签。

<ul class="navbar-nav ml-auto">
  <li class="nav-item">
  <form action="{% url 'logoutuser' %}" method='POST'>
  {% csrf_token %}
    <button class="btn btn-outline-info mb-auto" type="submit">Logout</button>
  -----  CLOSING FORM TAG MISSING HERE ---
  </li>
</ul>

and when you submit the form at Create Course, you actually trigger this form, which logs out the user.当您在 Create Course 提交表单时,您实际上会触发此表单,该表单会注销用户。 Add closing tag to the logout form and you'll fix your problem.将结束标签添加到注销表单,您将解决问题。

Sometimes debugging can be a bit tricky.有时调试可能有点棘手。

You need to use a model form to achieve this您需要使用 model 表单来实现此目的

class MyForm(ModelForm):
     class Meta:
         model = MyModel
         fields = []

And then you can do something like this:然后你可以做这样的事情:

 form = MyForm(request.POST)
 if form.is_valid():
       new_item = form.save()
       ...

And it will save directly to the database.它会直接保存到数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM