With Django 'str' object is not callable in class based-views

1

I have this problem when I want to access a URL that tells me that it is str object is no callable surely I have something wrong in the urls or a configuration of those but the truth is that I have reviewed all the files well and I do not understand very why you must this error.

I leave the codes that I think are influencing some of the error. If you need some more tell me and I add it too. Also if you could give me an explanation of the error to know better why. I know it's a data that python is not reading correctly.

models.py

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

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    date_of_birthday = models.DateField()
    address = models.TextField()
    phone_number = models.CharField(max_length=11)

    def __str__(self):
        return self.user.first_name

class UserForm(ModelForm):
    class Meta:
        model = UserProfile
        fields = '__all__'

views.py

from django.shortcuts import render

from django.views.generic import CreateView

from .models import UserProfile

class UserCreateView(CreateView):
    model = UserProfile
    template_name = 'userprofiles/user_create.html'
    success_url = '/'
    form_class = 'UserForm'

    def form_valid(self, form):
        form.save()
        return super(UserCreate, self).form_valid(form)

urls.py

from django.conf.urls import url 

from .views import UserCreateView

app_name = "users"
urlpatterns = [
    url(r'^create/', UserCreateView.as_view(), name="user_create"),
]

template

<form action="{% url 'users:user_create' %}" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Crear Usuario</button>
</form>

If anyone could help me with this, I would appreciate it a lot.

Greetings.

    
asked by ikenshu 31.08.2016 в 17:43
source

1 answer

3

The problem is in the attribute form_class of your view UserCreateView .

When the view is executed, a method called .get_form() is called, in which a line similar to this one is executed:

self.form_class(...)

As you see, create an instance of what is in the class attribute form_class , as you have a string there: 'UserForm' can not make a call (I mean instantiate it with () ) to a string. Instead you must import your UserForm and place the class as a value in form_class :

from my_app.forms import UserForm  # ruta de ejemplo

class UserCreateView(CreateView):
    model = UserProfile
    template_name = 'userprofiles/user_create.html'
    success_url = '/'
    form_class = UserForm  # sin comillas

    def form_valid(self, form):
        form.save()
        return super(UserCreate, self).form_valid(form)
    
answered by 31.08.2016 / 21:27
source