Extra fields Django-registration Forms - django

Good evening, I am using django-registration for a Web application; By using this, the form that has default django-registration only has 4 fields (username, email, password, repeat password). How to add more fields to this form and store them in the database correctly? Thank you.

I haven't used django-registrations but I found a link which might be helpful to you.
All you need to do is extend the class 'RegistrationForm' and add more fields.
Something like this:
forms.py
import from registration.forms import RegistrationForm
class CustomRegistrationForm(RegistrationForm):
extra_field = forms.EmailField()
extra_field_2 ...
Then, handle the form POST and save these details.
http://django-registration.readthedocs.io/en/2.0.1/forms.html

Related

How to overwrite django-redux default user registration form

When the default django-registration-redux registration page loads, it displays fields for username, email, password, along with labels instructing the user on minimum xters for username, and a list of instructions on setting password.
I want to be able to add some fields to the form, also, I want to remove the list of instruction labels. I could do it with JS but how do i overwrite the class from the django-registration-redux.
Pls i really need help. I have tried subclassing different classes, yet no headway.
You can remove help text with the below code. In your app forms.py, write below code:
from registration.forms import RegistrationForm
class MyRegForm(RegistrationForm):
def __init__(self,*args,**kwargs):
for fieldname in ['username','email', 'password1', 'password2']:
self.fields[fieldname].help_text = None
self.fields[fieldname].labels = None

Django user with extra fields- extending User

Hey I'm new to allauth package.
I would like to know how to write a user model that extends the all auth user.
for example i would like to have a user that has allauth user fields in it and also an image, list of favorite text field.
I would realy appreciate any help!!
You can extend the Django user model using an OneToOneField(User).
Here's the relevant part of the Django docs: Extending the existing User model
IF you need it you can use a custom user model but this will be more difficult. In this case see allauth custom user models and Django documentation
Since you want allauth user fields with some extra fields, you can inherit default user model and add your custom fields to it.
from django.contrib.auth.models import AbstractUser
class ExtendedUser(AbstractUser):
favourites = models.charField(max_length=255)
....
....
In your settings.py file, add this line
AUTH_USER_MODEL = 'users.ExtendedUser'
To store the extra fields when user signs up, use django-allauth signals as in your views as follows.
from django.dispatch import receiver
from allauth.account.signals import user_signed_up
#receiver(user_signed_up)
def user_signed_up(request, user, **kwargs)
#get extra fields from kwargs and save to database

Django-Registration: Account creation that asks for First Name/Last Name?

This question is a follow-up to the solution explained by Muki here:
Problem in adding custom fields to django-registration
I have installed and have been successfully using the Django-registration package. By default, when you create an account using this package, it asks for your username, email address and password. I want it to also ask for (optional) first name + last name. Muki's answer at the link above explains how to do so.
However, Muki left out what should go into the file that he creates in the custom/forms.py. I need to know what the name of the class I should create in here is and what the field definitions should look like.
Can someone please post a sample forms.py that I can use to accomplish what I'm trying to do?
If your custom backend is in the custom folder, then custom/forms.py could be something like this:
from django import forms
from registration.forms import RegistrationForm
class RegistrationFormWithName(RegistrationForm):
first_name = forms.CharField(required=False)
last_name = forms.CharField(required=False)
This adds your two optional fields to the default registration form. To tell your custom backend to use this new form instead of the default you need to change the get_form_class method in custom/__init__.py Muki's answer explains how to do that.
Of course, you'll also need to handle saving the data from the first_name and last_name fields.
Edit:
Your custom/__init__.py needs to look something like this:
from registration.backends.default import DefaultBackend
from registration.backends.custom.forms import RegistrationFormWithName
class CustomBackend(DefaultBackend):
def get_form_class(self, request):
return RegistrationFormWithName
And custom/urls.py needs a line like this:
url(r'^register/$', register, {'backend': 'registration.backends.custom.CustomBackend'}, name='registration_register'),
Change the name of the CustomBackend class in both files to whatever you're calling your new backend.
Have a look at the default backend source to get an idea of the other methods you can override. Hope that helps.
This link explains the process well and works with django-registration 1.0
here are a few extra pointers in addition to the above code.
To update the first name change this in the models.py
def user_registered_callback(sender, user, request, **kwargs):
profile = ExUserProfile(user = user)
profile.is_human = bool(request.POST["is_human"])
user.first_name = request.POST["firstname"]
user.save()
profile.save()
user_registered.connect(user_registered_callback)
and in the forms.py file
class ExRegistrationForm(RegistrationForm):
is_human = forms.BooleanField(label = "Are you human?:")
firstname = forms.CharField(max_length=30)
lastname = forms.CharField(max_length=30)
finally to see the changes on the form create an appropriate template. The profile can be seen in the admin by creating a file called admin.py in your app and write the following code
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from prof.models import ExUserProfile
admin.site.unregister(User)
class UserProfileInline(admin.StackedInline):
model = ExUserProfile
class UserProfileAdmin(UserAdmin):
inlines = [ UserProfileInline, ]
admin.site.register(User, UserProfileAdmin)

