Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在使用两个模型保存到表单之前设置ForeignKey_Python_Django - Fatal编程技术网

Python 在使用两个模型保存到表单之前设置ForeignKey

Python 在使用两个模型保存到表单之前设置ForeignKey,python,django,Python,Django,我到处寻找这个,但找不到任何适合我的情况。我的应用程序中有一个User和UserProfilemodelform 我的forms.py如下所示: from django import forms from django.forms import ModelForm from django.contrib.auth.models import User from .models import UserProfile class UserForm(ModelForm): class Me

我到处寻找这个,但找不到任何适合我的情况。我的应用程序中有一个
User
UserProfile
modelform

我的forms.py如下所示:

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

class UserForm(ModelForm):

    class Meta:
        model = User
        fields = ('username', 'email', 'password')

class  UserProfileForm(ModelForm):

    class Meta:
        model = UserProfile
        fields = ('display_name', 'avatar', 'birthday', 'usertype', 'daw', 'usergenre')
def RegisterView(request):
    if request.method == 'POST':
        form = UserForm(request.POST, prefix='uf')
        form2 = UserProfileForm(request.POST, prefix='upf')
        if form.is_valid():
            if form2.is_valid():
                form.save()
                form2.user = form.username
                form2.save()
                return HttpResponseRedirect('/')
    elif request.method == 'GET':
        form = UserForm(prefix='uf')
        form2 = UserProfileForm(prefix='upf')            

    return render(request, 'profile/register.html', {'form': form, 'form2': form2})
我的views.py如下所示:

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

class UserForm(ModelForm):

    class Meta:
        model = User
        fields = ('username', 'email', 'password')

class  UserProfileForm(ModelForm):

    class Meta:
        model = UserProfile
        fields = ('display_name', 'avatar', 'birthday', 'usertype', 'daw', 'usergenre')
def RegisterView(request):
    if request.method == 'POST':
        form = UserForm(request.POST, prefix='uf')
        form2 = UserProfileForm(request.POST, prefix='upf')
        if form.is_valid():
            if form2.is_valid():
                form.save()
                form2.user = form.username
                form2.save()
                return HttpResponseRedirect('/')
    elif request.method == 'GET':
        form = UserForm(prefix='uf')
        form2 = UserProfileForm(prefix='upf')            

    return render(request, 'profile/register.html', {'form': form, 'form2': form2})
现在看,我的问题是,当我保存UserProfile实例时,它没有与新保存的
用户
实例相关的所需
ForeignKey(User)
集,在保存之前如何设置?显然,我必须在
用户
实例保存后执行此操作,但是如何获取我们刚刚创建的用户实例的“request.User”,并将UserProfile中的
ForeignKey
设置为该值

models.py

from django.db import models
from django.core.exceptions import ValidationError
from django.core.files.images import get_image_dimensions
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from Submission.storage import OverwriteStorage

