简体   繁体   English

form.is_valid() 未按预期工作 django

[英]form.is_valid() not working as intended django

I am neew to django and I am trying to make an attendance system where the user can type their name and press clock in or clock out but when I test the code.我是 django 的新手,我正在尝试制作一个考勤系统,用户可以在其中输入他们的姓名并按下打卡或打卡,但是当我测试代码时。 But whenever I type a name and press clock In it does not save the name and time to the database.但是每当我输入名称并按时钟时,它不会将名称和时间保存到数据库中。

views.py:视图.py:

def home(response):
    form = CreateNewList()
    empName = employeeName.objects.all
    if response.method == "POST":
        form = CreateNewList(response.POST) 
        if 'clockIn' in response.POST:
            if form.is_valid():
                n = form.cleaned_data["name"]
                now = datetime.now()
                current_time = now.strftime("%H:%M:%S")
                t = Name(name = n, timeIn=current_time)
                t.save()
                return redirect('/')
    else: 
        form = CreateNewList()        
    return render(response, "main/home.html", context={"form":form, "empName":empName})

models.py:模型.py:

class employeeName(models.Model):
    employee = models.CharField(max_length=200)
    total_Hours_Worked = models.CharField(max_length=8, default="Empty")

    def __str__(self):
        return self.employee
    
class Name(models.Model):
    name = models.ForeignKey(employeeName, null=True,on_delete=models.CASCADE)
    timeIn = models.TimeField()
    timeOut = models.TimeField(default=datetime.now())
    date = models.DateField(auto_now=True)

    def __str__(self):
        return str(self.name)  

forms.py: forms.py:

class CreateNewList(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(CreateNewList, self).__init__(*args, **kwargs)

        self.fields['name'].widget = TextInput()
    
    class Meta:
        model = Name
        fields = ['name']

home.html:主页.html:

<form method="post">
    {% csrf_token %}
    <div class="input-group mb-2">
        <div class="input-group-prepend">
            <h3 class="p2" >Clock In/Clock Out</h3>
            <label>Enter Your Full Name:</label>
            {{form.name}}
            <datalist id="attendance">
                {% for empName in empName %}
                    <option value="{{empName.employee}}">
                {% endfor %}
            </datalist>
            <button type="submit" name="clockIn" value="clockIn" class="btn btn-outline-primary">Clock In</button>
            <button type="submit" name="clockOut" value="clockOut" class="btn btn-outline-primary">Clock Out</button>
        </div>
    </div>
</form>

I tried testing whenever I press the clockIn button to print something in the terminal and nothing ever printed.每当我按下clockIn按钮在终端中打印一些东西并且没有打印任何东西时,我都会尝试进行测试。 I don't get what is wrong with my code我不明白我的代码有什么问题

The problem you have is that name in the Name model is a foreign key to the employeeName model.您遇到的问题是name model 中的名称是employeeName Name model 的外键。 In your form you have changed the widget for the name field to a TextInput .在您的表单中,您已将name字段的小部件更改为TextInput Django is expecting a employeeName object, not a string, when creating Name objects.在创建Name对象时,Django 需要一个employeeName object,而不是字符串。 You should just keep the widget as the default model select, so users will select their name instead of typing it.您应该将小部件保留为默认的 model select,因此用户将使用 select 他们的名称而不是输入它。 Otherwise you will have to implement search functionality which becomes more complicated.否则,您将不得不实现变得更加复杂的搜索功能。 What if a user spells his name wrong?如果用户拼错了他的名字怎么办? How to you inform a user of this?你如何通知用户这件事? How do they confirm that the employeeName object is correct?他们如何确认employeeName object 是正确的?

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

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