When i am hitting the URL, only html button is getting rendered,form.as_p is now getting rendered. Please be helping me out. Thanks
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('signup/',views.SignUp, name = 'signup_view'),
]
my code :
forms.py
from django import forms
from .models import Profile
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['user','bio','location','birth_date']
class SignUpForm(UserCreationForm):
first_name = forms.CharField(max_length=200,required=True,help_text='Hello')
last_name = forms.CharField(max_length=200,required=True)
email = forms.EmailField(max_length=500,help_text='Enter a valid email address')
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2',]
views.py
from django.shortcuts import render,redirect
from django.contrib.auth import login,authenticate
from .forms import SignUpForm
def SignUp(request):
form = SignUpForm()
if request.method == 'POST':
print(request.method)
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
raw_username = form.cleaned_data.get['username']
raw_password = form.cleaned_data.get['password1']
user = authenticate(username = raw_username,password = raw_password)
login(request,user)
return redirect('home')
else:
return render(request,'registration/signup.html',{'form':form})
templates/registration/signup.html
<form method="post">
{% csrf_token %}
{{ from.as_p }}
<button value="submit" type="submit">SignUp</button>
</form>
Related
Iam coding in django and trying to figure how to update profile of a user in my app
Please help me Iam trying to learn how to code and this is a big barrier for me to learn
here's models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete= models.CASCADE)
image = models.ImageField(default='default.jpg',upload_to="profile_pics")
def __str__(self):
return f'{self.user.username} Profile'
here's my views.py:
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get("username")
messages.success(request, f'Yor account has been created! You are now able to login')
return redirect('/login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html',{'form': form})
#login_required
def profile(request):
u_form = UserUpdateForm(instance = request.user)
p_form = ProfileUpdateForm(instance= request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'users/profile.html', context)
Iam getting error at 'u_form':u_form,
and This is my forms.py:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email','password1','password2']
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username','email']
class ProfileUpdateForm(forms.ModelForm):
model = Profile
field = ['image']
Iam getting my error at this
p_form = ProfileUpdateForm()
In the ProfileUpdateForm you defined the model class name without the Meta class
Model name and fields should be defined inside the Meta class like this:
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
I have a profile page with a default profile picture and a 'Change' button beside it which will trigger a modal upon being clicked. In this modal, the image upload button (for choosing the image) will appear along with a submit button. I have created a separate view for handling the image upload. I do not know why a file is not being created after upload. No error message is being given by Django. I suspect it has something to do with settings.py configuration or the action part of my modal field.
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from .forms import KeyForm, Weekly_Item_Form, Daily_Item_Form, ProfileForm
from .models import Key, Weekly_Item, Daily_Item, Profile
def profile_view(request):
profiles = Profile.objects.all()
mainprofile = profiles.last()
if profiles:
form = ProfileForm()
context = {
'page_title':"Profile",
'mainprofile':mainprofile,
'form': form
}
else:
context = {'page_title':"Profile"}
return render(request, "bujo/profile.html", context)
def update_image(request, pk):
mainprofile = Profile.objects.get(id=pk)
form = ProfileForm(instance=mainprofile)
if request.method == 'POST':
form = ProfileForm(request.POST, request.FILES, instance=mainprofile)
if form.is_valid():
form.save()
return redirect('profile')
return redirect('profile')
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('profile/', app_views.profile_view, name='profile'),
path('update_image/<str:pk>', app_views.update_image, name='update_image'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
profile.html
<form method='POST' enctype="multipart/form-data" action="{% url 'update_image' mainprofile.pk %}"> {% csrf_token %}
{{ form.image }}
<input type='submit' class="btn btn-primary"" value='Change profile picture' />
</form>
forms.py
from django import forms
from .models import Profile
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['name', 'image', 'nickname', 'bio']
models.py
class Profile(models.Model):
name = models.CharField(max_length=50, blank=False)
image = models.ImageField(null=True, blank=True, upload_to="images/")
nickname = models.CharField(max_length=20, null=False, blank=True)
bio = models.CharField(max_length=100, null=False, blank=True)
Your form has fields other than image also. You don't render them in the template but the form class expects them, so when the form is submitted it is considered to be not valid. If you want to update only the image create another form class which has only the image field.
In your forms.py add another form class:
from django import forms
from .models import Profile
class ProfileImageForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
In your views:
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from .forms import KeyForm, Weekly_Item_Form, Daily_Item_Form, ProfileForm, ProfileImageForm
from .models import Key, Weekly_Item, Daily_Item, Profile
def profile_view(request):
profiles = Profile.objects.all()
mainprofile = profiles.last() # This line feels weird! You always make the form for the last profile only.
if profiles:
form = ProfileImageForm()
context = {
'page_title':"Profile",
'mainprofile':mainprofile,
'form': form
}
else:
context = {'page_title':"Profile"}
return render(request, "bujo/profile.html", context)
def update_image(request, pk):
mainprofile = Profile.objects.get(id=pk)
form = ProfileImageForm(instance=mainprofile)
if request.method == 'POST':
form = ProfileImageForm(request.POST, request.FILES, instance=mainprofile)
if form.is_valid():
form.save()
return redirect('profile')
return redirect('profile')
Right now, if I enter invalid data into my UserCreationForm and submit it, the page reloads but doesn't show any error. I would like the EmailValidator validator in Django to show the error. I have tried adding the validators attribute to the email field, but it didn't do anything.
Here are my views:
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render
from django.urls import reverse
from .models import CustomUserCreationForm
# Create your views here.
def register(request):
if request.user.is_authenticated:
return HttpResponseRedirect(reverse('index'))
elif request.method == 'GET':
form = CustomUserCreationForm()
elif request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
form.save()
context = {
'user': request.user,
}
return HttpResponseRedirect(reverse('index'), context)
else:
return HttpResponseRedirect(reverse('register'))
else:
return HttpResponse("Project 3: TODO")
context = {
'form': form,
}
return render(request, 'registration/signup.html', context)
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse('login'))
And here are my models:
from django.contrib.auth.models import AbstractUser, AbstractBaseUser
from django import forms
from django.contrib.auth.models import User
from django.db import models
from django.contrib.auth.forms import UserCreationForm
from django.core.validators import EmailValidator
# Create your models here.
# Customer class.
class CustomUser(User):
REQUIRED_FIELDS = ['email', 'first_name', 'last_name']
# Create user registration form class.
class CustomUserCreationForm(UserCreationForm):
first_name = forms.CharField(required=True, max_length=150, help_text='Required.')
last_name = forms.CharField(required=True, max_length=150, help_text='Required.')
email = forms.CharField(required=True, max_length=150, help_text='Required.', validators=[EmailValidator], error_messages={'invalid': 'This does not look like an email address.'})
class Meta:
model = User
fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email',)
# TODO: show an error message when email is incorrectly formatted.
# TODO: make email field unique and show an error message when it was already used.
Use built in EmailField of Django in CustomUserCreationForm
email = forms.EmailField(...)
See this too (validation of email) (form.clean), read this for showing errors of individual form fields
I was just watching a tutorial in youtube and i was just following what was indicated buti still got those errors.
Forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(max_length = 50)
class Meta:
model : User
fields = ['username', 'password1', 'password2']
views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}!')
return redirect('home')
else:
form = UserRegisterForm()
return render (request, 'users/register.html', {'form':form})
I am trying to make a simple signup/login page through django.
I have used UserCreationForm and used a model UserProfile to extend the user model.
I want to retrieve the data posted from form i.e department at my home page after user logged in.
I am new to django so brief explanation would be appreciated.
Thanks in advance
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from mysite.core.models import UserProfile
from django.db import models
class SignUpForm(UserCreationForm):
first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
department = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email','password1', 'password2', 'department',)
def save(self, commit=True):
# Save the provided password in hashed format
user = super(SignUpForm, self).save(commit=False)
user_profile = UserProfile(user=user, department=self.cleaned_data['department'])
user.save()
user_profile.save()
return user, user_profile
views.py
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect
from mysite.core.forms import SignUpForm
#login_required
def home(request):
return render(request, 'home.html')
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user,user_profile = form.save(commit=False)
username = user.cleaned_data.get('username')
raw_password = user.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE,unique=True)
department = models.CharField(max_length=500, blank=True)
home.html in templates:
{% extends 'base.html' %}
{% block content %}
<h2>Welcome, <small>{{ user.username }}</small>!</h2>
<p>Your email address: {{ user.email }}</p>
<p>Department: {{ user_profile.department }}</p>
{% endblock %}
I am able to print username and email but department is coming empty.
Firstly, you have the wrong relationship. There is a one-to-one relationship between User and UserProfile; a user can only have one profile, and a profile can only belong to one user. The way you have it now, a user can have many profiles, which doesn't make sense.
You should replace the ForeignKey with a OneToOneField.
Once you have done that, you will be able to access the profile data via the relationship: user.userprofile.department, and so on.