Manage UserCreationForm properties and fields

I am new in Django and even after trying thoroughly to find an answer for this question, I couldn't find any. =/
I am using UserCretionForm to create my users and I wanted to know a couple of things:
1 - How can I manage this form's properties? (e.g. I don't want to show the tips like "Required. 30 charact..." or "Enter the same password as above, for verification.")
2 - I want to make it show other customized fields. How can I do it? (please, try to be clear where I have to write the codes you'll show me as I am not an expert =D ). (e.g. Here in Brazil we have some national info I need to store. That is why I need these fields.)
Thanks in advance! (Y)
Changing the default validator messages
You can change the error messages for the default validators via the error_messages argument to a form field.
To find out which validators exist per field, check here: https://docs.djangoproject.com/en/dev/ref/forms/fields/#built-in-field-classes
class MyForm(UserCreationForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['username'].error_messages = {'invalid': 'foobar'}
self.fields['password1'].error_messages = {'required': 'required, man'}
Adding new fields to an existing form
If you want to add new fields, you'd add them via subclassing (which is just python).
If you subclass UserCreationForm and add a field to it, you end up with a new form class that simply has the original's fields and your new ones.
class MyForm(UserCreationForm):
extra_field = forms.CharField()
Overriding the admin form
If you are trying to override the UserCreationForm that the admin site uses by default, you'll have to register a new ModelAdmin for the User moder.
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from foo import MyNewUserCreationForm
class NewUserAdmin(UserAdmin):
add_form = MyNewUserCreationForm
admin.site.unregister(User)
admin.site.register(User, NewUserAdmin)

Making email field unique with Django User admin

There was a nearly similar question: How to make email field unique in model User from contrib.auth in Django
The solution was not perfect: Validating email for uniqueness. The solution provided is rather funny. It disallows modifications to User that leave email intact. How to fix it? Thanks in advance!
in your __init__.py
from django.contrib.auth.models import User
User._meta.get_field_by_name('email')[0]._unique = True
Thanks to Ofri Raviv but what I've seen is not what I needed. So I resolved my own issue and now I'd like to share the tips:
Use username instead of email, exclude email from the form. Mask its label as email.
Subclass User and create a UNIQUE field which receives email addresses, mask it as email, exclude original email field from the form.
It's that simple but took me some time. Hope it help others with the same need.
This method won't make email field unique at the database level, but it's worth trying.
Use a custom validator:
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
def validate_email_unique(value):
exists = User.objects.filter(username=value)
if exists:
raise ValidationError("Email address %s already exits, must be unique" % value)
Then in forms.py:
from django.contrib.auth.models import User
from django.forms import ModelForm
from main.validators import validate_email_unique
class UserForm(ModelForm):
#....
email = forms.CharField(required=True, validators=[validate_email_unique])
#....