EzDevInfo.com

django-registration

django-registration (redux) now with Django 1.6/1.7/1.8 & Python 3 support django-registration-redux 1.2 documentation — django-registration-redux 1.2 documentation

How to add extra (custom) fields in Django-registration 1.0

I have been reading a lot of questions and answers regarding this, but still no good luck. For example here is a great answer but most probably doesn't apply to django-registration 1.0.

My goal is to add two custom fields, namely organization and position in the sign up form. Note: I am using one-step django registration provided by registration.backend.simple.


Source: (StackOverflow)

"TemplateSyntaxError: 'humanize' is not a valid tag library:" in DJango

While setting up the django-registration module I have run into a bit of trouble. Everything works correctly as far as rendering templates. After trying to test-register I am hit with this error. I do have Django.contrib.humanize in the settings.py file. Any help is appreciated


Source: (StackOverflow)

Advertisements

How to redirect users to a specific url after registration in django registration?

So I am using django-registration app to implement a user registration page for my site. I used Django's backends.simple views which allows the users to immediately login after registration. My question is how do I redirect them to my other app's page located in the same directory as the project.

Here is what my main urls.py looks like:

from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',

    url(r'^accounts/', include('registration.backends.simple.urls')),
    url(r'^upload/', include('mysite.fileupload.urls')),
    # Examples:
    # url(r'^$', 'mysite.views.home', name='home'),
    # url(r'^mysite/', include('mysite.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
)

import os
urlpatterns += patterns('',
        (r'^media/(.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media')}),
)

fileupload is the name of the other app I have in the project directory mysite.

This is what the backends.simple.urls looks like:

"""
URLconf for registration and activation, using django-registration's
one-step backend.

If the default behavior of these views is acceptable to you, simply
use a line like this in your root URLconf to set up the default URLs
for registration::

    (r'^accounts/', include('registration.backends.simple.urls')),

This will also automatically set up the views in
``django.contrib.auth`` at sensible default locations.

If you'd like to customize registration behavior, feel free to set up
your own URL patterns for these views instead.

"""


from django.conf.urls import include
from django.conf.urls import patterns
from django.conf.urls import url
from django.views.generic.base import TemplateView

from registration.backends.simple.views import RegistrationView


urlpatterns = patterns('',
                       url(r'^register/$',
                           RegistrationView.as_view(),
                           name='registration_register'),
                       url(r'^register/closed/$',
                           TemplateView.as_view(template_name='registration/registration_closed.html'),
                           name='registration_disallowed'),
                       (r'', include('registration.auth_urls')),
                       )

And here is the backends.simple.views:

from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.contrib.auth.models import User

from registration import signals
from registration.views import RegistrationView as BaseRegistrationView


class RegistrationView(BaseRegistrationView):
    """
    A registration backend which implements the simplest possible
    workflow: a user supplies a username, email address and password
    (the bare minimum for a useful account), and is immediately signed
    up and logged in).

    """
    def register(self, request, **cleaned_data):
        username, email, password = cleaned_data['username'], cleaned_data['email'], cleaned_data['password1']
        User.objects.create_user(username, email, password)

        new_user = authenticate(username=username, password=password)
        login(request, new_user)
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        return new_user

    def registration_allowed(self, request):
        """
        Indicate whether account registration is currently permitted,
        based on the value of the setting ``REGISTRATION_OPEN``. This
        is determined as follows:

        * If ``REGISTRATION_OPEN`` is not specified in settings, or is
          set to ``True``, registration is permitted.

        * If ``REGISTRATION_OPEN`` is both specified and set to
          ``False``, registration is not permitted.

        """
        return getattr(settings, 'REGISTRATION_OPEN', True)

    def get_success_url(self, request, user):
        return (user.get_absolute_url(), (), {})

I tried the changing the get_success_url function to just return the url I want which is /upload/new but it still redirected me to users/insert username page and gave an error. How do I redirect the user to the upload/new page where the other app resides after registration?


