【问题标题】:How to save user from non class based view in django?如何从 django 中的非基于类的视图中保存用户?
【发布时间】:2017-04-10 21:21:08
【问题描述】:

我正在尝试从 NON Classe Based View 在我的 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()))

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

【问题讨论】:

  • 您在哪里尝试创建用户 - 您的视图中没有任何内容可以创建或更新用户。
  • 不是 def save() 这样做的吗?如果不是那么那应该是我的错误...但是正如您所看到的,我最后在模型用户中放了一个 def 保存...
  • 好吧,我看你在我看来是这样说的,好的,我会在那里试一试
  • 如果你从不调用 save 方法,你为什么期望它做任何事情?感觉好像我在这里遗漏了一些东西......
  • 好的,让我再解释一下,以前我使用基于类的视图进行保存过程,然后模型中的 def 保存工作得很好,并在管理员用户和我的应用程序中创建了用户用户,但是我必须应用一个过滤器,它似乎只能直接从模板渲染表单字段,所以我将 UsersCreate View 从基于类更改为使用表单渲染模板......我所做的就是,然后def save in models 刚刚停止创建用户,既然你提到我必须在我看来实现它,我意识到这是一个很好的点......让我试试吧

标签: django function templates save django-views


【解决方案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 }}

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

【讨论】:

  • 好的。非常感谢你的帮助,让我打它,我会告诉你的
  • 好吧,我刚刚尝试了这个实现,它引发了一个错误,即 sais ... IntegrityError at users/create/ ... NOT NULL 约束失败:users.organization_id_id
  • 嗨@Prometeo,太好了,这意味着您的用户正在尝试保存。这是更进一步的一步。我不确定为什么在您的用户模型中组织 ID 的 NOT NULL 约束失败,您确实设置了“null=True,blank=True”。我建议尝试先让一些东西工作并从那里调试。从用户窗体的字段和模板中删除“organisation_id”。看看你是否可以保存一个用户。在 'if form.is_valid():' 行之前放置一个打印语句,以查看错误是在表单验证之前还是之后发生。 (您可以在此行之前设置组织 ID:form.instance.organisation
  • 是@user3035260,实际上,即使抛出此错误,用户也会被保存,此时我刚刚找到了让它在我的应用程序中保存用户的方法......我解决了 NOT NULL通过从表单中获取organization_id,然后在调试时将其传递给我的应用程序模型,因为django在调试时问我......像这样......如果form.is_valid():form.organization_id = request.POST.get ('organization_id') ... 然后 ... id=user.id Users.objects.create(user_id=User.objects.get(id=id), organization_id=Users.objects.get(organization_id=form.organization_id ))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
  • 2019-08-29
  • 2015-04-20
  • 2016-02-21
相关资源
最近更新 更多