[英]Django Creating User Account Manually
Django有一個內置的管理頁面,該頁面具有添加/編輯/刪除用戶(及其身份驗證)的功能。
但是,我需要創建一個涉及以下模型的自定義表單
員工/models.py
# Stores profile details such as DoB, Martial Status, TFN and so on
class Profile(models.Model):
user = models.OneToOneField(User)
MARTIAL_STATUS = (
('s', 'Single'),
('m', 'Married'),
('d', 'Divorced'),
('w', 'Widowed')
)
martial = models.CharField(max_length=1, choices=MARTIAL_STATUS, null=True)
tfn = models.CharField(max_length=200, blank=False)
我想要做的是擁有一個表單,用戶可以在其中輸入有關用戶名,first_name等信息以及模型中所需的所有字段。
到目前為止,這是我所做的
請注意,在可以插入其他信息(來自不同模型)之前,需要首先創建一個帳戶的方式
ps:我使用的是Django ver 1.6
如果我理解正確,則需要創建自定義用戶,以將其添加到管理網站中的個人資料表單中。 為什么不使用django shell? 例如:
在manage.py所在的位置,打開終端/命令提示符並鍵入:
>>python manage.py shell
In [1]: from django.contrib.auth.models import User
In [2]: i=User(username="test")
In [3]: i.save()
In [4]: i.set_password('test')
In [5]: i.save()
您可以使用此用戶名/密碼登錄站點。
假設您的管理網址類似於www.mysite.com/admin,則可以使用以下網址直接訪問用戶:www.mysite.com/admin/auth/user/add/。 管理界面也如下所示: 。
如果要添加電子郵件地址和其他數據,則可以按save and continue editing
如下save and continue editing
:
這將導致您更新用戶內容。
如果您不想從管理站點創建用戶,那么使用UserCreationForm來減輕用戶注冊的痛苦。
from django.views.generic.edit import CreateView
from django.contrib.auth.forms import UserCreationForm
urlpatterns = patterns('',
url('^register/', CreateView.as_view(
template_name='register.html',
form_class=UserCreationForm,
success_url='/'
)),
url('^accounts/', include('django.contrib.auth.urls')),
# rest of your URLs as normal
)
您必須在此處創建一個register.html,例如:
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Create" />
</form>
詳細信息: http : //www.obeythetestinggoat.com/using-the-built-in-views-and-forms-for-new-user-registration-in-django.html
我通常從完整的文檔示例開始,然后根據需要對其進行調整。 您保留了Django權限,但還添加了一些自定義權限 。
我不知道您在您的項目中有多遠,但是如果您剛開始,我建議您使用twoscoops模板或Daniel Greenfield的cookiecutter -django 。 它還實現了django all auth庫,這對於社交身份驗證非常有用。
user
模型下拉框附近應有+
符號,以方便用戶快速添加,如下圖所示。
如果user
模型已經在admin
中注冊,我認為您可以即時創建它。
作為Ruddra的上述答案,您已經創建了所有用戶個人資料,然后可以直接填寫表單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.