Source: (StackOverflow)

Django login, logout urls and current user name

I'm new to Django and just just got django-registration up and running. Could anyone tell me how to get a get a log-in, log-out url name and the name of the current user in my template. Are these called template tags? IS there a comprehensive list somewhere for all the default variables supplied with Django.

I'm a little lost with this. I've Googled for a while now but I couldn't find anything.

Thanks.


Source: (StackOverflow)

Get django-registration and django-profile working together

I am in process to setting up a new django project and I want to use the provided apps django-registration and django-profile. I installed both of them with easy-install and managed to get the django-registration working fine. My next step would be to connect the django-profile app to the working branch. The django-registration offers a service, that redirects to a URL, which is defined in the settings.py-variable LOGIN_REDIRECT_URL. My guess was, that I can simply paste a url of the django-profile app to connect both. (e.g. '/profiles/'). My settings.py-variable AUTH_PROFILE_MODULE is set on 'registration.User', (trying to use the django-registration model!). But I get a SiteProfileNotAvailable at /profiles/ No exception supplied error. I tried to follow these steps: https://bitbucket.org/ubernostrum/django-registration/src/tip/docs/index.rst https://bitbucket.org/ubernostrum/django-profiles/src/tip/docs/overview.txt But i am not sure, if I done everything properly, namely this paragraph from overview.txt

For default use, create a profile model for your site and specify the AUTH_PROFILE_MODULE setting appropriately. Then add profiles to your INSTALLED_APPS setting, create the appropriate templates and set up the URLs. For convenience in linking to profiles, your profile model should define a get_absolute_url() method which routes to the view profiles.views.profile_detail, passing the username.

So my questions are:

  • Is that a well known error?
  • Is it the right way to set 'registration.User' as AUTH_PROFILE_MODULE?
  • What is ment by "should define a get_absolute_url() method which routes to the view profiles.views.profile_detail, passing the username." in the overview.txt?

Source: (StackOverflow)

Get user information in django templates

What's the best way to get user information from a django template?

For example, if I just want to, for example:

  1. If the user is logged in, display "Welcome [username]"
  2. Otherwise, display the login button.

I'm using django-registration/authentication


Source: (StackOverflow)

Django email app broken lines - maximum line length (and how to change it)?

# settings.py
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'

# view.py
from django.core.mail import send_mail

def send_letter(request):
    the_text = 'this is a test of a really long line that has more words that could possibly fit in a single column of text.'
    send_mail('some_subject', the_text, 'me@test.com', ['me@test.com'])

The Django view code above, results in a text file that contains a broken line:

this is a test of a really long line that has more words that could possibl=
y fit in a single column of text.
-------------------------------------------------------------------------------

Anyone know how to change it so the output file doesn't have linebreaks? Is there some setting in Django that controls this? Version 1.2 of Django.

Update - to back up a level and explain my original problem :) I'm using the django-registration app, which sends an email with an account activation link. This link is a long URL, with a random token at the end (30+ characters), and as a result, the line is breaking in the middle of the token.

In case the problem was using the Django's filebased EmailBackend, I switched to the smtp backend and ran the built-in Python smtpd server, in debugging mode. This dumped my email to the console, where it was still broken.

I'm sure django-registration is working, with zillions of people using it :) So it must be something I've done wrong or mis-configured. I just have no clue what.

Update 2 - according to a post in a Django list, it's really the underlying Python email.MIMEText object, which, if correct, only pushes the problem back a little more. It still doesn't tell me how to fix it. Looking at the docs, I don't see anything that even mentions line-wrapping.

Update 3 (sigh) - I've ruled out it being a MIMEText object problem. I used a pure Python program and the smtplib/MIMEText to create and send a test email, and it worked fine. It also used a charset = "us-ascii", which someone suggested was the only charset to not wrap text in MIMEText objects. I don't know if that's correct or not, but I did look more closely at my Django email output, and it has a charset of "utf-8".

