如何在django中保存用户从非基于类的视图?

时间:2017-04-10 21:21:09

标签: django function templates save django-views

我正在尝试通过我的django项目中的 NON Classe Based View 为管理员和应用创建新用户,我有模型,视图和模板,我在哪里获取表单因为它将在下一个代码中显示...

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

这里的问题是当试图覆盖它时保存不起作用,根本没有创建用户......你能不能帮助我看看这次我做错了什么?提前谢谢。

1 个答案:

答案 0 :(得分: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()))

在您的app + u'/ users_form.html'文件中,您可以按如下方式访问UserForm字段:

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

我没有测试过这段代码,但这应该让你走上正轨。