Django - MultiValueKeyError in form when running test - django

I have a CustomUser model, using django's auth for authentication, and a custom signup view. In the signup form I have some validation to check that the email_suffix (domain of the email) matches with the district that they select in the form. I also check that the email is unique.
When running a test on this, I get an error on the form:
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'district'
Model
class CustomUser(AbstractUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
is_student = models.BooleanField('student status', default=False)
is_teacher = models.BooleanField('teacher status', default=False)
SD23 = 'SD23'
SD39 = 'SD39'
SD67 = 'SD67'
SDISTRICT = [
(SD23, 'Kelowna SD23'),
(SD39, 'Vancouver SD39'),
(SD67, 'Summerland SD67'),
]
district = models.CharField(
max_length=4, choices=SDISTRICT, blank=True, default='SD39')
paper = models.BooleanField(default=False)
def __str__(self):
return self.username
View
def signup(request):
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
to_email = form.cleaned_data.get('email')
# make the username the same as the email
user.username = str(to_email)
user.is_teacher = True
user.is_staff = True
user.is_active = False
user.save()
group = Group.objects.get(name='teacher')
user.groups.add(group)
current_site = get_current_site(request)
print(urlsafe_base64_encode(force_bytes(user.pk)))
sendgrid_client = SendGridAPIClient(
api_key=os.environ.get('SENDGRID_API_KEY'))
from_email = From("doug#smartmark.ca")
to_email = To(to_email)
subject = "Activate your SmartMark Account"
active_link = render_to_string('account/acc_active_email_link.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
html_text = f'Hello {user}<br/><p>Please click on the link below to confirm</p>{active_link}'
html_content = HtmlContent(html_text)
mail = Mail(from_email, to_email, subject,
html_content)
response = sendgrid_client.send(message=mail)
return redirect(reverse('accounts:account_activation_sent'))
else:
form = CustomUserCreationForm()
return render(request, 'account/signup.html', {'form': form})
Form
class CustomUserCreationForm(UserCreationForm):
""" form from class based view """
paper = forms.BooleanField(
label='I agree that keeping a backup paper gradebook is best practice')
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
class Meta:
model = get_user_model()
fields = ('email', 'first_name', 'last_name', 'district', 'paper')
def signup(self, request, user):
user.district = self.cleaned_data['district']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.paper = self.cleaned_data['paper']
user.email = self.cleaned_data['email']
def check_suffix(self, e, d):
email_domain = e.split("#", 2)[1]
t_suffix = email_creation(d)[0] # method which takes the 'district' and creates an email suffix
print(email_domain)
print(t_suffix)
if email_domain == t_suffix:
return True
else:
return False
def clean_email(self):
value = self.cleaned_data["email"]
value_district = self.data["district"]
if not value:
raise forms.ValidationError('An Email address is required.')
check_users = CustomUser.objects.filter(email__iexact=value)
if check_users:
raise forms.ValidationError('This email is already in use.')
if value and not check_users:
if not self.check_suffix(value, value_district):
self.add_error(
"email", "Your email address does not match your school district.")
return value
email_creation method
def email_creation(school_district):
if school_district == "SD23":
teacher_suffix = "sd23.bc.ca"
student_suffix = "learn.sd23.bc.ca"
email_prefix = True
elif school_district == "SD39":
teacher_suffix = "vsb.bc.ca"
student_suffix = "learn.vsb.bc.ca"
email_prefix = True
elif school_district == "SD67":
teacher_suffix = "sd67.bc.ca"
student_suffix = teacher_suffix
email_prefix = True
return(teacher_suffix, student_suffix, email_prefix)
Test
def test_signup_endpoint(self):
email = "foo#vsb.bc.ca"
result = self.client.post('/accounts/signup/', {'email': email})
self.assertEqual(result.status_code, 200)
created_user = get_user_model().objects.get(email=email)
self.assertTrue(created_user.is_active ==
False, created_user.to_dict())
The check_suffix might seem a bit convoluted but the MultiValueDictKeyError is happening before this method is called. The problem seems to be the `self.data['district'], it doesn't like the choice? Do I need to set/define this choice/field in my test? I tried that by adding the following in the test, but it didn't change the error.
email = "foo#vsb.bc.ca"
district = "SD39"

Related

I receive an error when I try to login to an account on my website

I cannot login to any account, because I receive an error:
Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive.(for an admin user)
And
Please enter a correct email and password. Note that both fields may be case-sensitive.
That happens after I update a profile through the profile-detail page. It just throws me to the login page after I press the Update button on the profile-update page.
Here is all the related code:
models.py
class Customer(AbstractUser):
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = UserManager()
customer_id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=50, null=True, blank=True)
last_name = models.CharField(max_length=50, null=True, blank=True)
username = models.CharField(max_length=30, null=True, blank=True)
phone = models.CharField(max_length=10, default='', null=True, blank=True)
email = models.EmailField(validators=[validators.EmailValidator()], unique=True)
description = models.TextField(max_length=1000,blank=True, null=True)
gender = models.CharField('Gender', max_length=10, choices=Gender.choices,
default='Male', null=True)
featured_img = models.ImageField(verbose_name='A profile image',
upload_to='profiles',
default='products/profile_default.jpg')
password = models.CharField(max_length=100, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return f'{self.email} {self.username} {self.customer_id}'
#staticmethod
def get_customer_by_email(email):
try:
return Customer.objects.get(email=email)
except:
return False
def exists(self):
if Customer.objects.filter(email=self.email):
return True
return False
class Meta:
verbose_name = 'Customer'
verbose_name_plural = 'Customers'
# unique_together = ['email']
class Profile(models.Model):
# USERNAME_FIELD = 'email'
profile_id = models.AutoField(primary_key=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
updated = models.DateTimeField(auto_now=True, null=True)
user = models.ForeignKey(Customer, on_delete=models.CASCADE,
related_name="customer", null=True)
class Meta:
verbose_name = 'Profile'
verbose_name_plural = 'Profiles'
# unique_together = ['email']
def __str__(self):
return f' {self.profiled}'
managers.py
class UserManager(BaseUserManager):
def create_user(self, email, first_name=None, description=None, gender=None, featured_img=None, username=None, last_name=None, phone=None, password=None):
if not email:
raise ValueError("User must have an email")
if not password:
raise ValueError("User must have a password")
user = self.model(
email=self.normalize_email(email),
)
user.first_name = first_name
user.username = username
user.last_name = last_name
user.password = make_password(password) # change password to hash
user.phone = phone
user.featured_img = featured_img
user.description = description
# user.profile = profile
user.gender = gender
user.admin = False
user.staff = True
user.active = True
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
if not email:
raise ValueError("User must have an email")
if not password:
raise ValueError("User must have a password")
user = self.model(
email=self.normalize_email(email)
)
user.username = username
user.password = make_password(password) # chang password to hash
user.admin = True
user.staff = True
user.active = True
user.save(using=self._db)
return user
views.py
#csrf_exempt
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST or None)
email = request.POST['email']
if Customer.get_customer_by_email(email=email) == False:
if form.is_valid():
user = form.save(commit=False)
# account = authenticate(request,
# username=email,
# password=request.POST['password'])
user.username = user.username.lower()
user.save()
login(request, user,
backend='allauth.account.auth_backends.AuthenticationBackend')
messages.success(request, 'The account was successfully created!!!')
return redirect(reverse_lazy('products:products'))
messages.error(request, f'{form.errors}')
return redirect(reverse_lazy('user-auth:register'))
return redirect(reverse_lazy('user-auth:login'))
form = SignUpForm()
context = {'form': form, 'user': request.user}
return render(request, 'auth/register/register.html', context)
class ProfileDetailView(
DetailView):
context_object_name = 'customer'
template_name = 'auth/profile_detail.html'
def get_object(self):
profile = Profile.objects.filter(user__customer_id=self.kwargs['pk']).first()
return profile.user
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['user'] = self.request.user
return context
class UpdateProfileView(LoginRequiredMixin,
UpdateView):
template_name = 'auth/profile_update.html'
form_class = ProfileUpdateForm
context_object_name = 'customer'
def get_success_url(self):
success_url = reverse_lazy('user-auth:profile-detail',
kwargs={'pk': self.request.user.customer_id})
return success_url
#method_decorator(ensure_csrf_cookie, name='dispatch')
def post(self, request, *args, **kwargs):
profile = self.get_object()
form = ProfileUpdateForm(instance=profile)
# if request.method == 'POST':
form = ProfileUpdateForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
if profile:
form.save()
messages.success(request, 'Successfully updated!')
return redirect(self.get_success_url())
messages.error(request, 'Profile does not exist!')
return redirect(reverse_lazy('user-auth:signup'))
messages.error(request, 'Invalid data!')
return render(request, self.template_name, self.get_context_data())
def get_object(self):
profile = Profile.objects.filter(user__customer_id=self.kwargs['pk']).first()
return profile.user
# def get(self, request, *args, **kwargs):
# context = {}
# context["form"] = ProfileUpdateForm(instance=self.get_object())
# context['user'] = request.user
# return render(request, self.template_name, context)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["form"] = ProfileUpdateForm(instance=self.get_object())
context['user'] = self.request.user
return context
class DeleteProfileView(LoginRequiredMixin,
DeleteView):
context_object_name = 'customer'
template_name = 'auth/profile_confirm_delete.html'
def get_success_url(self):
success_url = reverse_lazy('user-auth:profile-detail',
kwargs={'pk': self.request.user.customer_id})
return success_url
def post(self, request, *args, **kwargs):
self.request = request
if self.get_object:
messages.success(request, 'Profile deleted successfully!')
return super().delete(request, *args, **kwargs)
messages.success(request, 'Profile does not exist!')
return redirect(reverse_lazy('user-auth:signup'))
def get_object(self):
profile = Profile.objects.filter(user__customer_id=self.kwargs['pk']).first()
return profile.user
signals.py
#receiver(post_save, sender=Customer)
def create_profile(sender, instance, created, **kwargs):
user = instance
if created:
print(user)
Profile.objects.create(
user=user
)
#receiver(pre_save, sender=Customer)
def update_profile(sender, instance, **kwargs):
# print(instance)
profile = instance
if profile.customer_id is not None:
Profile.objects.update(user=profile)
#receiver(post_delete, sender=Customer)
def delete_profile(sender, instance, **kwargs):
user = instance
customer = Customer.objects.filter(email=user.email).first()
if user and customer:
# profile.delete()
customer.delete()
print('Not exists...')
forms.py
class SignUpForm(UserCreationForm):
class Meta:
model = Customer
fields = ('username','phone', 'first_name', 'last_name', 'email', 'featured_img')
# def __init__(self, *args, **kwargs):
# super(SignUpForm, self).__init__(*args, **kwargs)
# for name, field in self.fields.items():
# field.widget.attrs.update({'class': 'input'})
class ProfileUpdateForm(forms.ModelForm):
password1 = forms.CharField(
label="Password",
strip=False,
widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
help_text=password_validation.password_validators_help_text_html(),
required=False
)
password2 = forms.CharField(
label="Password confirmation",
widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
strip=False,
help_text="Enter the same password as before, for verification.",
required=False
)
class Meta:
model = Customer
fields = ('username', 'phone', 'first_name', 'last_name', 'email', 'featured_img', 'description', 'gender')
def save(self, commit=True):
customer = super().save(commit=False)
email = self.cleaned_data.get('email')
customer.email = email.lower()
# customer.password = customer.set_password(self.cleaned_data['password1'])
if commit:
if customer.exists():
super(ProfileUpdateForm, self).save()
return customer
urls.py
from django.contrib.auth import views as auth_views
app_name = 'user-auth'
urlpatterns = [
path('register/', views.signup, name='register'),
path('accounts/login/', auth_views.LoginView.as_view(
template_name='auth/login/login.html',
success_url='products/'),
name='login'
),
path('accounts/logout/', auth_views.LogoutView.as_view(), name='logout'),
path('profile-detail/<int:pk>/', views.ProfileDetailView.as_view(), name='profile-detail'),
path('profile-update/<int:pk>/', views.UpdateProfileView.as_view(),
name='profile-update'),
path('profile-delete/<int:pk>/', views.DeleteProfileView.as_view(),
name='profile-delete'),
]
I have tried to delete my database and fill it in once again. Then I tried to find out why the email or password dis incorrect. Maybe they are wrong in the database. But I have no idea what's going on.

How to make log-in with Django rest api

hello i learning about Django rest api, I am learning through someone else's code, but I don't know how to make Login.
my code :
model:
class User(models.Model):
class Meta:
db_table = "users"
created_at = models.DateTimeField(default = timezone.now)
updated_ay = models.DateTimeField(auto_now= True)
email = models.CharField(max_length = 128, unique= True)
password = models.CharField(max_length = 255)
active = models.BooleanField(default=False)
token = models.CharField(max_length= 255, null = True)
nickname = models.CharField(max_length = 255, null = True)
serializer:
class UserSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
class Meta:
model = User
fields = '__all__'
def to_internal_value(self, data):
ret = super(UserSerializer, self).to_internal_value(data)
# cipher = AESSipher()
# ret['password'] = cipher.encrypt_str(ret['password'])
return ret
def to_representation(self, obj):
ret = super(UserSerializer, self).to_representation(obj)
print(ret)
return ret
def validate_email(self, value):
if User.objects.filter(email=value).exists():
raise serializers.ValidationError("Email already exists")
return value
def validate_password(self, value):
if len(value) < 8:
raise serializers.ValidationError("The password must be at least %s characters long. " % 8)
return value
def create(self, validate_data):
user = User.objects.create(
email = validate_data['email'],
password = validate_data['password'],
)
user.active = False
user.save()
message = render_to_string('user/account_activate_email.html', {
'user': user,
'domain' : 'localhost:8000',
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user)
})
mail_subject = 'sign up mail.'
to_email = 'mymail#gmail.com'
email = EmailMessage(mail_subject, message, to=[to_email])
email.send()
return validate_data
views:
class SignUp(APIView):
def post(self, request):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class UserActivate(APIView):
permission_classes = (permissions.AllowAny,)
def get(self, request, uidb64, token):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk = uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
try:
if user is not None and account_activation_token.check_token(user, token):
user.active = True
user.token = token
user.save()
return Response(user.email + 'email active', status=status.HTTP_200_OK)
else:
return Response('Expired Link', status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
print(traceback.format_exc())
Since I want to handle log-in status in the Mobile Client section,
I want to get only user model information when I log-in.
When Enter Email and Password in Client and I want to get user information.
How to make log-in? Do you know anyone?
Here is the link to the article: custom user authentication; it should help you
https://wsvincent.com/django-rest-framework-user-authentication-tutorial/
Hi you can use Django packages for this. for example you can use rest-auth package this package have all the things that you need for log in log out and reset password and all you need is that follow the rest auth documentation :
. https://pypi.org/project/django-rest-auth/
. https://django-rest-auth.readthedocs.io/en/latest/

Need to search user based on email and then deactivate his profile

I am trying to create a search form, Where admin can search users and then deactivate their profiles, if it is the right account.
tried function based views and then class based views. It shows the profile in function based views but doesn't update it. and in class based view it wouldn't even show the profile.
models.py
class User(AbstractBaseUser):
objects = UserManager()
email = models.EmailField(verbose_name='email address', max_length=255, unique=True,)
type = models.CharField(max_length = 50, choices = type_choices)
name = models.CharField(max_length = 100)
department = models.CharField(max_length = 100, null = True, blank = True, choices = department_choices)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False) # a superuser
admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['type']
forms.py
class SearchForm(forms.Form):
email = forms.EmailField(required=True)
views.py
#method_decorator(login_required, name='dispatch')
class adminDeleteProfileView(LoginRequiredMixin, View):
def render(self, request):
return render(request, 'admin/view_account.html', {'form': self.form})
def form_valid(self, form):
self.form = SearchForm(request.POST)
print('im here', form.cleaned_data.get('email'))
User.objects.filter(email = form.cleaned_data.get('email')).update(active = False)
#print('Donot come here')
def get(self, request):
self.form = SearchForm()
return self.render(request)
#login_required
def admin_deactivate_profile_view(request):
error_text = ''
if request.method == 'POST':
print('here')
user_email = request.POST.get('email')
try:
print('Deactivating',user_email, 'Account.')
profile = User.objects.filter(email = user_email).first()
if request.POST.get('delete'):
User.objects.filter(email = user_email).update(active = False)
messages.success(self.request, 'Profile Updated!')
except Exception as e:
print(e)
messages.success(self.request, 'There was an error!')
return render(request, "admin/delete_profile.html", {'profile':profile})
simple query .
user=User.objects.get(email="user#email.com")
user.activate=false
user.save()

Django always returning invalid form during signup

I am trying to implement email authentication during sign up. But always the compiler returning the invalid form. Can anyone suggest what may be the reason behind this? I am using SALEOR package for this project. Below I have posted model, forms and views code
models.py
class User(PermissionsMixin, AbstractBaseUser):
email = models.EmailField(unique=True)
addresses = models.ManyToManyField(Address, blank=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now, editable=False)
default_shipping_address = models.ForeignKey(
Address, related_name='+', null=True, blank=True,
on_delete=models.SET_NULL)
default_billing_address = models.ForeignKey(
Address, related_name='+', null=True, blank=True,
on_delete=models.SET_NULL)
USERNAME_FIELD = 'email'
objects = UserManager()
forms.py
class SignupForm(forms.ModelForm):
password = forms.CharField(
widget=forms.PasswordInput)
email = forms.EmailField(
error_messages={
'unique': pgettext_lazy(
'Registration error',
'This email has already been registered.')})
class Meta:
model = User
fields = ('email',)
labels = {
'email': pgettext_lazy(
'Email', 'Email'),
'password': pgettext_lazy(
'Password', 'Password')}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self._meta.model.USERNAME_FIELD in self.fields:
self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update(
{'autofocus': ''})
def save(self, request=None, commit=True):
user = super().save(commit=False)
password = self.cleaned_data['password']
user.set_password(password)
if commit:
user.save()
return user
views.py
the else part of if form.is_valid getting executed every time
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST or None)
print('POST Method')
if form.is_valid():
print('Valid Form')
user = form.save(commit=False)
user.is_active = False
user.save()
current_site = get_current_site(request)
mail_subject = "Activate Your Account"
message = render_to_string('account/activate.html', {
'user': user,
'domain': current_site.domain,
'uid':force_text(urlsafe_base64_encode(user.pk)),
'token':account_activation_token.make_token(user),
})
to_email = form.cleaned_data.get('email')
from_email = settings.EMAIL_HOST_USER
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
print('Mail Sent')
return HttpResponse('Please confirm your email address to complete the registration')
else:
form = SignupForm()
print('else of form valid')
return render(request, 'account/signup.html', {'form': form})
else:
print('Not POST Method')
form = SignupForm()
return render(request,'account/signup.html',{'form':form})

Key Error with form - DJANGO

I have a project in django and I am creating a simple form that will allow a user to create a simple profile that asks for name and date of birth and location. I am getting a key error with the date of birth section and I dont know exactly why.
I am trying to collect data and store it to then later added it to a database record.
Here is the views file:
cd = form.cleaned_data
first_name = cd['first_name']
last_name = cd['last_name']
dob_month = cd['dob_month']
dob_day = ['dob_day']
dob_year = ['dob_year']
city = cd['city']
state = cd['state']
phone = cd['phone']
privacy = cd['privacy']
Here is the models file:
user = models.ForeignKey(User, on_delete=models.CASCADE) # server
first_name = models.CharField(max_length=25, default='first')
last_name = models.CharField(max_length=25, default='last')
dob_month = models.IntegerField(default=0)
dob_day = models.IntegerField(default=0)
dob_year = models.IntegerField(default=0)
city = models.CharField(max_length=45) # user
state = models.CharField(max_length=25, default='state')
phone = models.BigIntegerField(default=0) # user
privacy = models.SmallIntegerField(default=1) # user
created = models.DateTimeField(auto_now_add=True) # server
here is the forms file:
class ProfileForm(forms.ModelForm):
split_choices = (('1', 'public'),
('2', 'private'))
privacy = forms.TypedChoiceField(
choices=split_choices, widget=forms.RadioSelect, coerce=int
)
dob = forms.DateField(widget=extras.SelectDateWidget)
class Meta:
model = Profile
fields = ['first_name', 'last_name', 'dob', 'city', 'state', 'phone', 'privacy']
and finally, here is the error that I am getting:
KeyError at /setup_profile/
'dob_month'
Request Method: POST
Request URL: http://127.0.0.1:8000/setup_profile/
Django Version: 1.8.6
Exception Type: KeyError
Exception Value:
'dob_month'
Exception Location: C:\Users\OmarJandali\Desktop\opentab\opentab\tab\views.py in profile_setup, line 292
first_name 'omar'
last_name 'jandali'
dob_month '1'
dob_day '23'
dob_year '2024'
city 'riverside'
state 'ca'
phone '9515343666'
privacy '1'
submit 'submit'
UPDATED:
here is the views.py file but the issue is with the cd['dobv_month'], but i have no idea why the error is coming from there.
def profile_setup(request):
if 'username' not in request.session:
return redirect('login')
else:
# the following is just going to grab the currently logged in user and
# save the profile information to the appropriate user
username = request.session['username']
currentUser = User.objects.get(username = username)
# the following is the provessing for the form where the user entered
# the profile informaiton
if request.method == 'POST':
form = ProfileForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
first_name = cd['first_name']
last_name = cd['last_name']
dob_month = cd['dob_month']
dob_day = ['dob_day']
dob_year = ['dob_year']
city = cd['city']
state = cd['state']
phone = cd['phone']
privacy = cd['privacy']
# this is the new record that is going to be created and saved
new_profile = Profile.objects.create(
user = currentUser,
first_name = first_name,
last_name = last_name,
dob_month = dob_month,
dob_day = dob_day,
dob_year = dob_year,
city = city,
state = state,
phone = phone,
privacy = privacy,
)
return redirect('home_page')
else:
# this is what is going to be saved into the html file and used to
# render the file
form = ProfileForm()
message = 'fill out form below'
parameters = {
'form':form,
'currentUser':currentUser,
'message':message,
}
return render(request, 'tabs/profile_setup.html', parameters)
Let's say your model name is User.
forms.py:
from .models import User
class UserForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
class Meta:
model = User
fields = '__all__'
and views.py:
def user_create(request):
form = UserForm(request.POST or None)
if request.method == 'POST':
form = UserForm(request.POST or None)
if not form.is_valid():
print form.errors
return render(request, 'user_create.html', {'form': form})
else:
first_name = form.cleaned_data.get("first_name")
last_name = form.cleaned_data.get("last_name")
# pass your extra fields here
new_user = User.objects.create_user(
user=user,
first_name=first_name,
last_name=last_name,
)
new_user.save()
return redirect('where you want to redirect',)
return TemplateResponse(request, 'user_create.html')
finally user will be save.
Read docs:https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/