I have a problem with adding new custom user to the database. I know thare's some threads about it on the internet but I couldn't find solution for my problem. After hitting "Submit" button in registration page which template is here:
{% extends 'strona/Main.html' %}
{% block body %}
< form action="" method="post" enctype="multipart/form-data" >
{% csrf_token %}
{% for field in form %}
{{ field.label_tag }}
< /br >
{{ field }}
< /br >
< /br >
{% endfor %}
< button type="submit" class="btn btn-success">Submit</button >
< /form >
{% endblock %}
it keeps saying that: "Cannot assign "< SimpleLazyObject: < django.contrib.auth.models.AnonymousUser object at 0x038B5A70 >>": "SUser.user" must be a "User" instance."
Source Codes:
VIEWS.PY
class RegPanelView(View):
panel = RegPanel
template_name = 'strona/RegistrationTemp.html'
registration = None
def get(self, request):
form = self.panel(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
# form = self.panel(data=request.POST)
form = self.panel(request.POST)
if form.is_valid():
# user = form.save(commit=False)
# username = form.cleaned_data['username']
password1 = form.cleaned_data['password1']
password2 = form.cleaned_data['password2']
if password1 == password2:
newuser = form.save(commit=False)
newuser.user = request.user
newuser.save()
return redirect('strona:index')
return render(request, self.template_name, {'form': form})
MODELS.PY
class SUser(models.Model):
# User = user_model()
user = models.OneToOneField(User, on_delete=models.CASCADE)
username = models.CharField(max_length=200)
# last_login = models.DateTimeField(blank=True)
# is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
relations = models.ManyToManyField('self')
# is_anonymous = False
# is_authenticated = True
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ('', )
FORMS.PY
class RegPanel(UserCreationForm):
# password = forms.CharField(max_length=16, widget=forms.PasswordInput)
# first_name = forms.CharField(max_length=100, required=False)
# last_name = forms.CharField(max_length=100, required=False)
# is_staff = forms.BooleanField(required=False)
# birthday = forms.DateField(required=False)
class Meta:
model = SUser
fields = ['username', 'is_staff', 'first_name', 'last_name']
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
# user.set_password(self.cleaned_data["passwosrd1"])
if commit:
user.set_password(self.cleaned_data["password1"])
user.save()
# if commit:
# user.save()
return user
SETTINGS.PY:
AUTH_USER_MODEL = 'auth.User'
EDIT
FULL ERROR TRACEBACK:
File
"C:\Users\Dawid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.3-py3.5.egg\django\core\handlers\exception.py"
in inner
39. response = get_response(request)
File
"C:\Users\Dawid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.3-py3.5.egg\django\core\handlers\base.py"
in _get_response
187. response = self.process_exception_by_middleware(e, request)
File
"C:\Users\Dawid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.3-py3.5.egg\django\core\handlers\base.py"
in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File
"C:\Users\Dawid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.3-py3.5.egg\django\views\generic\base.py"
in view
68. return self.dispatch(request, *args, **kwargs)
File
"C:\Users\Dawid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.3-py3.5.egg\django\views\generic\base.py"
in dispatch
88. return handler(request, *args, **kwargs)
File "C:\Users\Dawid\PycharmProjects\Zadanie\strona\views.py" in post
97. newuser.user = request.user
File
"C:\Users\Dawid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.3-py3.5.egg\django\db\models\fields\related_descriptors.py"
in set
211. self.field.remote_field.model._meta.object_name,
Exception Type: ValueError at /index/register/ Exception Value: Cannot
assign "< SimpleLazyObject: >": "SUser.user" must be a "User" instance.
Please could someone help me out?
Kind regards.
Django lazy loads request.user so that it can be either User or AnonymousUser depending on the authentication state.
if request.user.is_authenticated(): #then request.user will be `User` instance
newuser = form.save(commit=False)
newuser.user = request.user
newuser.save()
Related
I just started learning Django and Python some weeks back. Working on a project sign up page, everything works perfectly except that form errors are not displaying on the form itself but redirected to a debug error page with the below
ValidationError at /register/
['Username exists']
Request Method: POST
Request URL: http://127.0.0.1:8000/register/
Django Version: 3.2.5
Exception Type: ValidationError
Exception Value:
['Username exists']
During a new user profile registration, i am checking if the username used to register already exists or not and if it exists, i want to display an error to user that Username already exists.
Please see my code below:
forms.py
class RegistrationForm(forms.Form):
first_name = forms.CharField(label='First Name')
last_name = forms.CharField(label='Last Name')
username = forms.CharField(label='Username')
password = forms.CharField(
label='Password', widget=forms.PasswordInput(), min_length=8)
password_confirm = forms.CharField(
label='Confirm Password', widget=forms.PasswordInput())
email_address = forms.EmailField(label='Email')
phone_number = PhoneNumberField(label='Phone Number')
whatsapp_number = PhoneNumberField(label='WhatsApp Number', required=False)
COUNTRY_CHOICES = [
('', 'Choose...'),
]
country = forms.ChoiceField(label='Country', choices=COUNTRY_CHOICES)
referral_id = forms.CharField(label='Referral ID', required=False)
license_agreement = forms.BooleanField(
label='I agree to all the Terms and Conditions')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_id = 'create-account-form'
self.helper.form_action = 'register'
self.helper.form_show_errors = True
self.helper.layout = Layout(
Row(
Column('first_name'),
Column('last_name'), css_class='g-2'
),
Row(
Column(
PrependedText('username', '#')
),
Column('country'), css_class='g-2'
),
Row(
Column('password'),
Column('password_confirm'),
Column('referral_id'),
css_class='g-2'
),
Row(
Column('phone_number'),
Column('whatsapp_number'),
Column('email_address'), css_class='g-2'
),
Row('license_agreement'),
Row(Submit('submit', 'Create Account'))
)
def check_username(self):
data = self.cleaned_data['username']
if User.objects.filter(username__iexact=data).exists():
raise ValidationError('Username exists')
return data
def compare_passwords(self):
password1 = self.cleaned_data['password']
password2 = self.cleaned_data['password_confirm']
if password2 != password1:
raise ValidationError('Password does not match')
return password1
views.py
def reg_form(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
username = form.check_username()
password = form.compare_passwords()
email = form.cleaned_data['email_address']
user = User.objects.create_user(
username=username, email=email, password=password)
user.first_name = first_name
user.last_name = last_name
user.save()
user_info = UserInfo()
user_info.user = user
user_info.linked_user = user.username
user_info.phone_number = form.cleaned_data['phone_number']
user_info.whatsapp_number = form.cleaned_data['whatsapp_number']
user_info.country = form.cleaned_data['country']
user_info.referral_id = form.cleaned_data['referral_id']
user_info.save()
login(request, user)
return redirect(reverse('dashboard'), permanent=True)
else:
form = RegistrationForm()
return render(request, 'office/reg_form_hx.html', {'form': form})
template
{% extends './base.html' %}
{% block main %}
{% load crispy_forms_tags %}
{% crispy form %}
{% endblock main %}
I figured this out.
I was supposed to implement the form clean() method or the clean_fieldname() method for a specific field.
It should have been clean_username() and not check_username() in the forms.py file.
Thank you.
I created a sign up form using two grouped forms and it has been working perfectly, but I would like to use django-allauth because of the features (login only with e-mail, sending confirmation e-mail ...).
However even reading some topics I still couldn't.
forms.py
class ExtendedUserCreationForm(UserCreationForm):
email = forms.EmailField(required=True, label="E-mail")
first_name = forms.CharField(max_length=30, label="Nome")
last_name = forms.CharField(max_length=30, label="Sobrenome")
class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'email', 'password1', 'password2')
def save(self, commit=True):
user = super().save(commit=False)
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
if commit:
user.save()
return user
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('sexo', 'data_nascimento', 'foto', 'sobre_mim', 'telefone', 'paroquia',
'cidade','estado', 'cep', 'possui_filhos', 'facebook', 'instagram')
CIDADES = []
for i in cidadesReader:
if i[1] not in CIDADES:
CIDADES.append(i[1])
widgets = {
'cidade': floppyforms.widgets.Input(datalist=CIDADES, attrs={'autocomplete': 'off'}),
}
views.py
def signup(request):
if request.method == 'POST':
form = ExtendedUserCreationForm(request.POST)
profile_form = UserProfileForm(request.POST, request.FILES)
if form.is_valid() and profile_form.is_valid():
user = form.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=password)
#login(request, user)
return redirect('home')
else:
form = ExtendedUserCreationForm()
profile_form = UserProfileForm()
context = {'form': form, 'profile_form' : profile_form}
return render(request, 'registration/signup.html', context)
signup.html
{% extends '_base.html' %}
{% load crispy_forms_tags %}
{% block title %}Cadastrar{% endblock title %}
{% block content %}
<h2>Criar Perfil</h2>
<form novalidate method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
{{ profile_form|crispy }}
<button class="btn btn-success" type="submit">Cadastrar</button>
</form>
{% endblock content %}
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
SEXOS = (
('M', 'Masculino'),
('F', 'Feminino'),
)
sexo = models.CharField(max_length=1, choices=SEXOS)
data_nascimento = models.DateField(validators=[idade_minima])
...
I've tried using the ACCOUNT_SIGNUP_FORM_CLASS and ACCOUNT_FORMS options in settings.py, but it didn't work.
I tried to make some adjustments, as in this topic similar to my question:
Django allauth saving custom user profile fields with signup form
For example, I changed it in models.py and I did migrate:
user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True, related_name ='profile')
After several attempts, the most common error is:
RelatedObjectDoesNotExist at /accounts/signup/
User has no profile.
Edit:
I changed my slug in UserProfile, because it depends from user (first name). The error changed:
IntegrityError at /accounts/signup/
NOT NULL constraint failed: profiles_userprofile.user_id
But UserProfile has no user continues in the final.
(Using in settings.py: ACCOUNT_SIGNUP_FORM_CLASS = 'profiles.forms.UserProfileForm'. Details from traceback:
...lib/python3.6/site-packages/allauth/account/views.py in dispatch
215 return super(SignupView, self).dispatch(request, *args, **kwargs)
.../lib/python3.6/site-packages/allauth/account/views.py in post
104 response = self.form_valid(form)
...lib/python3.6/site-packages/allauth/account/views.py in form_valid
231 self.user = form.save(self.request)
...lib/python3.6/site-packages/allauth/account/forms.py in save
405 self.custom_signup(request, user)
...lib/python3.6/site-packages/allauth/account/forms.py in custom_signup
359 custom_form.save(user)
...profiles/models.py in save
super(UserProfile, self).save(*args, **kwargs)
▼ Local vars
Variable Value
__class__
<class 'profiles.models.UserProfile'>
args ()
kwargs {}
self Error in formatting: RelatedObjectDoesNotExist: UserProfile has no user.
slug_name 'nome-sp-260221205510'
Signals
Using signals the error changed. I added it in models.py:
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
Error:
ValueError at /accounts/signup/
The 'foto' attribute has no file associated with it.
Then I tried remove foto field, but the other error happens in another field:
IntegrityError at /accounts/signup/
NOT NULL constraint failed: profiles_userprofile.data_nascimento
Thanks in advance for any help.
The error UserProfile has no user is triggered in UserProfile.save(). You are calling this the first time in your view with commit=False and only afterwards are you setting the user:
# your code from the question
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
I'm guessing that UserProfile.save reads the the user field to create the slug. You could either skip it if commit=False, or maybe it will already work if you change it like this:
profile_form.instance.user = user
profile.save()
Another common solution is, to provide the user when initializing the form, but then you would have to change your current view code quit a bit.
I achieved! No need to use signals. Here are the changes:
forms.py
I needed to use a single class:
class SignupForm(forms.ModelForm):
first_name = forms.CharField(max_length=30, label="Nome")
last_name = forms.CharField(max_length=30, label="Sobrenome")
class Meta:
model = UserProfile
fields = ('sexo', 'data_nascimento', 'foto', 'sobre_mim','telefone','paroquia',
'cidade','estado', 'cep', 'possui_filhos', 'facebook', 'instagram')
CIDADES = []
for i in cidadesReader:
if i[1] not in CIDADES:
CIDADES.append(i[1])
widgets = {
'cidade': floppyforms.widgets.Input(datalist=CIDADES, attrs={'autocomplete': 'off'}),
}
field_order = ['first_name', 'last_name', 'email', 'password1', 'password2',
'sexo', 'data_nascimento', 'foto', 'sobre_mim','telefone','paroquia',
'cidade','estado', 'cep', 'possui_filhos', 'facebook', 'instagram']
def signup(self, request, user):
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
profile, created = models.UserProfile.objects.get_or_create(user=user)
profile.sexo = self.cleaned_data['sexo']
profile.data_nascimento = self.cleaned_data['data_nascimento']
def compressImage(foto):
...
return foto
profile.foto = compressImage (self.cleaned_data['foto'])
profile.sobre_mim = self.cleaned_data['sobre_mim']
profile.telefone = self.cleaned_data['telefone']
profile.paroquia = self.cleaned_data['paroquia']
profile.cidade = self.cleaned_data['cidade']
profile.estado = self.cleaned_data['estado']
profile.cep = self.cleaned_data['cep']
profile.possui_filhos = self.cleaned_data['possui_filhos']
profile.facebook = self.cleaned_data['facebook']
profile.instagram = self.cleaned_data['instagram']
user.save()
profile.save()
Note:
I was using a function to compress images, in models.py.
To correct the error
ValueError at /accounts/signup/
The 'foto' attribute has no file associated with it
I had to bring it to forms.py
settings.py
ACCOUNT_SIGNUP_FORM_CLASS = 'profiles.forms.SignupForm'
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True, related_name ='profile')
SEXOS = (
('M', 'Masculino'),
('F', 'Feminino'),
)
sexo = models.CharField(max_length=1, choices=SEXOS)
...
Note:
It was necessary to test field by field.
Sometimes there were some errors like NOT NULL constraint failed ou no such table.
The solutions to these problems:
Add null=True in the field (temporarily)
makemigrations and migrate
Delete migrations
signup.html
Only {{ form|crispy }} is necessary (I could delete {{ profile_form|crispy }})
<form novalidate method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-success" type="submit">Cadastrar</button>
</form>
Thank you for your help, #Risadinha.
I have been trying make users follow other users from thier posts like in instagrams explore page. Currently a user can just follow and unfollow other users from their profile but I will like to have that follow/unfollow on their posts too. I tried to make this happen but in the process I got a NameError name 'username' is not defined, How can I fix this error in order to make this work?
models.py (mates model is where the follow/unfollow should go)
class Mates(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='usermates', unique=True)
req_bio = models.CharField(max_length=400)
class Following(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
followed = models.ManyToManyField(User, related_name="followed")
follower = models.ManyToManyField(User, related_name="follower")
#classmethod
def follow(cls, user, another_account):
obj, create = cls.objects.get_or_create(user = user)
obj.followed.add(another_account)
print("followed")
#classmethod
def unfollow(cls, user, another_account):
obj, create = cls.objects.get_or_create(user = user)
obj.followed.remove(another_account)
print("unfollowed")
def __str__(self):
return f'{self.user.username} Profile'
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank=True, default='default.png')
bio = models.CharField(max_length=400, default=1, null=True)
connection = models.CharField(max_length = 100, blank=True)
follower = models.IntegerField(default=0)
following = models.IntegerField(default=0)
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.profile_pic.path)
if img.height > 300 or img.width > 300:
output_size = (300,300)
img.thumbnail(output_size)
img.save(self.profile_pic.path)
def __str__(self):
return f'{self.user.username} Profile'
views.py
def matesmain(request):
if request.user.has_posts():
contents = Mates.objects.filter(
categories__in=['action', 'sports', 'shooter', 'battle_royale', 'adventure', 'racing']
)
mates_owner = get_object_or_404(User, username=username)
context = {
'contents': contents,
'mates_owner': mates_owner,
}
print("nice3")
return render(request, 'mates.html', context)
else:
return render(request, 'mates-error.html')
def follow(request, username):
main_user = request.user
to_follow = User.objects.get(username=username)
following = Following.objects.filter(user = main_user, followed = to_follow)
is_following = True if following else False
if is_following:
Following.unfollow(main_user, to_follow)
is_following = False
else:
Following.follow(main_user, to_follow)
is_following = True
resp = {
'following': is_following,
}
response = json.dumps(resp)
return HttpResponse(response, content_type="application/json")
html
{% if connection and not request.user == mates_owner %}
<a type="button" class="button-caballo" id="follow" role="button" href="{% url 'follow' mates_owner.username %}">Unfollow</a>
{% elif not connection and not request.user == mates_owner %}
<a type="button" class="button-caballo" id="follow" role="button" href="{% url 'follow' mates_owner.username %}">Follow</a>
{% endif %}
urls.py
urlpatterns = [
path('follow/<str:username>', views.follow, name='follow')
path('mates-main', views.matesmain, name='mates-main'),
]
traceback
Traceback (most recent call last):
File "C:\Users\USER\Envs\startup\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\USER\Envs\startup\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\USER\Envs\startup\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\USER\startup\gstartup\startup_home\views.py", line 126, in matesmain
mates_owner = get_object_or_404(User, username=username)
NameError: name 'username' is not defined
[16/Jul/2020 08:53:25] "GET /mates-main HTTP/1.1" 500 70246
I'm trying to make register possible on the homepage (register box appears onclick), so I don't have a seperate URL to handle registration. I'm trying to send the form through get_context_data, however it's not working. Here's my code:
forms.py
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
confirm_password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = [
'username',
'password',
'confirm_password',
]
views.py
class BoxesView(ListView):
template_name = 'polls.html'
def get_context_data(self):
context = super(BoxesView, self).get_context_data()
# login
form = UserRegistrationForm(self.request.POST or None)
context['form'] = form
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = User.objects.create_user(username, password)
user.save()
return redirect('/')
return context
return context
def get_queryset(self):
pass
base.html
<form action="" enctype="multipart/form-data" method="post">{% csrf_token %}
<div class="registerBox">
{{ form.username }}
{{ form.password }}
<input type="submit" value="register"/>
</div>
</form>
The fields show up but after submitting the form it doesn't create a User because my form.is_valid is False. Any idea?
You shouldn't return a response from get_context_data(). Instead, do that in the post() method like this:
class BoxesView(ListView):
template_name = 'polls.html'
def post(self, request, *args, **kwargs):
form = UserRegistrationForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = User.objects.create_user(username, password=password)
return redirect('/')
else:
return self.get(request, *args, **kwargs)
def get_context_data(self):
context = super(BoxesView, self).get_context_data()
context['form'] = UserRegistrationForm()
return context
Looks like your Form expects to have confirm_password submitted, but that's not part of your html form.
I've been trying everything, but I can't figure out why it's not showing-up. I searched everywhere on this site with no luck. The button shows up but when I click than it give me a TypeError at get_profile, saying:
Exception Value:
get_profile() got an unexpected keyword argument 'username'
Here's my code:
models.py
class CustomUser(AbstractBaseUser):
email = models.EmailField('email address', unique=True, db_index=True)
username = models.CharField('username', max_length=50, unique=True, db_index=True)
first_name = models.CharField(max_length=50, blank=False)
last_name = models.CharField(max_length=50, blank=False)
joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __unicode__(self):
return self.username
forms.py
from django import forms
from apps.accounts.models import CustomUser
class RegistrationForm(forms.ModelForm):
email = forms.EmailField(widget=forms.TextInput, label='email')
username = forms.CharField(widget=forms.TextInput, label='username')
password1 = forms.CharField(widget=forms.PasswordInput, label='Enter your password')
password2 = forms.CharField(widget=forms.PasswordInput, label='Re-type your password')
first_name = forms.CharField(widget=forms.TextInput, label='First Name')
last_name = forms.CharField(widget=forms.TextInput, label='Last Name')
class Meta:
model = CustomUser
fields = ['email', 'username', 'password1', 'password2', 'first_name', 'last_name']
def clean(self, password1, password2):
cleaned_data = super(RegistrationForm, self).clean()
if password1 in self.cleaned_data and password2 in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError("Passwords don't match. Please enter both fields again")
return self.cleaned_data
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
views.py
def register(request):
"""
User Registration View
"""
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
CustomUser = form.save()
CustomUser.save()
return redirect('home.html')
else:
form = RegistrationForm()
return render_to_response('register.html', {
'form': form,
}, context_instance=RequestContext(request))
def get_profile(request):
username = CustomUser.username
return render_to_response(request, 'profile.html', {'username': username})
urls.py
urlpatterns = patterns ('',
url(r'register$', 'apps.accounts.views.register', name='register'),)
register.html
{% load staticfiles %}
{% load crispy_forms_tags %}
<!DOCTYPE html>
<html lang="en">
<body>
{% block body %}
<form method='POST' action="register" enctype= 'multipart/form-data'>{% csrf_token %}
<table>{{ form.ast_table}}</table>
<input type='submit' class="btn btn-default" value="Register" />
</form>
{% endblock %}
</body>
</html>
It seems that you don't have the right signature for the get_profile view function.
You should check your urls, you probably have something like
url(r'^profile/(?P<username>\w+/$', get_profile),
If so, your view should be
def get_profile(request, username):
#you can get the user
user = CustomUser.objects.get(username=username)
return render_to_response(request, 'profile.html', {'username': username, 'user': user})
CustomUser is the class. You need to fetch an instance before you can actually fetch its username.
Eg:
CustomUser.objects.get(pk=1).username
Gives you the username of the first user.
Also, its supposed to be {{form.as_table}} not ast_table