我决定在我的用户对象中保存关于其他内容的额外数据(创建用户时的对象并存储一些关于我想到的信息)。
问题是我不知道什么会更好,如果创建自定义模型或添加寄存器到我创建的文档。
我不知道mongoengine中的自定义用户模型,但我尝试在用户对象中添加一些额外的字段。我可以轻松地在mongo控制台中添加它,但是我在使用Django视图时遇到了麻烦,所以我尝试了类似的东西,但是没有用。
我的模型如下:
from django.db import models
from mongoengine import *
class User(Document):
username = StringField(max_length=120, required=True)
password = StringField(max_length=120, required=True)
email = StringField(max_length=120, required=True)
my_extra_field= StringField(max_length=120, required=False)
我的forms.py看起来像是
from django import forms
from captcha.fields import CaptchaField
class PostForm(forms.Form):
user = forms.CharField(max_length=256)
password = forms.CharField(widget=forms.PasswordInput)
email = forms.CharField(max_length=256)
#my_extra_field is not defined because is a fixed value and no need to introduce in the form
这就是观点,我遇到了麻烦
def post_form_upload(request):
if request.method == 'GET':
form = PostForm()
else:
# A POST request: Handle Form Upload
form = PostForm(request.POST) # Bind data from request.POST into a PostForm
# If data is valid, proceeds to create a new post and redirect the user
if form.is_valid():
user = form.cleaned_data['user']
password = form.cleaned_data['password']
email = form.cleaned_data['email']
my_extra_field = 500
connect('reborn')
m = User.create_user(user,password,email)
m.gold=500
m.save()
return HttpResponse(m)
e.gold = 500
e.save()
#john.save()
#return HttpResponse("Usuari nou creat")
return render(request, 'game/welcomeuser.html', {
'user': user,
})
return render(request, 'game/post_form_upload.html', {
'form': form,
})
我尝试了不同的方法,但总是出错,所以:
选项1:
if form.is_valid():
user = form.cleaned_data['user']
password = form.cleaned_data['password']
email = form.cleaned_data['email']
my_extra_field = 500
connect('reborn')
m = User.create_user(user,password,email,my_extra_field)
...
给出4个参数和5个参数的错误。
选项2:
if form.is_valid():
user = form.cleaned_data['user']
password = form.cleaned_data['password']
email = form.cleaned_data['email']
connect('reborn')
m = User.create_user(user,password,email)
m.gold=500
m.save()
return HttpResponse(m)
e.gold = 500
e.save()
#john.save()
#return HttpResponse("Usuari nou creat")
return render(request, 'game/welcomeuser.html', {
'user': user,
})
提供错误保存不是用户对象的方法。
不知道如何解决这个问题!!我阅读了手册,但我无法在readthedocs.com上发布的mongoengine文档中找到解决方案
答案 0 :(得分:1)
你使用mongoengine.django.auth.User。它包含用户模型的常见字段,如
如果需要,可以这样添加更多字段
from mongoengine.django.auth import User
from mongoengine import *
class MyUser(User):
sex = StringField(default='M',max_length=1)# M-> male, F-> female
date_of_birth = DateTimeField()
[...]