首页 \ 问答 \ 为自定义Django用户创建登录页面?(Creating a login page for custom Django users?)

为自定义Django用户创建登录页面?(Creating a login page for custom Django users?)

我正在尝试编写一个webapp,允许用户根据兴趣匹配并与其他用户会面。 我处于早期阶段并编写了注册页面,并使用自定义用户模型注册用户。 我希望这些用户能够登录他们的个人资料并进行必要的更改/查看他们的个人资料。

我当前的登录页面总是只是刷新,因为它似乎无法登录任何配置文件,即使凭据很好。

自定义用户型号:

class MyUser(AbstractBaseUser):
    """
    Custom user class.
    """
    first_name = models.CharField(max_length=40)
    last_name = models.CharField(max_length=40)
    email = models.EmailField('email address', unique=True)
    date_of_birth = models.DateField()
    joined = models.DateTimeField(auto_now_add=True)
    course = models.ForeignKey(Course)
    location = models.ForeignKey(Location)
    interests = models.ManyToManyField(Interest)
    bio = models.TextField(blank=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'

    def __unicode__(self):
        return self.email

当前登录表格:

class AuthenticationForm(forms.Form):
    """
    Login form
    """
    email = forms.EmailField(widget=forms.TextInput)
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        fields = ['email', 'password']

最后,当前的登录视图:

def login(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = authenticate(email=request.POST['email'], password=request.POST['password'])
            if user is not None:
                if user.is_active:
                    django_login(request, user)
                    return redirect('/success/')
    else:
        form = AuthenticationForm()
    return render_to_response('login.html', {
        'form': form,
    }, context_instance=RequestContext(request))

我已就该主题进行了大量搜索,但所有项目示例或围绕该主题的帮助似乎已经过时了。

任何有关这方面的帮助将不胜感激! 非常感谢。


I am trying to write a webapp that allows users to match, and meet other users, based on interests. I am in early stages and have written a registration page, and used a custom user model to register users. I'd like those users to be able to login to their profile and make any necessary changes/view their profile.

My current login page is always simply refreshing, as it can't seem to log into any profiles, even though the credentials are fine.

Custom user Model:

class MyUser(AbstractBaseUser):
    """
    Custom user class.
    """
    first_name = models.CharField(max_length=40)
    last_name = models.CharField(max_length=40)
    email = models.EmailField('email address', unique=True)
    date_of_birth = models.DateField()
    joined = models.DateTimeField(auto_now_add=True)
    course = models.ForeignKey(Course)
    location = models.ForeignKey(Location)
    interests = models.ManyToManyField(Interest)
    bio = models.TextField(blank=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'

    def __unicode__(self):
        return self.email

Current Login form:

class AuthenticationForm(forms.Form):
    """
    Login form
    """
    email = forms.EmailField(widget=forms.TextInput)
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        fields = ['email', 'password']

Finally, the current login view:

def login(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = authenticate(email=request.POST['email'], password=request.POST['password'])
            if user is not None:
                if user.is_active:
                    django_login(request, user)
                    return redirect('/success/')
    else:
        form = AuthenticationForm()
    return render_to_response('login.html', {
        'form': form,
    }, context_instance=RequestContext(request))

I have done many searches on the topic, but all project examples, or help around the subject seems fairly outdated.

Any help with this would be greatly appreciated! Many thanks.


原文:https://stackoverflow.com/questions/27273386
更新时间:2022-04-18 14:04

最满意答案

我目前正在这样做的方法是在排序之前在数组上运行一个过滤器,它使用我希望它们具有的默认值填充任何可选字段,如下所示:

.filter('orderByDefault', function(){
  return function(array, key, defaultValue){
    return array.map(function(item){
      if( ! item[key]) item[key] = defaultValue;

      return item;
    });
  };
})

<li ng-repeat="item in items | orderByDefault:'optionalKey':0 | orderBy:['-optionalKey', 'secondaryKey']">{{ item.secondaryKey }}</li>

请参阅此处的示例: http//plnkr.co/edit/W9OwBpd7V7syJXkzxnsV?p = preview

我担心这不是因为我不断地迭代/复制数组而没有那么高效。 它还修改了原始阵列内容,这可能会导致副作用,并且不一定是所希望的。 更重要的是,它仍然无法处理深度密钥嵌套,我绝对需要支持。


Turns out the answer was simpler than I thought, as angular's built-in $parse method easily handles the deep key nesting:

$scope.orderByDefault = function(path, defaultValue){
    var getter = $parse(path);

    return function(item){
        return getter(item) || defaultValue;
    };
};

and

<li ng-repeat="item in items | orderBy:[orderByDefault('optionalKey.nestedKey', 0),'-secondaryKey']:true"></li>

@TODO: handle +/- predicate prefixes so I don't have to reverse the whole array.

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。