[英]How can I assign a model to all users upon creation in Django?
I have this model:我有这个模型:
models.py模型.py
class Upload_model(models.Model):
content=models.CharField(max_length=200)
user_name=models.ForeignKey(User)
forms.py表格.py
class upload_form(ModelForm):
class Meta:
model=Upload_model
fields=[“content”]
views.py视图.py
I'm trying to write a function that iterates the creation of the Upload_model to all Users independently.我正在尝试编写一个函数,该函数可以独立地向所有用户迭代 Upload_model 的创建。 But it won't work.
但它不会工作。
def upload_all_user_models(request):
if request.method==”POST”:
form=upload_form(request.POST, request.FILES)
instance=form.save(commit=False)
instance.user_name=User.objects.all()
return redirect(“upload_all_user_models”)
else:
form=upload_form()
return render(request,”uploadpage.html”,{“form”:form})
I want the Upload_model to be assigned to all users upon creation but I seem to be getting a ValueError.我希望在创建时将 Upload_model 分配给所有用户,但我似乎收到了 ValueError。 How can I solve this?
我该如何解决这个问题?
I believe when you use instance.user_name=User.objects.all()
, you're assigning the instance.user_name
to a queryset of User rather than each individual users (ie instance.user_name=[queryset<id=1, id=2>]
).我相信当您使用
instance.user_name=User.objects.all()
,您将instance.user_name
分配给 User 的查询集而不是每个单独的用户(即instance.user_name=[queryset<id=1, id=2>]
)。 You need to set up conditional statements that determine if each user doesn't have the Upload_model, then add and save Upload_model to the user.您需要设置条件语句来确定每个用户是否没有 Upload_model,然后将 Upload_model 添加并保存到用户。
What you're trying to create is going to be complicated due to the order in which model gets created first: the upload_model or the user.由于首先创建模型的顺序:upload_model 或用户,您尝试创建的内容将变得复杂。
Let's say you have 5 users and you create an Upload_model, saving the Upload_model to the 5 users.假设您有 5 个用户并且您创建了一个 Upload_model,将 Upload_model 保存到 5 个用户。 What's going to happen if user #6 comes along?
如果用户#6 出现会发生什么?
I'm sure there's a way you can configure the code to make it how you want it, but at the end of it all, your question is quite vague but all in all you're getting a ValueError because you're trying to assign user_name not to each user, but to a list of users.我确定有一种方法可以配置代码以使其成为您想要的方式,但最后,您的问题很模糊,但总而言之,您收到了 ValueError 因为您正在尝试分配user_name 不是分配给每个用户,而是分配给用户列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.