2017-04-10 13 views
0

私は管理者とアプリケーションに新しいユーザーを作成しようとしていますNON Classe Based View私のdjangoプロジェクトでは、次のようにフォームを取得しているモデル、ビュー、テンプレートがありますコード - 私は示すことだろう。..djangoで非クラスベースのビューからユーザーを保存するには?

models.py

class Users(models.Model): 

# Fields 
username = models.CharField(max_length=255, blank=True, null=True) 
password = models.CharField(max_length=12, blank=True, null=True) 
organization_id = models.ForeignKey('ip_cam.Organizations', editable=True, null=True, blank=True) 
slug = extension_fields.AutoSlugField(populate_from='created', blank=True) 
created = models.DateTimeField(auto_now_add=True, editable=False) 
last_updated = models.DateTimeField(auto_now=True, editable=False) 

# Relationship Fields 
user_id = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True) 

class Meta: 
    ordering = ('-created',) 

def __str__(self): 
    return u'%s' % self.user_id 

def get_absolute_url(self): 
    return reverse('ip_cam_users_detail', args=(self.slug,)) 


def get_update_url(self): 
    return reverse('ip_cam_users_update', args=(self.slug,)) 

def __unicode__(self): # __str__ 
    self.organization_id=self.request.POST.get('organization_id') 
    return unicode(self.user_id, self.organization_id) 

# This overrides the standard save method for a user, creating a new user in the admin and getting it to the template at the same time   
def save(self, *args, **kwargs): 
    self.password = make_password(self.password) 
    self.user_id, created = User.objects.get_or_create(username=self.username, password=self.password, is_staff=True) 
    self.user_id.groups.add(Group.objects.get(name='admin')) 
    self.id = self.user_id.id 
    super(Users, self).save(*args, **kwargs) 

views.py

def UsersCreate(request): 
model = Users 

var = {} 
var = user_group_validation(request) 
userInc = Users.objects.get(id=request.user.id).organization_id.pk 
request.session['userInc'] = userInc 

if var['group'] == 'superuser': 
    object_list = Users.objects.all() 
    organization = Organizations.objects.all() 
    roles_choice = DefaultLandingPage.objects.all() 
if var['group'] == 'admin' or var['group'] == 'user': 
    object_list = Users.objects.filter(organization_id=request.session['userInc']) 
    organization = Organizations.objects.filter(id=request.session['userInc']) 
    roles_choice = DefaultLandingPage.objects.exclude(role=1) 
url = request.session['url'] 
tpl = var['tpl'] 
role = var['group'] 
organization_inc = Organizations.objects.filter(id=request.session['userInc']) 

template = get_template(app+u'/users_form.html') 

return HttpResponse(template.render(locals())) 

ここでの問題は、それを上書きしようとしているときに保存が機能していないということです。ユーザーはまったく作成されていません...今回は間違っていますか?前もって感謝します。

+0

ユーザーを作成しようとしています。ユーザーを作成または更新するビューはありません。 –

+0

はそれを行うためにdef save()を行いませんか?そうでなければそれは私の間違いでなければなりません...しかし、あなたが見ることができるように、私は最後にモデルのユーザーの中にデフを保存します... – Prometeo

+0

大丈夫、私はあなたが私の意見で言ったのを見ました。試してみてください – Prometeo

答えて

1

一般的なdjangoクラスベースのビューを使用していない場合は、リクエストのPOSTとGET機能を自分で実装する必要があります。最も簡単なのは、ユーザー・モデルからフォームを作成し、それがPOST要求タイプかどうかに基づいて要求を処理することです。

はこの試してみてください:あなたのアプリ+ U '/ users_form.html' ファイルで

forms.py(https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/

from django.forms import ModelForm 
from .models import User 

class UserForm(ModelForm): 
    class Meta: 
     model = Users 
     fields = ['username', 'organization_id'] 

views.py

from .models import User 
from .forms import UserForm 

def UsersCreate(request): 
    # This function can hadle both the retrieval of the view, as well as the submission of the form on the view. 
    if request.method == 'POST': 
     form = UserForm(request.POST, request.FILES) 
     if form.is_valid(): 
      form.save() # This will save the user. 
      # Add the user's role in the User Role table below? 
     # 
    else: 

     # The form should be passed through. This will be processed when the form is submitted on client side via this functions "if request.method == 'POST'" branch. 
     form = UserForm() 

     var = user_group_validation(request) 
     userInc = Users.objects.get(id=request.user.id).organization_id.pk 
     request.session['userInc'] = userInc 

     if var['group'] == 'superuser': 
      object_list = Users.objects.all() 
      organization = Organizations.objects.all() 
      roles_choice = DefaultLandingPage.objects.all() 
     if var['group'] == 'admin' or var['group'] == 'user': 
      object_list = Users.objects.filter(organization_id=request.session['userInc']) 
      organization = Organizations.objects.filter(id=request.session['userInc']) 

      # The line below will ensure that the the dropdown values generated from the template will be filtered by the 'request.session['userInc']' 
      form.organisation_id.queryset = organization 

      roles_choice = DefaultLandingPage.objects.exclude(role=1) 
     url = request.session['url'] 
     tpl = var['tpl'] 
     role = var['group'] 
     organization_inc = Organizations.objects.filter(id=request.session['userInc']) 

     template = get_template(app+u'/users_form.html') 

    return HttpResponse(template.render(locals())) 

を、あなたがアクセスすることができますユーザーフォームフィールドは次のようになります。

<!-- inside your <form> tag add: -->> 
{{ form.username }} 
{{ form.organisation_id }} 

私はこのコードをテストしていませんが、これは正しい軌道に乗るはずです。

+0

ok。 – Prometeo

+0

よく、私はちょうどこの実装を試してみました、そして、それはsaisというエラーを起こしています... IntegrityError at users/create/... NOT NULL制約失敗:users.organization_id_id – Prometeo

+0

こんにちは@Prometeo、これは、あなたのユーザーが保存しようとしていることを意味します。これはさらに進歩です。あなたのUserモデルのようにNOT NULL制約が組織IDに失敗した理由がわからないときは、 "null = True、blank = True"が設定されています。 私はまず何かを取得してそこからデバッグしようとするとよいでしょう。 UserFormのフィールドとテンプレートから 'organisation_id'を削除します。ユーザーを保存できるかどうかを確認してください。 'form.is_valid():'行の前にprintステートメントを置いて、フォームの検証の前後にエラーが発生していないかどうかを確認します。 (あなたはこの行の前に組織IDを設定することができます:form.instance。組織 – user3035260

関連する問題