My form data is not being displayed on html template - python

i made a form and now i am trying to to view the data from the form on the html template but its not working, any help would be helpful i just want the the data entered through the the form to be displayed on the html page. Here is the code
views.py
from django.shortcuts import render
from .models import Post
from.forms import TaskForm
def add_task(request):
form = TaskForm()
if request.method == 'POST':
print(request.POST)
form = TaskForm(request.POST)
if form.is_valid():
form.save()
context = {'form': form}
return render(request, 'List/add_task.html', context)
def home(request):
return render(request, 'List/home.html')
def task_list(request):
context = {
'posts': Post.objects.all(),
}
return render(request, 'List/task.html', context)
models.py
from django.db import models
class Post(models.Model):
Task = models.CharField(max_length=50, default='pythons')
Detail = models.TextField(max_length=100, default='python')
date = models.DateTimeField(auto_now_add=True)
forms.py
from django.forms import ModelForm
from .views import Post
class TaskForm(ModelForm):
class Meta:
model = Post
fields = '__all__'
task.html
{% extends "List/Home.html" %}
{% block content %}
{% for post in posts %}
<h3>{{ post.title }}</h3>
<h3>{{ post.detail }}</h3>
{% endfor %}
{% endblock content %}

in your Post model you have fields name Task and Detail and in your template you are looking for field title and detail

Related

"Post.user" must be a "User" instance

I am new to using django and I'm creating a simple webpage that takes in user input and saves it to the Model Form
models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
post = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE)
forms.py
from django import forms
from .models import Post
class HomeForm(forms.ModelForm):
post = forms.CharField()
class Meta:
model = Post
fields = ('post',)
views.py
from django.shortcuts import render, redirect
# Create your views here.
from django.http import HttpResponse
from django.views.generic import TemplateView
from .forms import HomeForm
class HomeView(TemplateView):
template_name = 'home.html'
def get(self, request):
form = HomeForm()
return render(request, self.template_name, {'form': form})
def post(self, request):
form = HomeForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save()
text = form.cleaned_data['post']
form = HomeForm()
return redirect('home.html')
args = {'form': form, 'text': text}
return render(request, self.template_name, args)
home.html
{% block body %}
<div class ='container'>
<h1>Home</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type ='submit'>Submit</button>
</form>
</div>
{% endblock %}
When I run the server the webpage comes up normal but when I type in some input an error page pops up and says : ValueError at /
Cannot assign ">": "Post.user" must be a "User" instance.
Any Help would be appreciated!

I am not able to retrive OneToOneField data from backend Django

