Django User does not update when saved? - django

I cannot get the default User model or my created Agent model to update. Below is my admin.py, forms.py, models.py, urls.py, views.py, and my edit_profile.html. I know it must be silly, but I've got three good days working on this.
The HTML page tries to edit both the EditProfileForm and the MoreInfoForm. The EditProfileForm uses the built-in User model, while the MoreInfoForm is my model that extends the built-in User model. As a note, the MoreInfoForm also contains an Image that I want to be able to update.
When I submit the form, I get a POST request, but when I view the profile, it doesn't contain any changes.
admin.py:
class AgentInline(admin.StackedInline):
model = Agent
can_delete = False
verbose_name_plural = 'agent'
class UserAdmin(BaseUserAdmin):
inlines = (AgentInline,)
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
forms.py:
class RegisterUserForm(UserCreationForm):
email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'}))
first_name = forms.CharField(max_length=50,
widget=forms.TextInput(attrs={'class': 'form-control'}))
last_name = forms.CharField(max_length=50,
widget=forms.TextInput(attrs={'class': 'form-control'}))
class Meta:
model = User
fields = ('username',
'first_name',
'last_name',
'email',
'password1',
'password2',)
def __init__(self, *args, **kwargs):
super(RegisterUserForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['password1'].widget.attrs['class'] = 'form-control'
self.fields['password2'].widget.attrs['class'] = 'form-control'
class MoreInfoForm(forms.ModelForm):
agent_phone_num = forms.CharField(max_length=10,
required=True,
help_text='Enter a 10 digit # without spaces or dashes',
widget=forms.TextInput(
attrs={'class': 'form-control'}))
agent_mls = forms.CharField(max_length=6,
required=True,
help_text='Enter your 6 digit MLS #',
widget=forms.TextInput(
attrs={'class': 'form-control'}))
headshot = forms.ImageField(required=False,
error_messages={'invalid': 'Image files only'},
widget=forms.FileInput(attrs={'class': 'form-control'}))
class Meta:
model = Agent
fields = ('agent_phone_num',
'agent_mls',
'headshot',)
class EditProfileForm(UserChangeForm):
email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'}))
first_name = forms.CharField(max_length=50,
widget=forms.TextInput(attrs={'class': 'form-control'}))
last_name = forms.CharField(max_length=50,
widget=forms.TextInput(attrs={'class': 'form-control'}))
class Meta:
model = User
fields = ('first_name',
'last_name',
'email',
'password',)
def __init__(self, *args, **kwargs):
super(EditProfileForm, self).__init__(*args, **kwargs)
del self.fields['password']
models.py:
class Agent(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
agent_phone_num = models.CharField(blank=False, max_length=10, default=None)
agent_mls = models.CharField(blank=False, max_length=6, default=None)
headshot = models.ImageField(upload_to='agents', blank=True)
def formatted_phone(self):
phone_string = f'{self.agent_phone_num}'
return ('1-' +
phone_string[:3] + '-' +
phone_string[3:6] + '-' +
phone_string[6:])
def __str__(self):
return self.user.username + self.formatted_phone()
urls.py:
urlpatterns = [
path('login', views.login_user, name='login', ),
path('logout', views.logout_user, name='logout', ),
path('register', views.register_user, name='register', ),
path('profile', views.view_profile, name='profile', ),
path('profile/edit/', views.edit_profile, name='edit_profile', ),
# TODO user password reset page
path('reset_password/',
auth_views.PasswordResetView.as_view(),
name='reset_password'),
path('reset_password_sent',
auth_views.PasswordResetDoneView.as_view(),
name='password_reset_done'),
path('reset/<uidb64>/<token>/',
auth_views.PasswordResetConfirmView.as_view(),
name='password_reset_confirm'),
path('reset_password_complete/',
auth_views.PasswordResetCompleteView.as_view(),
name='password_reset_complete'),
]
views.py:
def login_user(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('index')
else:
messages.success(request, 'There Was An Error Logging In, Try Again...')
return redirect('login')
else:
return render(request, 'authenticate/login.html', {
})
def logout_user(request):
logout(request)
messages.success(request, 'You Were Logged Out!')
return redirect('index')
def register_user(request):
if request.method == 'POST':
form = RegisterUserForm(request.POST)
more_form = MoreInfoForm(request.POST, request.FILES)
if form.is_valid() and more_form.is_valid():
user = form.save()
more = more_form.save(commit=False)
more.user = user
more.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
messages.success(request, 'Registration Successful!')
return redirect('index')
else:
form = RegisterUserForm()
more_form = MoreInfoForm(request.POST)
return render(request, 'authenticate/register_user.html', {
'form': form,
'more_form': more_form,
})
def view_profile(request):
return render(request, 'authenticate/profile.html', {
'user': request.user,
})
def edit_profile(request):
user_profile = get_object_or_404(Agent, user=request.user)
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
more_form = MoreInfoForm(request.POST, request.FILES, instance=user_profile)
if form.is_valid() and more_form.is_valid():
form.save()
more_form.save()
messages.success(request, 'Your profile has been updated.')
return redirect('edit_profile')
else:
form = EditProfileForm(instance=request.user)
more_form = MoreInfoForm(instance=user_profile)
return render(request, 'authenticate/edit_profile.html', {
'form': form,
'more_form': more_form,
'user_profile': user_profile,
})
edit_profile.html:
<div class="container"
style="min-height: 100vh">
{% if user.is_authenticated %}
<h1 class="h1 text-center mt-3 text-capitalize">{{ user.first_name }}'s Profile</h1>
<div class="">
<img src="{{ user.agent.headshot.url }}"
alt="Profile Picture"
class=""
height="300"
width="">
</div>
<form action="{% url 'edit_profile' %}"
method="POST"
enctype="multipart/form-data">
{% csrf_token %}
{{ form.first_name }}
{{ form.last_name }}
{{ form.email }}
{{ more_form.agent_phone_num }}
<div class="form-group col-md-6">
<label for="">Profile Picture</label>
{{ more_form.headshot }}
</div>
<input type="submit"
class="btn btn-secondary"
value="Save">
{#<button class="btn btn-secondary"#}
{# type="submit">Save#}
{#</button>#}
</form>
{% else %}
<h1 class="h1 text-center mt-3">You must be logged in to view this page</h1>
<div class="text-center m-3">
<a href="{% url 'login' %}"
class="text-decoration-none">
<button type="button"
class="btn btn-light pl-5 pr-5">Login
</button>
</a>
</div>
{% endif %}
</div>

Related

Django Show var as Label name

models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
telefoon = models.CharField(max_length=10, blank=True)
telefoon_mobiel = models.CharField(max_length=10, blank=True)
woonplaats = models.CharField(max_length=20, blank=True)
postcode = models.CharField(max_length=6, blank=True)
straat = models.CharField(max_length=20, blank=True)
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
form.py
class ProfileForm(forms.ModelForm):
straat = forms.CharField(required=False,
widget=forms.TextInput(attrs={'class': 'form-control'}))
postcode = forms.CharField(required=False,
widget=forms.TextInput(attrs={'class': 'form-control'}))
woonplaats = forms.CharField(required=False,
widget=forms.TextInput(attrs={'class': 'form-control'}))
telefoon = forms.CharField(required=False,
widget=forms.TextInput(attrs={'class': 'form-control'}))
telefoon_mobiel = forms.CharField(required=False,
widget=forms.TextInput(attrs={'class': 'form-control'}))
class Meta:
model = Profile
fields = ('telefoon', 'telefoon_mobiel', 'woonplaats', 'postcode', 'straat')
views.py
#login_required
#transaction.atomic
def profiel(request):
if request.method == 'POST':
user_form = UserForm(request.POST, instance=request.user)
profile_form = ProfileForm(request.POST, instance=request.user.profile)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, ('Profiel aangepast'))
return redirect('user')
else:
messages.error(request, ('Los ondestaande probleem op'))
else:
user_form = UserForm(instance=request.user)
profile_form = ProfileForm(instance=request.user.profile)
return render(request, 'public/profiel.html', {
'user_form': user_form,
'profile_form': profile_form,
})
template:
<div class="card-body">
<h5 class="card-title">Profiel {{ user.get_full_name }}</h5>
<hr>
<div class="container">
<div class="row">
<div class="col-sm">
{{ user.first_name }} {{ user.last_name }}
</div>
<div class="col-sm">
{{ straat }}
</div>
</div>
<br/>
<div class="row">
<div class="col-sm">
<label>Achternaam:</label>
</div>
<div class="col-sm">
{{ user_form.last_name }}
</div>
</div>
When I call for example the field straat I am getting an editable field and I just want to show the value of it as text.

How to override username validation in Django

I have a simple profile form that displays the users profile and allows them to make updates to Full Name, Initials, Username and Bio. In my Profile model, I have Username set to unique with field validation. It is more of a screen-name reference field, as email is used for login, however it still needs to be unique and the user can change this name if needed.
The issue is that validation does not pass form.is_valid(), even when user does not change their username, but updates other fields, due to the fact that the username does already exist for the request user. How can I get around this issue.
Sample of what i am trying to do:
If username == form['username'].value() (meaning username is unchanged)
allow form.save()
else if form.is_valid(): (perform normal validation checks)
form.save()
Thanks for any suggestions.
Profile Model
class Profile(models.Model):
# OneToOneField ensures that only one user can have one profile
my_user = models.OneToOneField(MyUser, on_delete=models.CASCADE)
# Extension of additional user information
full_name = models.CharField(max_length=255, blank=False, null=True)
initials = models.CharField(max_length=3, blank=False, null=True)
username_validator = UnicodeUsernameValidator()
username = models.CharField(verbose_name='username', max_length=30, unique=True, blank=False, null=True,
help_text='Required. 30 characters or fewer. Letters, digits and #/./+/-/_ only.',
validators=[username_validator],
error_messages={
'unique': "Username already exists.",
},
)
bio = models.TextField(null=True, blank=True)
avatar = models.ImageField(null=True, blank=True)
Form
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('full_name', 'initials', 'username', 'bio')
widgets = {
'full_name': forms.TextInput(attrs={'class': 'form-control mb-3', 'id':'full_name', 'placeholder': 'Full Name'}),
'initials': forms.TextInput(attrs={'class': 'form-control mb-3', 'id':'initials', 'maxlength': '3', 'placeholder': 'Initials'}),
'username': forms.TextInput(attrs={'class': 'form-control mb-3', 'id':'username', 'placeholder': 'Username'}),
'bio': forms.Textarea(attrs={'rows':5, 'cols':8}),
}
Views post function
def post(self, request, *args, **kwargs):
form = ProfileForm(request.POST or None)
email = self.request.user
my_user = Profile.objects.get(my_user=email)
if my_user.username == form['username'].value():
#need to override username validation on field for current user
pass
else:
if form.is_valid():
# Update Profile Information
my_user.full_name = form.cleaned_data['full_name']
my_user.initials = form.cleaned_data['initials']
my_user.username = form.cleaned_data['username']
my_user.bio = form.cleaned_data['bio']
my_user.save()
# Send Success Message To User
messages.success(request, 'Profile has been updated.')
# Update Session Variables
request.session['full_name'] = my_user.full_name
request.session['initials'] = my_user.initials
request.session['username'] = my_user.username
context = {'form': form}
return render(request, 'profile.html', context)
Template
{% extends 'account/base.html' %}
{% load crispy_forms_tags %}
{% block head_title %}Manage Profile{% endblock %}
{% block base_content %}
<h6 class="text-center">Manage Account Profile</h6>
<hr>
<div class="py-3">
<form id="profile_form" method="POST" action="{% url 'account_profile' %}" class="col-sm-8 mx-auto small">
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-primary btn-block" type="submit">Update Profile</button>
</form>
</div>
{% endblock %}
Since you are using model form any way you can pass a profile instance to your form if you want to update that Profile. Try this.
def post(self, request, *args, **kwargs):
obj = Profile.objects.get(my_user = request.user)
form = ProfileForm(request.POST, instance = obj)
if form.is_valid():
form.save()
messages.success(request, 'Profile has been updated.')
context = {'form': form}
return render(request, 'profile.html', context)

Profile model Data is not saving when I try to create user and Profile simultaneously

When I try to create a new user, I also want to create their profile at the same time. But there is no data coming from the Profile form. User is created but in Profile creation form I am getting an error.
Here is my models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
StudentID = models.IntegerField(primary_key=True, verbose_name='SID')
image = models.ImageField(default='default.jpeg', upload_to='profile_pics', blank=True)
def __str__(self):
return self.Branch
def save(self, *args, **kwargs):
super(Profile, self).save(*args, **kwargs)
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)
forms.py
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
first_name = forms.CharField()
last_name = forms.CharField()
class Meta:
model = User
fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2']
class ProfileCreationForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['StudentID', 'Branch', 'YearOfStudy', 'ContactNumber']
views.py
when I try to print StudentID, I get None value. I think there is data loss.
def register(request):
print("hello")
if request.method == 'POST':
form = UserRegisterForm(request.POST)
form1 = ProfileCreationForm(request.POST)
if form.is_valid() and form1.is_valid():
user = form.cleaned_data.get('username')
StudentID = form.cleaned_data.get('StudentID')
print(StudentID)
profile = form1.save(commit=False)
profile.user = user
form.save()
profile.save()
messages.success(request, f'Your account has been created! You are now able to log in')
print("reached here")
return redirect('login')
else:
form = UserRegisterForm()
form1 = ProfileCreationForm()
context = {
'form': form,
'form1': form1
}
return render(request, 'user/register.html', context)
register.html
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">JOIN TODAY</legend>
{{ form|crispy }}
{{ form1|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">Already have an account?<a class="ml-2" href="{% url 'login' %}">Sign In</a></small>
</div>
</div>
{% endblock content %}
StudentID is on form1 not form
StudentID = form1.cleaned_data.get('StudentID')
print(StudentID)
You should also save the User first since it's a required relation for the Profile model
user = form.save()
profile = form1.save(commit=False)
profile.user = user
profile.save()
Apart from what #Iain has pointed out, I think your code in the views has some problem after you run is_valid. Try to fix it like this:
if form.is_valid() and form1.is_valid():
profile = form1.save(commit=False)
user = form.save()
profile.user = user
profile.save()
messages.success(request, 'Your account has been created! You are now able to log in')
return redirect('login')
Let me explain why you might get error, that is profile.user is a User instance, not a string. So putting username will not work. But you can get the user object when you save the form. Like user=form.save(), so use that in profile.user.

Data not filling in with Edit Profile form Django

I'm using the following line to fill in data into the form.
form = EditProfileForm(request.POST, instance=request.user)
However, no data fills into the form. I just get the empty form. Not sure what's going wrong. I have a profile html where the data from each user shows up, but the line above is not working on the edit page. The model is the default user model. Django version 2.2.3.
#views.py
def editprofile(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
if form.is_valid():
agree = form.save(commit=False)
agree.save()
args = {'form': form}
else:
form = EditProfileForm(request.POST)
args = {'form': form}
return render(request, 'profile_edit.html', {'form':form})
Here is my forms.py:
class EditProfileForm(UserChangeForm):
username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'class': "form-control"}))
first_name = forms.CharField(label='First Name', widget=forms.TextInput(attrs={'class': "form-control"}))
last_name = forms.CharField(label='Last Name', widget=forms.TextInput(attrs={'class': "form-control"}))
email = forms.CharField(label= 'Email', widget=forms.EmailInput(attrs={'class': "form-control"}))
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'password']
def save(self, commit=True):
user = super(EditProfileForm, self).save(commit=False)
user.username = self.cleaned_data['username']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
template
{% block content %}
<h3> Please edit your profile here </h3>
<div class="container">
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button href="{% url 'profilepage' %}" type="submit" >Submit</button>
</form>
<br>
</div>
{% endblock %}
Added urls.py
path('profile/', views.profile, name = 'profilepage'),
path('profile/edit/', views.editprofile, name = 'editprofile')
Try adding action to your form tag in template.
Like this:
<form action= "{% url 'editprofile' %}" method="post">
'editprofile' is the url_name of your editprofile view. Also the class Meta and method def save() should be inside your class EditProfileForm() block.

update user profile issue with post_save signal. errors a message are user already exists on update

I have extending user profile with profile model and create an post_save signal.
I works well on user creation but seems that there is an issue on update. When I want to update I have messages saying user and email already exists in data table. So nothing is updated. and and send back to Register page but should go to edit_profile page
My model.py:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from authenticate.thumbs import ImageWithThumbsField # transforme les images en thumbs
import os
def image_name(instance, filename):
extension = filename.split('.')
extension = extension[-1]
return 'avatars/{}.{}'.format(instance.user.pk, extension)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = ImageWithThumbsField(upload_to=image_name, blank=True) # transforme les images en thumbs
bio = models.CharField(max_length=100, blank=True)
location = models.CharField(max_length=30, blank=True, default='Please fill in info')
birth_date = models.DateField(null=True, blank=True)
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
My forms.py:
class UniqueUserEmailField(forms.EmailField):
"""
An EmailField which only is valid if no User has that email.
"""
def validate(self, value):
super(forms.EmailField, self).validate(value)
try:
User.objects.get(email = value)
raise forms.ValidationError("Email already exists")
except User.MultipleObjectsReturned:
raise forms.ValidationError("Email already exists")
except User.DoesNotExist:
pass
class SignUpform(UserCreationForm):
"""
Extends the built in UserCreationForm in several ways:
* Adds an email field, which uses the custom UniqueUserEmailField,
that is, the form does not validate if the email address already exists
in the User table.
* The username field is generated based on the email, and isn't visible.
* first_name and last_name fields are added.
* Data not saved by the default behavior of UserCreationForm is saved.
* add forms control from Bootstrap to improve form UX
"""
email = forms.EmailField(required= True, label='', max_length=100, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Email address' }))
first_name = forms.CharField(label='',max_length=100, widget=forms.TextInput(attrs={'placeholder': 'First Name', 'class': 'form-control'}))
last_name = forms.CharField(label='',max_length=100,widget=forms.TextInput(attrs={'placeholder': 'Last Name', 'class': 'form-control'}))
class Meta:
model = User
fields = ('email', 'username', 'first_name', 'last_name', 'password1', 'password2',)
def __init__(self, *args, **kwargs):
super(SignUpform, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['password1'].widget.attrs['class'] = 'form-control'
self.fields['password2'].widget.attrs['class'] = 'form-control'
# change labels
self.fields['username'].label = ''
self.fields['username'].help_text = '<span class="form-text text-muted"><small>Required.</small></span>'
self.fields['email'].help_text = '<span class="form-text text-muted"><small>Required.</small></span>'
self.fields['password1'].label = ''
self.fields['password1'].help_text = '<ul class="form-text text-muted small">' \
'<li>Your password cannot be too similar to your other personal information.</li>' \
'<li>Your password must contain at least 8 characters.</li>' \
'<li>Your password cannot be a commonly used password.</li>' \
'<li>Your password cannot be entirely numeric.</li>' \
'</ul>'
self.fields['password2'].label = ''
self.fields['password2'].help_text = '<span class="form-text text-muted"><small>Enter the same password as before, for verification.</small></span>'
self.fields['username'].widget.attrs['placeholder'] = 'User Name'
self.fields['password1'].widget.attrs['placeholder'] = 'password'
self.fields['password2'].widget.attrs['placeholder'] = 'confirm password'
def clean_email(self):
# Get the email
email = self.cleaned_data.get('email')
# Check to see if any users already exist with this email as a username.
try:
match = User.objects.get(email=email)
print("ok")
except User.DoesNotExist:
# Unable to find a user, this is fine
return email
# A user was found with this as a username, raise an error.
raise forms.ValidationError('This email address is already in use.')
class EditUseform(UserChangeForm):
class Meta:
model = User
fields = ('email', 'username', 'first_name', 'last_name', 'password',)
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('avatar', 'bio', 'location', 'birth_date')
widgets = {
'birth_date': DatePickerInput(), # default date-format %m/%d/%Y will be used
}
My views.py:
def register_user(request):
if request.method == 'POST':
form = SignUpform(request.POST)
profile_form = ProfileForm(request.POST, request.FILES)
if form.is_valid() and profile_form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(request, username=username, password=password)
# modify existing profile
profile = Profile.objects.get(user=user.pk)
profile.avatar = profile_form.cleaned_data['avatar']
profile.bio = profile_form.cleaned_data['bio']
profile.location = profile_form.cleaned_data['location']
profile.birth_date = profile_form.cleaned_data['birth_date']
profile.save()
login(request, user)
messages.success(request, 'You are registered')
# redirect to a succes page
return redirect('home')
else:
form = SignUpform()
profile_form = ProfileForm()
context = {'form': form,
'profile_from': profile_form, }
return render(request, 'register.html', context)
def edit_profile(request):
if request.method == 'POST':
form = EditUseform(request.POST, instance=request.user)
profile_form = ProfileForm(request.POST, instance=request.user.profile)
if form.is_valid() and profile_form.is_valid():
form.save()
# modify existing profile
profile_form.save()
messages.success(request, _('Your profile was successfully updated!'))
# redirect to a succes page
return redirect('edit_Profile')
else:
form = EditUseform(instance=request.user)
profile_form = ProfileForm(instance=request.user.profile)
context = {'form': form,
'profile_from': profile_form, }
return render(request, 'edit_Profile.html', context)
My Edit_Profille.html:
{% extends 'base.html' %}
<!---- datepicker ---->
{% block extrahead %}
{{ profile_from.media }}
{% endblock %}
<!-------->
{% block content %}
<h2 class="text-center">Edit user</h2>
<div class="col-md-6 offset-md-3">
<form method="POST" action="{% url 'register' %}" enctype="multipart/form-data">
{% csrf_token %}
{% if form.errors %}
<div class="alert alert-warning alert-dismissable" role="alert">
<button class="close" data-dismiss="alert">
<small><sup>x</sup></small>
</button>
<p>Your form has errors:</p>
{% for field in form %}
{% if field.errors %}
{{ field.errors }}
{% endif %}
{% endfor %}
</div>
{% endif %}
{{ form.as_p }}
{{ profile_from.as_p }}
<input type="submit" value="register" class="btn btn-primary">
</form>
{% endblock %}