Could the wrong charset be the problem? And if so, how do I change it in Django?

Here's the entire output stream from Django's email:

---------- MESSAGE FOLLOWS ----------
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
Subject: some_subject
From: me@test.com
To: me@test.com
Date: Tue, 17 May 2011 19:58:16 -0000

this is a test of a really long line that has more words that could possibl=
y fit in a single column of text.
------------ END MESSAGE ------------

Source: (StackOverflow)

{% url %} gives me NoReverseMatch error while reverse() returns the url just fine. Why?

I don't know if this SO question is of the same problem that I am about to describe, but it does share the same symptoms. Unfortunately, it still remains unresolved as I am writing.

So here is my problem. I am trying to add James Bennett's django-registration app to my django project. I have pretty much finished configuring it to my needs - custom templates and urls. Just when I thought everything was good to go. I got NoReverseMatch error from using {% url 'testing' item_id=123 %} (I also tried using the view name, myapp.views.test, instead but no luck) in one of the custom templates required by django-registration. Interestingly, I tried reverse('testing', kwargs={'item_id':123}) in the shell and the url was returned just fine. I thought {% url %} uses reverse() in the back-end but why did I get different outcomes?

urls.py: (the URLconf of my site)

urlpatterns = patterns('myapp.views',
    url(r'^test/(?P<item_id>\d+)/$', 'test', name='testing'),
)

activation_email.txt: (the said template. Note it's intentionally in .txt extension as required by django-registration and that shouldn't be the cause of the problem.)

{% comment %}Used to generate the body of the activation email.{% endcomment %}
Welcome to {{ site }}! Please activate your account by clicking on the following link:

{% url 'testing' item_id=123 %}

Note the activation link/code will be expired in {{ expiration_days }} days.

I don't know if it matters but just thought I should mention activation_email.txt is stored in the templates directory of myapp though it is used by django-registration.

Also, I am using django 1.4

I have a feeling that the problem has something to do with the url namespaces, a topic that I have never understood, but it's just a naive guess. (IMO, the django documentation is great in explaining everything about django, except when it comes to url namespaces)


Source: (StackOverflow)

Django - Ajax modal login/registration

I have a project in which I need to pop a modal window for not authenticated users.

This modal will allow to login directly or create an account.

So it will contain two forms:

  • django.contrib.auth.forms.AuthenticationForm
  • registration.forms.RegistrationForm

Modal tabbed forms

Here is my view to get both forms:

def ajax_registration(request):
    obj = {
        'login_form': AuthenticationForm(),
        'registration_form': RegistrationForm(),
    }
    return render(request, 'common/ajax_registration.html', obj)

And my template displaying the forms tabbed

<ul class="nav nav-tabs">
  <li><a rel='nofollow' href="#tab1" data-toggle="tab">{% trans 'Login' %}</a></li>
  <li><a rel='nofollow' href="#tab2" data-toggle="tab">{% trans 'Registration' %}</a></li>
</ul>
<div class="tab-content">
  <div class="tab-pane active" id="tab1">
    {{ login_form|bootstrap }}
  </div>
  <div class="tab-pane" id="tab2">
    {{ registration_form|bootstrap }}
  </div>
</div>

Question is: Since I'm using ajax to display this modal, How can I validate the selected form, preferably using the already written django-registrations register & django.contrib.auth login views ?


Source: (StackOverflow)

django-registration auto create UserProfile

I'm using django-registration and I'm trying to connect to its signals to automatically create a UserProfile.

Signal definition:

from django.dispatch import Signal

# A new user has registered.
user_registered = Signal(providing_args=["user", "request"])

