0

I'd like to save custom field in django allauth. I created models and forms to make separate table and I can save the user_id in that table. But I can't save the actual custom field in that table. The table is myApp_userprofile represented by the UserProfile model.

from django.db import models
from django.contrib.auth.models import User

from django.db.models.signals import *


class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')

    school = models.CharField(max_length=128, blank=False)

    def __unicode__(self):  # __str__
        return unicode(self.user.username)

    def create_user_profile(sender, instance=None, created=False, **kwargs):
        if created:
            profile, created = UserProfile.objects.get_or_create(user=instance)

    post_save.connect(create_user_profile, sender=User) 

When I save the form it saves only user_id without any errors but school field is empty. Could you please let me know what I miss? And Yes, I'm a super newbie in python

forms.py

from django import forms
from .models import UserProfile

SCHOOL = (
    ('', 'Select your school...'),
    ('ucla.edu', 'UCLA'),
    ('berkeley.edu', 'Berkeley'),
    ('gmail.com', 'Test Gmail'),
)

class SignupForm(forms.Form):
    school = forms.ChoiceField(choices=SCHOOL, required=True)

    def signup(self, request, user):

        profile = UserProfile()
        profile.school = self.cleaned_data['school']
        #profile.save(profile, update_fields=['school'])
        profile.create_user_profile(profile)

signup.html

<form id="signup_form" method="post" action="{% url 'account_signup' %}">
                            {% csrf_token %}
                            {{ form|crispy }}

                            {% if form.non_field_errors %}
                            <div class="alert alert-warning">
                              <ul class="alert-message">
                                {% for error in form.non_field_errors %}
                                <li>{{ error }}</li>
                                {% endfor %}
                              </ul>
                            </div>
                            {% endif %}

                            {% if redirect_field_value %}
                                <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
                            {% endif %}
                            <div class="footer text-center">
                                <button class='btn btn-primary btn-raised btn-lg' type="submit" id="btnSignUp">{% trans "Sign Up" %}</button>
                            </div>
                        </form>

Thanks ahead!!!

MrKarl
  • 19
  • 1
  • 3

0 Answers0