如何使用表单更新Django中的行?

我正在尝试创建一个网站来使用django跟踪我的志愿者的出勤情况,其中将有一个签入/签入和签入/签出按钮,因此当单击签入/签入按钮时,数据将转到那里的数据库没问题,这是在“检出/检出”按钮中,单击检出/检出按钮时,它应该更新行并添加检出/检出的日期/时间。

models.py:

from django.db import models
from django.forms import ModelForm

# Create your models here.

class Volunteer(models.Model):
    full_name = models.CharField(max_length=200)
    phone_number = models.CharField(max_length=30)
    email = models.CharField(max_length=255)
    national_id = models.CharField(max_length=255)

    def __str__(self):
        return self.full_name

class Login(models.Model):
    full_name = models.CharField(max_length=200,default="",null=True,)
    national_id = models.CharField(max_length=200,)
    check_in = models.DateTimeField(auto_now_add=True)
    check_out = models.DateTimeField(auto_now=True)
    check_in.editable=True
    check_out.editable=True

    def __str__(self):
        return self.full_name

views.py:

from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from .models import Volunteer,Login
from django import forms
# Create your views here. 


def volunteerView(request):
    if request.method=='POST':
        print ("Recieved a POST request")
        form=LoginForm(request.POST)
        if form.is_valid():
            print ("FORM is valid")
        else:
            print ("FORM is unvalid")
    all_volunteers = Volunteer.objects.all()
    return render(request,'volunteer.html',{'all_volunteers': all_volunteers,'form':LoginForm()})

def loginView(request):
    login_view = Login.objects.all()
    return render(request,'login.html',{'login_view': login_view})



def addVolunteer(request):
    new_volunteer = Volunteer(full_name = request.POST['full_name'],phone_number = request.POST['phone_number'],email = request.POST['email'],national_id = request.POST['national_id'],)
    new_volunteer.save()
    return HttpResponseRedirect('/')

def addChekIn(request):
    new_checkin = Login(
        national_id = request.POST['national_id'],full_name = request.POST['full_name'],)
    new_checkin.save()
    return HttpResponseRedirect('/login/')

template / login.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Ertiqa | Login</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>  
</head>

<style>

h1{
    color: white;
}


</style>

<body>

    <form action="/addCheckIN/" method="POST" class="container">
        {{ form.as_p }}
        {% csrf_token %}
        <h1>Check IN</h1>
        <h3>Full Name</h3>
        <input type="text" name="full_name"><br>
        <h3>National ID</h3>
        <input type="text" name="national_id"><br>
        <input type="submit" value="Check IN" class="btn btn-primary">
    </form>


</body>

</html>
huangfeng802 回答:如何使用表单更新Django中的行?

我遇到了你的问题。首先,您的models.py小说有点错误。您可以使用以下模型类:

from django.db import models
from django.forms import ModelForm

# Create your models here.

class Volunteer(models.Model):
    full_name = models.CharField(max_length=200)
    phone_number = models.CharField(max_length=30)
    email = models.CharField(max_length=255)
    national_id = models.CharField(max_length=255)

    def __str__(self):
        return self.full_name

class Login(models.Model):
    full_name = models.CharField(max_length=200,default="",null=True)
    national_id = models.CharField(max_length=200,null=True)
    check_in = models.DateTimeField(auto_now_add=True,editable=True) # <--- You can use editable arg inline.
    check_out = models.DateTimeField(auto_now=True,editable=True) # <--- You can use editable arg inline.

    def __str__(self):
        return self.full_name

我认为您不使用任何授权会话。只是有人填写输入并将这些信息发布到数据库。为什么需要两个类的“志愿者”和“登录”?他们有关系吗?还是需要两个模型?也许比这更好:

class Volunteer(models.Model):
    full_name = models.CharField(max_length=200,unique=True)
    phone_number = models.CharField(max_length=30)
    email = models.CharField(max_length=255)
    national_id = models.CharField(max_length=255,unique=True)
    check_in = models.DateTimeField(auto_now_add=True,editable=True) #<-- auto_now_add=True args mean: when you call .save() method first time,this field is filled in with the current date and time.
    check_out = models.DateTimeField(auto_now=True,editable=True) #<-- auto_now=True args mean: when you call .save() method second and next times (every updating),this field is filled in with the current date and time.


    def __str__(self):
        return self.full_name

您需要两个函数,第一个完成了(def addCheckIn),因此您调用.save()方法来保存新的志愿者。第二个是用于更新(例如def checkout(request))。因此,您应该像这样再次调用.save()方法:

def checkout(request):
    national_id = request.POST['national_id'],# If national_id is unique,It's enough.
    try: #Check this national id is exist in your db.
        person = Login.objects.get(national_id=national_id)
        person.save()
        messages.success(request,"Thank you for checkout blabla")
        return HttpResponseRedirect('/login/')  # Maybe you can create a success page.
    except LoginDoesNotExist: # If doesn't you can show error message.
        messages.error(request,"No such registry was found in the system.")
        return redirect("/login/")

最后一个,当给函数命名时,应使用下划线而不是驼峰式大小写。 (例如def add_check_in())。这只是pep8 Python拼写规则。 希望对您有帮助。

本文链接:https://www.f2er.com/3135574.html

大家都在问