Signal send by django-registration:

    def register(self, request, **kwargs):
    """
    Create and immediately log in a new user.

    """
    username, email, password = kwargs['username'], kwargs['email'], kwargs['password1']
    User.objects.create_user(username, email, password)

    # authenticate() always has to be called before login(), and
    # will return the user we just created.
    new_user = authenticate(username=username, password=password)
    login(request, new_user)
    signals.user_registered.send(sender=self.__class__,
                                 user=new_user,
                                 request=request)
    return new_user

My signal connect:

from registration.signals import *
from core.models import UserProfile
from django.contrib.auth.models import User

def createUserProfile(sender, instance, **kwargs):
    UserProfile.objects.get_or_create(user=instance)

user_registered.connect(createUserProfile, sender=User)

Needless to say no UserProfile is being created. What am I missing here?

Thanks a lot!

EDIT: I moved my connect() and its corresponding method to a model.py and still no luck.

New code:

from django.db import models

from django.contrib import auth
from django.contrib.auth import login
from core.forms import AuthForm
from registration.signals import *
from django.contrib.auth.models import User


# Create your models here.

class UserProfile(models.Model) :
    user = models.ForeignKey(User, unique=True)

    def __unicode__(self):
        return self.user.username


def createUserProfile(sender, instance, **kwargs):
    print "creating profile"
    UserProfile.objects.get_or_create(user=instance)

user_registered.connect(createUserProfile, sender=User)

I'm using Pycharm to debug, and in the very beginning my breakpoint on user_registered.connect() is hit. So I assume that connect() is being registered correctly. However, I still don't see createUserProfile being run. Anything else I'm missing?

Thanks!

ANSWER: Doh. My connect and receiver code was wrong. Correct code:

def createUserProfile(sender, user, request, **kwargs):
UserProfile.objects.get_or_create(user=user)

user_registered.connect(createUserProfile)

Realized it after I read signals.py in django-registration


Source: (StackOverflow)

Django - Create user profile on user creation

I'm following Django documentation here in order to achieve a simple objective: Create a user profile as soon as a new user is created.

I have an 'accounts' app and my accounts.models looks like this:

# -*- coding: utf-8 -*-
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from main.models import Store

class UserProfile(models.Model):

    GENRE_CHOICES = (
        ('m', 'Masculino'),
        ('f', 'Feminino'),
    )
    MARITAL_STATUS_CHOICES = (
        ('s', 'Solteiro'),
        ('c', 'Casado'),
        ('d', 'Divorciado'),
        ('v', 'Viúvo'),
    )

    user = models.ForeignKey(User, unique=True)
    birth_date = models.DateField()
    genre = models.CharField(max_length=1, choices=GENRE_CHOICES)
    address = models.CharField(max_length=150)
    postal_code_4 = models.PositiveIntegerField()
    postal_code_3 = models.PositiveIntegerField()
    locatity = models.CharField(max_length=30)
    marital_status = models.CharField(max_length=1, choices=MARITAL_STATUS_CHOICES)
    child_amount = models.PositiveSmallIntegerField()
    is_merchant = models.BooleanField(default=False)
    store = models.ForeignKey(Store, null=True)

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

Everything looks fine to me but when trying to add a new user (using django admin), instead of having a newly created user and user profile, I get the following error: InternalError at /admin/auth/user/add/ current transaction is aborted, commands ignored until end of transaction block

Here is the traceback error part:

/djangoProjects/lwboanova/lwboanova/apps/accounts/models.py in create_user_profile

34: UserProfile.objects.create(user=instance)

It seems like an integrity error but I'm not getting the reason for it.

Would be great if any of ya could give me some help on this.


Source: (StackOverflow)

Django registration alternatives

I'm looking at django-registration. It's in alpha 0.8, and hasn't been updated for 12/13 months. But it seems this is what most people use? I'm just wondering if there is a production standard package out there for managing users on a django site, or do people tend to roll their own?


Source: (StackOverflow)

Different user profiles with django-profiles & django-registration

My models.py:

