我认为models.OneToOneField
,在这种情况下是组字段,是指Group
表的id字段。
但是,通过我的views.py
,如果我在群组id == 6
时没有上传图片,那么该群组的group_id == 3
会发生,但群组覆盖id == 2, 3 and 4
会发生。
对不起,我的英文很奇怪。
简而言之,当Group的id为6时,我认为Django
在Group_Cover的group_id中设置了6。
models.py
@python_2_unicode_compatible
class Group(models.Model):
#group_id = models.AutoField(primary_key=True)
group_name = models.CharField(max_length=50, unique=False, blank=False)
class Meta:
db_table = traceback.extract_stack()[-2][2].lower()
@python_2_unicode_compatible
class Group_Cover(models.Model):
group = models.OneToOneField(Group, primary_key=True)
group_cover = models.ImageField(upload_to="static/image/group/")
class Meta:
db_table = traceback.extract_stack()[-2][2].lower()
views.py
@login_required(login_url='/')
def group_register(request):
import pdb; pdb.set_trace()
from myapp.forms import GroupRegister
from myapp.forms import GroupCover
formset = GroupRegister
formcover = GroupCover
if request.method == 'POST':
form = formset(request.POST)
cover = formcover(request.POST)
if form.is_valid():
from myapp.models import Group
new_group = Group()
new_group.group_name = form.cleaned_data['group_name']
new_group.save()
from myapp.models import Group_Cover
new_cover = Group_Cover()
new_cover.group_cover = request.FILES['group_cover']
new_cover.save()
return redirect('/myapp/group_page/{}'.format(new_group.id))
else:
form = formset()
cover = formcover()
view = {
'form': form,
'cover': cover,
}
template = 'myapp/group/group_register.html'
return render(request, template, view)
答案 0 :(得分:4)
您需要将Group
实例分配给Group_Cover
实例。或多或少如此:
if form.is_valid():
from myapp.models import Group
new_group = Group()
new_group.group_name = form.cleaned_data['group_name']
new_group.save()
from myapp.models import Group_Cover
new_cover = Group_Cover()
new_cover.group_cover = request.FILES['group_cover']
new_cover.group = new_group # This line assigns it
new_cover.save()
答案 1 :(得分:2)
初始化Group_Cover
时未指定该组。
而不是代码:
new_cover = Group_Cover()
使用以下内容:
new_cover = Group_Cover(group=new_group)
答案 2 :(得分:2)
new_cover = Group_Cover(group=new_group)
new_cover.group_cover = request.FILES['group_cover']
new_cover.save()
需要告诉Django您所引用的组(请参阅group=new_group
)