i can get data from backend from User e.g user.id but when i want to get data from OneToOneField e.g user.checkAdmin.isAdmin its not displaying any data in html page
views.py
def registerView(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
isAdminForm = checkAdminForm(request.POST) #
if form.is_valid() and isAdminForm.is_valid():
user = form.save()
isAdminFormObject = isAdminForm.save(commit=False)
isAdminFormObject.user = user
isAdminFormObject.save()
return redirect('login_url')
else:
form = UserCreationForm()
isAdminForm = checkAdminForm()
return render(request, 'registration/register.html',{'form':form,'isAdminForm':isAdminForm})
Forms.py
from django import forms
from .models import checkAdmin
class checkAdminForm(forms.ModelForm):
class Meta:
model = checkAdmin
fields = ['isAdmin']
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class checkAdmin(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
isAdmin = models.BooleanField(default=False)
def __str__(self):
return self.user.username
dashboard.html
{% extends 'index.html' %}
{% block content %}
<h1>Welcome, {{ user.id }}</h1>
<h1>check?,{{ user.checkAdmin.isAdmin }}</h1>
<button>Mark Attendance</button> <button>Mark Leave</button> <button>View Attance</button>
Logout
{% endblock %}
use checkadmin instead of checkAdmin
{% extends 'base.html' %}
{% block content %}
<h1>Welcome, {{ user.id }}</h1>
<h1>check?,{{ user.checkadmin.isAdmin }}</h1>
<button>Mark Attendance</button> <button>Mark Leave</button> <button>View Attance</button>
Logout
{% endblock %}

Can't get forms to render in Django

I'm working on a project and I don't get the django forms to render on any of my pages. I've compared it to django girls code, as that is what I usually consult but it looks virtually identical to it. It's not just this page, my other pages have issues with rendering the forms as well. Here's the code:
Views.py
from django.shortcuts import render
from .models import *
from .forms import *
from django.shortcuts import render, get_object_or_404
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.db.models import Sum
from django.utils import timezone
from django.views.decorators.http import require_POST
from .cart import Cart
from django.db import transaction
from django.contrib import messages
#login_required
def post_edit(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = PostForm(request.POST, instance=post)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm(instance=Post)
return render(request, 'rentadevapp/post_edit.html', {'rentadevapp': post_edit}, {'form': form})
Forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'text',)
post_edit.html
{% extends 'rentadevapp/base.html' %}
{% load staticfiles %}
{% load crispy_forms_tags %}
{% block content %}
<head>
<link rel="stylesheet" href="{% static 'css/post_edit.css' %}">
</head>
<body>
<div class="container"><br>
<h2>New Post</h2><br>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
</div>
</body>
{% endblock %}
Models.py
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
updated_date = models.DateTimeField(auto_now_add=True)
price = models.DecimalField(max_digits=10, decimal_places=2, default='0')
class Meta:
ordering = ('title',)
def created(self):
self.created_date = timezone.now()
self.save()
def updated(self):
self.updated_date = timezone.now()
self.save()
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
I'm pretty stuck and have spent a couple hours trying to figure this out. Any help is really appreciated.
Thanks!
Your form isn't returned to the template in the context.
In Django 1.11 or 2.2 the render function call in your view should return a dictionary of context variables as the third argument, but you've got two dictionaries. The 4th argument where you've got a dictionary containing the form is being passed as content_type which is then used in the HttpResponse so I'm quite surprised there isn't something strange happening or an error seen.
So you're doing;
return render(request, 'rentadevapp/post_edit.html', {'rentadevapp': post_edit}, {'form': form})
What you need to do is;
context = {'form': form, 'rentadevapp': post_edit}
return render(request, 'rentadevapp/post_edit.html', context)
Prior to 1.10 render had a different signature, but the first three arguments of request, template_name, context have been that way since <1.8

Django form fields not loading in template

I can't seem to get a model form to load in my template.
models.py
from django.db import models
class Event(models.Model):
name = models.CharField(max_length=60)
start_datetime = models.DateTimeField()
end_datetime = models.DateTimeField()
description = models.TextField()
forms.py
from django import forms
from .models import Event
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = ['name']
views.py
from django.shortcuts import render
from .forms import EventForm
def index(request):
if request.method == 'POST':
form = EventForm(request.POST)
if form.is_valid():
form.save()
else:
form = EventForm()
return render(request, 'index.html')
index.html
<form method="POST" action="">
{% csrf_token %}
{{ form.as_p }}
</form>
<button type="submit">Save</button>
I can get the form to print to the console on load when adding print(form) in views.py on the GET request, but it doesn't load in the template.
Good examples on different ways to use forms : https://docs.djangoproject.com/en/1.11/topics/forms/#the-view
For index.html to render it is expecting form variable. So Render method call should be like this:
render(request, 'index.html', {'form': form})

Django: Form is not saving to database

I've seen similar types of problems on here but I still haven't been able to work out my problem. When I save PhotographerProfileForm in my view, the form is rendered correctly but after clicking update/submit nothing is actually saved.
No errors are shown either.
What I have now are the fields are prepopulated and I would like the ability to save over these in the database, but nothing happens and at the moment you can only update it from the admin panel.
models.py
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
# Create your models here.
class PhotographerProfile(models.Model):
user = models.OneToOneField(User)
location = models.CharField(max_length=200)
bio = models.TextField(max_length=500)
def __str__(self):
return self.user.username
User.profile = property(lambda u: PhotographerProfile.objects.get_or_create(user=u)[0])
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=User)
def create_profile(sender,instance,created,**kwargs):
if created:
profile, new = PhotographerProfile.objects.get_or_create(user=instance)
urls.py
urlpatterns = [
url(r'^profile/$', 'photoprofile.views.photographer_profile', name = 'photographer_profile'),
url(r'^profile/portfolio/$', 'photoprofile.views.photographer_portfolio', name='photographer_portfolio'),
]
views.py
#login_required
def photographer_profile(request):
photographerProfile = PhotographerProfile.objects.get(user=request.user)
form = PhotographerProfileForm(initial={'bio':photographerProfile.bio, 'location':photographerProfile.location})#This means you can prepoulate it
return render_to_response('photographerprofile.html',{'form':form}, RequestContext(request))
if request.method == 'POST':
form = PhotographerProfileForm(request.POST, instance = request.user.profile,)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/profile')
else:
user = request.user
profile = user.profile
form = PhotographerProfileForm()
return render(request, 'photographerprofile.html', {'form':form})
def photographer_portfolio(request):
photographerProfile = PhotographerProfile.objects.get(user=request.user)
return render_to_response('photographerportfolio.html', {'photographerProfile':photographerProfile}, RequestContext(request))
forms.py
class PhotographerProfileForm(forms.ModelForm):
class Meta:
model = PhotographerProfile
exclude = ('user',)
photographerprofile.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<h2> Profile</h2>
{% for field in form %}
{{ field.error}}
{% endfor %}
<form action='/accounts/profile/' method='post'>
{% csrf_token %}
{{form|crispy}}
<input type='submit' value='Update'/>
<p>Click <a href='/accounts/profile/portfolio/'>here</a> to view portfolio. </p>
</form>
{% endblock %}
You return in the third line of your view, before the form has been processed. Remove that line.

Categories