USER_TYPES = (                                                                                                                                                                   
    ('D', 'Demo'   ),                                                                                                                                                               
    ('F', 'Free'   ),
    ('P', 'Premium'),                                                                                                                                                        
)                                                                                                                                                                                                                                                                                                                                                                

class BaseProfile(models.Model):                                                                                                                                                 
    user      = models.OneToOneField(User, primary_key=True)                                                                                                                     
    user_type = models.CharField(max_length=1, blank=True, choices=USER_TYPES)                                                                                                           

class DemoProfile(models.Model):                                                                                                                                                 
    user      = models.OneToOneField(User, primary_key=True)                                                                                                                     
    demo      = models.CharField(max_length=10, blank=True) 
    ...

class FreeProfile(models.Model):                                                                                                                                                 
    user      = models.OneToOneField(User, primary_key=True)                                                                                                                     
    free      = models.CharField(max_length=10, blank=True) 
    ...

class PremiumProfile(models.Model):                                                                                                                                                 
    user      = models.OneToOneField(User, primary_key=True)                                                                                                                     
    premium    = models.CharField(max_length=10, blank=True) 
    ...

class ProxyProfile(BaseProfile):                                                                                                                                                 
    class Meta:                                                                                                                                                                  
        proxy = True             
    def get_profile(self):                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
        if self.user_type == 'D':                                                                                                                                              
            return DemoProfile._default_manager.get(user__id__exact=self.user_id)                                                                                              
        elif self.user_type == 'F':                                                                                                                                            
            return FreeProfile._default_manager.get(user__id__exact=self.user_id)                                                                                              
        else:                                                                                                                                                                  
            return PremiumProfile._default_manager.get(user__id__exact=self.user_id)                                                                                                         

I use BaseProfile to map user_id to specific user_type. I wanted to use ProxyProfile as proxy which loads user_type depending profiles to ModelForm as shown below

Content of my forms.py:

class ProfileForm(ModelForm):                                                                                                                                                    
...                                                                                                                                                                                 
    class Meta:                                                                                                                                                                 
        model   = ProxyProfile                                                                                                                                                  
        exclude = ('user','user_type')   
...

ProfileForm is provided to django-profiles using following code in urls.py:

urlpatterns += patterns('',                                                                                                                                                      
    url(r'^profiles/edit/', edit_profile,                                                                                                                                        
        {'form_class': ProfileForm},                                                                                                                                             
        name='profiles_edit_profile'),                                                                                                                                           
    (r'^profiles/',include('profiles.urls')),                                                                                                                                    
)

I've also set in settings.py:

AUTH_PROFILE_MODULE = 'main.ProxyProfile'

During user registration all db data is filled correctly (it looks like everything is OK). I register using form passed to django-registration:

urlpatterns += patterns('',                                                                                                                                                      
    url(r'^register/$', register,                                                                                                                                                
        {'form_class': UserRegistrationForm},                                                                                                                                    
        name='registration.views.register'),                                                                                                                                     
    (r'', include('registration.urls')),                                                                                                                                         
) 

from forms.py:

class UserRegistrationForm(RegistrationFormUniqueEmail, RegistrationFormTermsOfService):                                                                                         
    utype        = forms.ChoiceField(choices=USER_CHOICES)                                                                                               

    def save(self, profile_callback=None):                                                                                                                                       
        new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'],
                                                                    password.self.cleaned_data['password1'],                                                                     
                                                                    email=self.cleaned_data['email'],                                                                            
                                                                    )                                                                                                            
        new_base_profile = BaseProfile(user=new_user, user_type=self.cleaned_data['utype'])                                                                                      
        if self.cleaned_data['utype'] == "D":                                                                                                                                    
            new_profile = DemoProfile(user=new_user)                                                                                                                             
        if self.cleaned_data['utype'] == "F":                                                                                                                                    
            new_profile = FreeProfile(user=new_user)                                                                                                                             
        if self.cleaned_data['utype'] == "P":                                                                                                                                    
            new_profile = PremiumProfile(user=new_user)                                                                                                                             
        new_profile.save()                                                                                                                                                       
        new_base_profile.save()                                                                                                                                                  
        return new_user                

