I've been trying to create a method to upload a profile picture for a user at the time of registration. In order to do so, I created a custom ModelForm with a file field and displayed this along with a UserCreationForm. However, it throws this error
ValueError at /signup
The UserProfile could not be created because the data didn't validate.
Files :-
models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user=models.OneToOneField(User, on_delete=models.CASCADE)
img=models.FileField(upload_to="profile/")
def __str__(self):
return self.user.username
forms.py
from django import forms
from . models import UserProfile
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
# Create your models here.
class ImgForm(forms.ModelForm):
class Meta:
model=UserProfile
fields=['img']
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.signin, name="signin"),
path('signup', views.signup, name="signup"),
path('logout', views.logout, name="logout")
]
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib import auth
from django.http import HttpResponse
from .forms import ImgForm
from django.contrib.auth.forms import UserCreationForm
# Create your views here.
def signup(request):
if request.method == 'POST':
form=UserCreationForm(request.POST)
imgform=ImgForm(request.POST, request.FILES)
if form.is_valid() and imgform.is_valid():
#looks good
user = form.save()
img=imgform.save()
img.user=user
return redirect('/')
else:
html = "<html><body><script>alert('Invalid form')</script></body></html>"
return HttpResponse(html)
else:
form=UserCreationForm()
imgform=ImgForm()
context={
'form':form,
'imgform':imgform
}
return render(request, "register/signup.html", context)
Form HTML Code (Signup.html)
<div class="card-body">
<h1>Sign Up</h1>
<form action="{% url 'signup' %}" method="POST">
{% csrf_token %}
{{form.as_p}}
{{imgform.as_p}}
<div class="row">
<div class="col-4 text-right">
<input type="submit" class="btn btn-primary" value=" Sign Up " />
</div>
</div>
</form>
</div>
What I've tried :
Tried removing the imgform validity check (removed imgform.is_valid()
) in views.py, removed all instances of imgform and the form submitted with no issues (without the image ofcourse). So my best guess is the error is caused due to saving imgform incorrectly. Couldn't figure out the problem myself. Any sort of help is appreciated!
Thanks.