【问题标题】:how to update a row in django using a form?如何使用表单更新 django 中的一行?
【发布时间】:2020-03-05 10:34:54
【问题描述】:

我正在尝试使用 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,default="", null=True,)
    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/')

模板/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>

【问题讨论】:

  • 嗨!您需要添加您尝试过的内容以帮助我们

标签: python django django-models django-rest-framework django-forms


【解决方案1】:

我有你的问题。首先,您的 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,default="", 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 拼写规则。 我希望这会对你有所帮助。

【讨论】:

  • 非常感谢!!我是 django 新手,所以我不是那么好,感谢您的帮助
  • 不客气。不要忘记,如果没有人互相帮助,我们就无法生活在这个世界上;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-05
  • 2021-06-09
  • 2021-03-05
  • 1970-01-01
  • 1970-01-01
  • 2013-09-19
  • 1970-01-01
相关资源
最近更新 更多