python - 为两个模型创建 View

标签 python django django-views

我正在尝试为两个模型创建注册和登录 View 。

我已经扩展了我的用户模型,我想知道如何在 CreateView 中使用扩展以及基本用户模型。我的自定义扩展如下所示(在 models.py 中):

class UserProfile(models.Model):

....

user = models.OneToOneField(User)
display_name = models.CharField(max_length=50, default="null")
avatar = models.ImageField(upload_to=generate_user_folder_avatar,storage=OverwriteStorage(),validators=[is_square_png])

usertype_choices = [
    ('PR', 'Producer'),
    ('ME', 'Mastering Engineer'),
    ('CP', 'Composer'),
    ('SI', 'Singer'),
    ('AR', 'Artist'),
    ('OT', 'Other'),
]

usertype = models.CharField(max_length=2,
                             choices=usertype_choices,
                             default='PR')
daw_choices = [
    ('FL', 'FL Studio'),
    ('AB', 'Live'),
    ('BT', 'Bitwig Studio'),
    ('CS', 'SONAR X3'),
    ('CB', 'Cubase'),
    ('AP', 'Apple Logic'),
    ('RE', 'Reason'),
    ('SO', 'Sony ACID'),
    ('PR', 'Pro Tools'),
    ('ON', 'Studio One'),
    ('MT', 'Digital Performer'),
    ('SA', 'Samplitude'),
    ('MC', 'Mixcraft'),
    ('RP', 'Reaper'),
    ('AR', 'Ardour'),
    ('OT', 'Other'),
    ('NO', 'None'),
]

daw = models.CharField(max_length=2,choices=daw_choices,default='NO')
usergenre = models.CharField(max_length=20,blank=True)
birthday = models.DateField()

joined = models.TimeField(auto_now=True,auto_now_add=False)
followers = models.ManyToManyField(User, related_name="followers",blank=True)
status = models.TextField(max_length=300,blank=True)
pro = models.BooleanField(default=False)

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

我正在使用 django 的内置身份验证系统,但我对如何在一个 View 中使用两个模型,然后将表单放入模板中感到困惑。

我尝试过这个(在views.py中):

from .models import UserProfile
from django.contrib.auth.models import User

class RegisterView(CreateView):
model = ['User', 'UserProfile']
fields = ['username','password','display_name','avatar','usertype','birthday','daw','usergenre']

但这给了我一个错误(参见 http://dpaste.com/0PRZX2R ) 所以我对如何做到这一点感到困惑。英语不是我的母语,所以请原谅这个糟糕的解释。

最佳答案

使用2个形式和前缀, 类 PrimaryForm(ModelForm): 类元: 型号=主要

class BForm(ModelForm):
    class Meta:
        model = B
        exclude = ('primary',)

class CForm(ModelForm):
     class Meta:
        model = C
        exclude = ('primary',)

def generateView(request):
    if request.method == 'POST': # If the form has been submitted...
        primary_form = PrimaryForm(request.POST, prefix = "primary")
        b_form = BForm(request.POST, prefix = "b")
        c_form = CForm(request.POST, prefix = "c")
        if primary_form.is_valid() and b_form.is_valid() and c_form.is_valid(): # All validation rules pass
                print "all validation passed"
                primary = primary_form.save()
                b_form.cleaned_data["primary"] = primary
                b = b_form.save()
                c_form.cleaned_data["primary"] = primary
                c = c_form.save()
                return HttpResponseRedirect("/viewer/%s/" % (primary.name))
        else:
                print "failed"

    else:
        primary_form = PrimaryForm(prefix = "primary")
        b_form = BForm(prefix = "b")
        c_form = Form(prefix = "c")
 return render_to_response('multi_model.html', {
 'primary_form': primary_form,
 'b_form': b_form,
 'c_form': c_form,
  })

Click

关于python - 为两个模型创建 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35260889/

相关文章:

django -/cart/处的DidsNotExist不存在产品匹配查询

python - Python 和 Django 时区格式问题

python - 将字典元素作为参数传递给函数

python - Keras LSTM 层实现背后的架构是什么?

python - pytest.raises 失败 : DID NOT RAISE with try/except

python - Python中的稀疏3d矩阵/数组?

python - Django:将整个模型对象集转换为单个字典

python - django 中未显示点赞数

Django session 不适用于 Heroku

python - Django HttpResponse - 响应文件和内容