无法将表单保存到模型Django

时间:2019-11-04 06:45:15

标签: python django forms django-models

我无法将表单保存到模型中,但代码无法顺利运行,但是如果我在Django admin中签入,则无法保存到我的数据库模型中,您能帮我吗  这是我的代码:

forms.py

class InstagramUsernameForm(forms.ModelForm):

   class Meta:
       model = InstagramUsername
       fields = ('nama_orang','username','nama_depan')

   nama_orang = forms.CharField(max_length=20)
   username = forms.ModelChoiceField(queryset=Instagram.objects.values_list("username", flat=True))
   nama_depan = forms.ModelChoiceField(queryset=Instagram.objects.values_list("nama_depan", flat=True))

models.py

from django.db import models

# Create your models here.
class Instagram(models.Model):
    nama_depan      =  models.CharField(max_length=100,blank=True,null=True)
    nama_belakang   =  models.CharField(max_length=100)
    username        =  models.CharField(max_length=100)

    def __str__(self):
        return self.username

class InstagramUsername(models.Model):
    nama_orang = models.CharField(max_length=20)
    username = models.CharField(max_length=20)
    nama_depan = models.CharField(max_length=100,default='')

    def __str__(self):
        return self.nama_orang

views.py

def create2(request):
    akun_form = InstagramUsernameForm(request.POST or None)

    if request.method == 'POST':
        if akun_form.is_valid():
            akun_form.save()
        return redirect('sosmed:awe')
    else:
        print(akun_form.errors)
    context = {
        "akun_form":akun_form,
    }

    return render(request,"sosmed/awe.html",context)

awe.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>awe</title>
</head>
<body>
<form method="post">
    {% csrf_token %}
<h1>awe</h1>
<table>
{{ akun_form.as_table }}
</table>
    <button type="submit">Create</button>
</form>
</body>
</html>

无法将表单保存到Django模型

1 个答案:

答案 0 :(得分:1)

values_list用作可迭代对象时,返回元组列表,而不是模型实例。 因此,请使用 .all()方法代替 values_list()

 username = forms.ModelChoiceField(queryset=Instagram.objects.all())