Home > Blockchain >  I get a form object when I need want to get a form:
I get a form object when I need want to get a form:

Time:01-30

Views.py:

from django.shortcuts import render, redirect
from .forms import UserRegisterForm, UserPostForm
from django.contrib.auth.models import User

def register(request):
    if request.method == "POST":
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')
    else:
        form = UserRegisterForm()
    return render(request, 'users/register.html', {'form':form})

def profile(request, username):
    post_form = UserPostForm()
    context = {
    'username': username,
    'post_form': post_form,
    }

    return render(request, 'users/profile.html', context)

urls.py:

from django.contrib import admin
from django.urls import path, include
from users import views as user_views

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("photoblog.urls")),
    path("register/", user_views.register, name="register"),
    path("profile/<str:username>", user_views.profile, name="profile")

profile.html:

{% extends 'photoblog/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
    <h1>Welcome to the {{ username }} profile page</h1>
    <form method="POST">
        {{post_form}}
    </form>
    
{% endblock %}

forms.py:

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from photoblog.models import Post

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

class UserPostForm():
    class Meta:
        model = Post
        fields = ['title', 'author', 'content', 'date_posted']

Whenever I load up the page, I get an <users.forms.UserPostForm object at 0x7ff183aea670> when I want the actual form to show up on the page. How do I get that to work?

I tried uploading UserPostForm() as a variable in the view function and was expecting it to render out as form on the page.

CodePudding user response:

You did not inherit from ModelForm, hence this is not a form, you work with:

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from photoblog.models import Post

from django import forms


#     inherit from ModelForm            
  • Related