And registration phase works OK.

I've problem with profile edit/details pages. My profiles filtered in ProxyProfile model and used as FormModel in ProfileForm are not rendered (I can't see profile specific fields are not rendered to HTML page) Maybe there is some other way (more like Django way :)) to do this (select and render profile model depending on user_type field which is related to User model).

Thanks in advance :)


Source: (StackOverflow)

How do I test sending an email with Django registration on a local computer (Mac 10.7)?

I never tried sending emails programmatically before. Do I need to set up a SMTP server on my local machine or something? Or can I use someone else's SMTP server (maybe Gmail's)?

Everytime Django registration is trying to send an email I get the error [Errno 61] Connection refused.

Here is the traceback. And a partial screenshot of the error screen:

I would appreciate any introductory explanations or beginner tutorials with Django and emails. Thanks!


Source: (StackOverflow)

Already Registered at /appname/: The model User is already registered

I'm trying to connect the django.contrib.auth User with my own UserProfile, and I'm getting an 'AlreadyRegistered' error when I go on the site.

Here's the traceback:

Environment:


Request Method: GET
Request URL: myurl.com/django/appname/

Django Version: 1.4.2
Python Version: 2.6.8
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'polls',
 'appname',
 'registration',
 'django.contrib.humanize')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response
  101.                             request.path_info)
File "/usr/lib/python2.6/site-packages/django/core/urlresolvers.py" in resolve
  298.             for pattern in self.url_patterns:
File "/usr/lib/python2.6/site-packages/django/core/urlresolvers.py" in url_patterns
  328.         patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/lib/python2.6/site-packages/django/core/urlresolvers.py" in urlconf_module
  323.             self._urlconf_module = import_module(self.urlconf_name)
File "/usr/lib/python2.6/site-packages/django/utils/importlib.py" in import_module
  35.     __import__(name)
File "/var/www/mysite/mysite/urls.py" in <module>
  3. admin.autodiscover()
File "/usr/lib/python2.6/site-packages/django/contrib/admin/__init__.py" in autodiscover
  29.             import_module('%s.admin' % app)
File "/usr/lib/python2.6/site-packages/django/utils/importlib.py" in import_module
  35.     __import__(name)
File "/var/www/mysite/appname/admin.py" in <module>
  4. admin.site.register(User)
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py" in register
  80.                 raise AlreadyRegistered('The model %s is already registered' % model.__name__)

Exception Type: AlreadyRegistered at /appname/
Exception Value: The model User is already registered

I'm pretty sure this stems from my app's models.py, seeing as that's all I changed in a major way, I believe.

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class Tag(models.Model):
        pics = models.ManyToManyField('Picture', blank=True)
        name = models.CharField(max_length=30)

        def __unicode__(self):
                return self.name

class UserProfile(models.Model):
        name = models.CharField(max_length=20)
        date_joined = models.DateTimeField('date joined')
        auth_user = models.OneToOneField(User)

        def __unicode__(self):
                return self.name

def create_user_profile(sender, instance, created, **kwargs):
        if created:
                UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

class Picture(models.Model):
        name = models.CharField(max_length=100)
        pub_date = models.DateTimeField('date published')
        tags = models.ManyToManyField('Tag', blank=True)
        owner = models.ForeignKey('UserProfile')
        content = models.ImageField(upload_to='instaton')

        def __unicode__(self):
                return self.name

class Comment(models.Model):
        content = models.CharField(max_length=500)
        date = models.DateTimeField('date commented')
        commenter = models.ForeignKey('UserProfile')
        pic = models.ForeignKey('Picture')

        def __unicode__(self):
                return self.content

Source: (StackOverflow)