# Create your models here.
class UserProfile(models.Model):

    def is_square_png(self):
        if not self.name.endswith('.png'):
            raise ValidationError("You may only upload .png files!")
        else:
            w, h = get_image_dimensions(self)
            if not h == w:
                raise ValidationError("This picture is not square! Your picture must be equally wide as its height.")
            else:
                if not (h + w) >= 1000:
                    raise ValidationError("This picture is too small! The minimum dimensions are 500 by 500 pixels.")
                else:
                    if not (h + w) < 2000:
                        raise ValidationError("This picture is too big! The maximum dimensions are 1000 by 1000 pixels.")
        return self

    def generate_user_folder_avatar(instance, filename):
        return "static/users/%s/%s.png" % (instance.user, 'avatar')

    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],blank=True)

    usertype_choices = [
        ('PR', 'Producer'),
        ('ME', 'Mastering Engineer'),
        ('CP', 'Composer'),
        ('SI', 'Singer'),
        ('AR', 'Artist'),
        ('DJ', 'Disk Jockey'),
        ('LI', 'Listener'),
        ('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(blank=True)

    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)
来自django.db导入模型的

从django.core.exceptions导入ValidationError
从django.core.files.images导入获取图像尺寸
从django.contrib.auth.models导入用户
从django.db.models.signals导入后保存
从Submission.storage导入覆盖存储
#在这里创建您的模型。
类UserProfile(models.Model):
def为方形png(自):
如果不是self.name.endswith('.png'):
引发ValidationError(“您只能上载.png文件!”)
其他:
w、 h=获取图像尺寸(自身)
如果不是h==w:
raise ValidationError(“此图片不是正方形!您的图片必须与其高度相等。”)
其他:
如果不是(h+w)>=1000:
raise ValidationError(“此图片太小!最小尺寸为500 x 500像素。”)
其他:
如果不是(h+w)<2000:
raise ValidationError(“此图片太大!最大尺寸为1000 x 1000像素。”)
回归自我
def生成用户文件夹化身(实例,文件名):
返回“static/users/%s/%s.png”%(instance.user,“avatar”)
用户=模型。OneToOneField(用户)
display\u name=models.CharField(最大长度=50,默认值为null)
avatar=models.ImageField(上传到=generate\u user\u folder\u avatar,storage=overwritestreage(),验证器=[is\u square\u png],blank=True)
用户类型_选项=[
(‘PR’、‘生产者’),
(‘我’、‘大师级工程师’),
('CP','Composer'),
("SI","Singer"),,
(‘AR’、‘艺术家’),
(‘DJ’、‘磁盘骑师’),
(‘LI’、‘Listener’),
(‘OT’、‘其他’),
]
usertype=models.CharField(最大长度=2,
choices=usertype\u选项,
默认值(='PR')
daw_选项=[
('FL','FL Studio'),
('AB','Live'),
('BT','Bitwig Studio'),
(‘CS’、‘声纳X3’),
('CB','Cubase'),
('AP','Apple Logic'),
(‘RE’、‘Reason’),
(“Sony ACID”),
(“PR”、“Pro工具”),
("ON","Studio One"),,
(‘MT’、‘数字表演者’),
(‘SA’、‘Samplitude’),
(‘MC’、‘Mixcraft’),
(‘RP’、‘收割者’),
('AR','Ardour'),
(‘OT’、‘其他’),
(‘否’、‘无’),
]
daw=models.CharField(max_length=2,choices=daw_choices,默认为'NO')
usergenre=models.CharField(最大长度=20,空白=True)
生日=型号.日期字段(空白=真)
joined=models.TimeField(auto\u now=True,auto\u now\u add=False)
followers=models.ManyToManyField(用户,相关的_name=“followers”,blank=True)
status=models.TextField(最大长度=300,空白=True)
pro=models.BooleanField(默认值=False)

在您的模型中将其作为外键
用户

from yourapp.forms import UserForm, UserProfileForm

def register(request):
    # Like before, get the request's context.
    context = RequestContext(request)

    # A boolean value for telling the template whether the registration was successful.
    # Set to False initially. Code changes value to True when registration succeeds -- which is optional.
    registered = False

    # If it's a HTTP POST, we're interested in processing form data.
    if request.method == 'POST':
        # Attempt to grab information from the raw form information.
        # Note that we make use of both UserForm and UserProfileForm.
        form = UserForm(data=request.POST, prefix='upf')
        form2 = UserProfileForm(data=request.POST, prefix='upf')

        # If the two forms are valid...
        if form.is_valid() and form2.is_valid():
            # Save the user's form data to the database.
            user_reg = form.save()

            # Now we hash the password with the set_password method.
            # Once hashed, we can update the user object.
            user_reg.set_password(user_reg.password)
            user_reg.save()

            # Now sort out the UserProfile instance.
            # Since we need to set the user attribute ourselves, we set commit=False.
            # This delays saving the model until we're ready to avoid integrity problems.
            profile = form2.save(commit=False)
            profile.user = user_reg

            # Did the user provide a profile picture?
            # If so, we need to get it from the input form and put it in the UserProfile model.
            if 'avatar' in request.FILES:
                profile.avatar = request.FILES['avatar']

            # Now we save the UserProfile model instance.
            profile.save()

            # Update our variable to tell the template registration was successful --- which is optional.
            registered = True

        # Invalid form or forms - mistakes or something else?
        # Print problems to the terminal.
        # They'll also be shown to the user.
        else:
            print form.errors, form2.errors

    # Not a HTTP POST, so we render our form using two ModelForm instances.
    # These forms will be blank, ready for user input.
    else:
        form = UserForm(prefix='upf')
        form2 = UserProfileForm(prefix='upf')

    # Render the template depending on the context.
    return render_to_response(
            'profile/register.html',
            {'form': form, 'form2': form2, 'registered': registered},
        context)

编辑并显示您的模型您的愿望就是我的命令。您的愿望得到了满足并得到了执行。如果我的回答没有帮助,请检查我刚才添加的注释。未定义用户。我已经看到我会立即编辑,现在当我按submit时,每个字段都会显示“此字段是必需的”。哪个字段。。。那块地叫什么?你为什么这么想?