Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7837489
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T14:39:29+00:00 2026-06-02T14:39:29+00:00

I am still experiencing some problems with understanding forms and relationships between model-forms. I

  • 0

I am still experiencing some problems with understanding forms and relationships between model-forms.
I am getting an error:
UserProfile.location” must be a “Location” instance.

I’ve set location in models to blank=True, null=True and required=False in forms.py.
And I dont really know at this point what to do with that.

How I can fix that problem?

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

class Location(models.Model):
    location = models.CharField(max_length=32)
    #county = models.CharField(max_length=32)
    #province = models.CharField(max_length=32)

class UserProfile(models.Model):
    user = models.OneToOneField(User, unique=True, primary_key=True)
    location = models.ForeignKey("Location", null=True, blank=True)

    website = models.URLField("Site", null=True, blank=True)
    accepted_rules = models.BooleanField(default=False)
    accepted_rules_date = models.DateTimeField(auto_now_add=True)

    #points_count = models.IntegerField(default=0, null=True, blank=True)
    #posts_count = models.IntegerField(default=0, null=True, blank=True)
    #comments_count = models.IntegerField(default=0, null=True, blank=True)

Forms:

from django import forms
from django.forms import Form
from django.forms.models import ModelForm
from accounts.models import UserProfile, Location
from django.contrib.auth.models import User


class UserCreationForm(forms.Form):

    username = forms.CharField(max_length=32)
    password = forms.CharField(widget=forms.PasswordInput())
    email = forms.EmailField()
    #password_repeat = forms.CharField(widget=forms.PasswordInput(render_value=False))

    def clean_username(self):

        try:
            # iexact = case-insensitive match / important for validation
            User.objects.get(username__iexact=self.cleaned_data['username'])
            print "User does already exist"
    except User.DoesNotExist:
        return self.cleaned_data['username'] 
    else:
        raise forms.ValidationError("User already exists")



def clean_email(self):

    if User.objects.filter(email__iexact=self.cleaned_data['email']):
        print u'Adres email jest już używany.' 
        raise forms.ValidationError('Adres email jest już używany.') 
    else:
        return self.cleaned_data['email']

def save(self):
    user  = User.objects.create(username = self.cleaned_data['username'], email = self.cleaned_data['email'],)

    user.set_password(self.cleaned_data['password'])
    return user


class UserProfileForm(ModelForm):
    website = forms.URLField(label="website", required=False)
    location = forms.ChoiceField(required=False)

    class Meta:
        model = UserProfile
        include = ['website', 'location']
        exclude = ('user', 'type', 'accepted_rules')

Views

contrib.auth.models import User
from django.template.response import TemplateResponse
from django.views.decorators.csrf import csrf_protect
from django.core.context_processors import csrf
from django.forms.models import inlineformset_factory
from django.http import HttpResponseRedirect

from accounts.forms import UserCreationForm, UserProfileForm



def index(request):
    return TemplateResponse(request, "base.html")

@csrf_protect
def register(request):
    form = UserCreationForm()
    user_profile = UserProfileForm()

    if request.method == "POST":

        form = UserCreationForm(prefix='user', data=request.POST or None)
        user_profile = UserProfileForm(prefix='profile', data= request.POST or None)

        if form.is_valid() and user_profile.is_valid():
            user = form.save()
            profile = user_profile.save(commit=False)
            profile.user = user
            profile.save()


            return HttpResponseRedirect("/")

    return TemplateResponse(request, 'accounts/register.html', {
                             'form':form,
                             'user_profile':user_profile ,
                             }
                            )
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T14:39:30+00:00Added an answer on June 2, 2026 at 2:39 pm

    The problem is here.

    class UserProfileForm(ModelForm):
        website = forms.URLField(label="website", required=False)
        location = forms.ChoiceField(required=False)
    
        class Meta:
            model = UserProfile
            include = ['website', 'location']
            exclude = ('user', 'type', 'accepted_rules')
    

    ModelForm will generate needed fields for your form. You don’t need to define them manually. So you should use something like this.

    class UserProfileForm(ModelForm):
        class Meta:
            model = UserProfile
            include = ['website', 'location']
            exclude = ('user', 'type', 'accepted_rules')
    

    Another thing. There is no include option, I think you wanted to use fields. But you don’t have to use both fields and exclude, usually you need to use one them. In your case exclude is enough. Final result:

    class UserProfileForm(ModelForm):
        class Meta:
            model = UserProfile
            exclude = ('user', 'type', 'accepted_rules')
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm experiencing some problems regarding Twitter OAuth within an android activity. I read a
I've just uploaded my site to GoDaddy hosting and experiencing some problems with URL
I've tried applying several suggestions found on the web, but still experiencing cached results
still a bit of a n00b on SharpSVN, I'm looking to get some simple
I'm experiencing some problem when I compile some legacy apps on VB6 since I
I am experiencing some weird behavior with an android app I have been working
I am still experiencing a strange menu problem (the last menu item of the
We are experiencing some serious scaling challenges for our intelligent search engine/aggregator . Our
noob here still experimenting with templates. Trying to write a message processing class template
I've been experimenting with making Facebook apps and I'm still not clear on app

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.