Django ValueError当从HTML表单发布数据到DB时-如何从选项列表中分配外键?

okxuctiv  于 2023-05-30  发布在  Go
关注(0)|答案(1)|浏览(139)

当从HTML页面发布数据到数据库时,我得到
ValueError at /add_emp/
无法分配“女性”:“PersonInfo.gender”必须是“Gender”示例
我试图在html选项列表下获得性别列表,以便用户可以在发布时选择一个。我的代码如下所示。我是新的django和自我教学从互联网上。

**Models.py**

class Gender(models.Model):
    gender = models.CharField(max_length=10)

    def __str__(self):
        return self.gender

class PersonInfo(models.Model):
    pid = models.CharField(max_length=10, blank=False)
    first_name = models.CharField(max_length=15, blank=False)
    middle_name = models.CharField(max_length=15, blank=False)
    last_name = models.CharField(max_length=15, blank=False)
    birth_date = models.DateField(blank=False)
    gender = models.ForeignKey(Gender, on_delete=models.CASCADE, null=True)

    def __str__(self):
        return(f"{self.first_name} {self.last_name}")

**Views.py**

def add_emp(request):
    if request.user.is_authenticated:
        all_record = PersonInfo.objects.all()
        # Show Form
        if request.method == "POST":

            pid = request.POST['pid']
            first_name = request.POST['first_name']
            middle_name = request.POST['middle_name']
            last_name = request.POST['last_name']
            birth_date = request.POST['birth_date']
            gender = request.POST['gender']

            new_employee = PersonInfo(pid=pid, first_name=first_name, middle_name=middle_name, last_name=last_name, birth_date=birth_date, gender=gender)
            new_employee.save()
            messages.success(request, "Employee Added")
            return render(request, 'add_emp.html', {'all_record': all_record})
        else:
            return render(request, 'add_emp.html', {'all_record': all_record})
    else:
        messages.success(request, "Access denied")
        return redirect('lobby')

**add_emp.html**

      <select name="gender" class="form-select">
        <option selected>Select Gender</option>
          {% for gender in all_record %}
            <option> {{ gender.gender }} </option>
          {% endfor %}
      </select>
svujldwt

svujldwt1#

您需要获取Gender对象本身并将其传递给PersonInfo

def add_emp(request):
    if request.user.is_authenticated:
        all_record = PersonInfo.objects.all()
        # Show Form
        if request.method == "POST":

            pid = request.POST['pid']
            first_name = request.POST['first_name']
            middle_name = request.POST['middle_name']
            last_name = request.POST['last_name']
            birth_date = request.POST['birth_date']

            # .filter().first() will return the matching object or `None`
            gender_obj = Gender.objects.filter(gender=request.POST['gender']).first()

            new_employee = PersonInfo(
                pid=pid,
                first_name=first_name,
                middle_name=middle_name,
                last_name=last_name,
                birth_date=birth_date,
                gender=gender_obj
            )
            new_employee.save()
            messages.success(request, "Employee Added")
            return render(request, 'add_emp.html', {'all_record': all_record})
        else:
            return render(request, 'add_emp.html', {'all_record': all_record})
    else:
        messages.success(request, "Access denied")
        return redirect('lobby')

编辑

只是澄清我对.filter().first()的使用。
你也可以把Gender.objects.get(gender=request.POST['gender']),但它没有找到任何项目与该列,它会崩溃(像一个真实的的崩溃,一个不受控制的错误)一般来说,我认为这是一个很好的路线,总是做.filter().first(),甚至与request.POST我总是使用request.post.get('gender') ..它将返回传入的值,如果没有传入,则返回None,类似于.filter().first()

相关问题