2017-04-10 40 views
0

我想創建新的用戶到管理員和應用程序從NON Classe Based View在我的django項目,我有模型,視圖和模板,我得到的形式,因爲它在下一步代碼I'm將展示..如何從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()這樣做的嗎?如果不是那麼這應該是我的錯誤...但正如你所看到的,我把DEF保存在模型中的用戶到底... – Prometeo

+0

好吧,我看你說在我看來,好吧我會給它一個嘗試在那裏 – Prometeo

回答

1

如果您不使用通用的基於django類的視圖,則必須自己實現請求的POST和GET功能。最簡單的方法是從您的用戶模型創建一個表單,並根據它是否爲POST請求類型來處理請求。

試試這個:

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())) 

在你的應用程序+ U '/ users_form.html' 文件,你可以訪問UserForm字段如下:

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

我沒有測試過這段代碼,但是這應該會讓你走上正軌。

+0

好吧。非常感謝您的幫助,讓我打開它,我會告訴你回到 – Prometeo

+0

好吧,我只是試過這個實現,它提出了一個錯誤,這是一個錯誤...用戶/創建/ ... NOT NULL約束失敗:users.organization_id_id – Prometeo

+0

嗨@Prometeo,很好,這意味着你的用戶正在嘗試保存。這是更進一步的。我不確定爲什麼組織ID的NOT NULL約束失敗,就像你的用戶模型中一樣,你確實設置了「null = True,blank = True」。 我建議嘗試讓某些東西先工作並從那裏調試。從UserForm的字段和模板中刪除'organisation_id'。看看你是否可以保存一個用戶。在'if form.is_valid():'行之前放置一個打印語句,以查看錶單驗證之前或之後是否發生錯誤。 (您可以在此行之前設置組織標識:form.instance。組織 – user3035260