Django: form not displaying in browser - django

The form doesn't display in the browser. The navbar and submit button show up but no form in between. The problem must be straightforward but I haven't been able to find the issue. Thank you for your help.
views.py
def ProductCreateView(request):
if request.method == 'POST':
form = ProductForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('set_app/product_list.html'))
else:
product_form = ProductForm()
return render(request, 'set_app/product_form.html', {'product_form':product_form})
forms.py
class ProductForm(forms.Form):
class Meta():
model = models.Product
fields = ('code', 'barcode', 'name', 'description', 'brand', 'status')
product_form.html
{% extends "set_app/basic_app_base.html" %}
{% block body_block %}
<h1>
{% if not form.instance.pk %}
Create Product
{% else %}
Update Product
{% endif %}
</h1>
<form method="post">
{% csrf_token %}
{{ product_form.as_p }}
<input type="submit" class="btn btn-primary" value="Submit">
</form>
{% endblock %}

Found the issue:
in forms.py
instead of
class ProductForm(forms.Form):
it should be
class ProductForm(forms.ModelForm):

Related

Django form keeps complaining required field

The form submits but immediately says this field is required... although it was filled out. What am I doing wrong
In my view:
def fileupload(request):
if request.user.is_authenticated and request.user.is_staff:
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES.getlist('file_field'))
return HttpResponseRedirect('/fileupload/')
else:
form = UploadFileForm()
return render(request, 'fileupload.j2.html', {'form': form})
return HttpResponseForbidden('<h1>403 Forbidden</h1>')
with this form:
class UploadFileForm(forms.Form):
kit_number = forms.CharField(label="Kit number", max_length=100, required=True, help_text='Required.')
file_field = forms.FileField(label='Upload kit result')
and template:
{% extends "menu.j2.html" %}
{% block content %}
{% if request.user.is_authenticated and request.user.is_staff %}
<h3>File upload</h3><br><br>
<form action="/fileupload/" method="post">
{% csrf_token %}
<div class="form-group">
<table>
{{ form.as_table() }}
</table>
</div>
<input id="button" class="btn" type="submit" value="Sent">
</form>
{% else %}
You are not authorized to see this page
{% endif %}
{% endblock %}
You forgot to set the form enctype.
<form action="/fileupload/" method="post" enctype="multipart/form-data">

Django creating update post function

I want to create a post update/edit function but I have a problem. When I click "Update" button there is no error but there is no change. I think reason of that a mistake that I made in models.py but I can not figure it out. And here is my code
models.py
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
.
.
.
def get_update_url(self):
return reverse('post:post_update', kwargs={'slug': self.slug})
views.py
def post_update(request, slug):
if not request.user.is_authenticated():
return Http404()
post = get_object_or_404(Post, slug=slug)
form = PostForm(request.POST or None, request.FILES or None, instance=post)
if form.is_valid():
form.save()
messages.success(request, "Updated")
return HttpResponseRedirect(get_absolute_url())
context = {
'form': form
}
return render(request, "blog/post_update.html", context)
post_update.html
{% extends 'blog/base.html' %}
{% load crispy_forms_tags %}
{% block body %}
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h1>Form</h1>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
{{ form.media }}
<input class="btn btn-primary" type="submit" value="Create post">
</form>
</div>
</div>
</div>
{% endblock %}
post_detail.html
//update link
<p >update</p>
urls.py
url(r'^(?P<slug>[\w-]+)/update/$', post_update, name="update"),
forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'text',)
Where is my mistake? What can I do?

Django Issues: ManagementForm data is missing or has been tampered with

I'm trying to create a simple todo list using built-in generic views.
Here's my views.py
class TaskList(ListView):
paginate_by = 5
template_name = 'todo/index.html'
context_object_name = 'formset'
def get_queryset(self):
return TaskFormSet(queryset=Task.objects.all())
def post(self, request):
formset = TaskFormSet(request.POST)
if formset.has_changed() and formset.is_valid():
formset.save()
return redirect('/todo')
And here's my template
<form method="post">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
<div>
{% for field in form %}
{{ field }}
{% endfor %}
</div>
{% endfor %}
<input type="submit" value="+">
</form>
So when I submit form I get ['ManagementForm data is missing or has been tampered with']
What's the deal?

nothing happens when submitting django form

I have a problem with django forms, when submitting a form nothing seems to happen, even the server didn't get any response except GET request to view the form template.
here is my code for the forms.py :
from django.forms import ModelForm
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = [
"title",
"content",
"category"
]
and here is my post_form.html :
{% extends 'base.html' %}
{% block content %}
<h1>form</h1>
<form method="POST" action=".">
{% csrf_token %}
{{ form.as_p }}
</form>
<button type="submit">Create Post</button>
{% endblock content %}
and here is my handling for the form in views.py :
def post_create(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect("posts:detail", pk=post.pk)
else :
form = PostForm()
context = {
"form":form,
}
return render(request,"post_form.html", context)
forms.py
from django.forms import ModelForm
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ["title", "content", "category"]
views.py
def post_create(request):
form = PostForm()
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save()
return redirect("posts:detail", pk=post.pk)
return render(request,"post-form.html", {"form": form})
post-form.html
{% extends 'base.html' %}
{% block content %}
<h1>form</h1>
{% for error in form.non_field_errors %}
<article class="message is-danger alert-message">
<div class="message-body">
<p>{{ error|escape }}</p>
</div>
</article>
{% endfor %}
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Create Post">
</form>
{% endblock content %}
in your views:
if form.is_valid():
form.commit = False
form.save()
or
if form.is_valid():
form.save(commit=false)
I suggest the latter
Don't Forget Place Your Submit Button In Form Tag !

django forms comments not visible

i can add comments in db and see its in admin panel but dont see added comments in posts (view_post.html).
i dont understand reason for this
models:
class Comment(models.Model):
name = models.CharField('Имя:', max_length=100)
create_date = models.DateField(blank=True, null=True)
text = models.TextField()
def __str__(self):
return '%s' % self.name
forms:
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ['name', 'create_date', 'text']
views:
def view_post(request, slug):
post_detail = get_object_or_404(Article, slug=slug)
form = CommentForm(request.POST or None)
if form.is_valid():
comment = form.save(commit=False)
comment.post_detail = post_detail
comment.save()
return redirect(request.path)
return render_to_response('view_post.html', {
'post_detail': post_detail, 'form': form },
context_instance=RequestContext(request))
post template:
{% extends 'base.html' %}
{% block head_title %}{{ post_detail.title }}{% endblock %}
{% block title %}{{ post_detail.title }}{% endblock %}
{% block content %}
{{ post_detail.body }}
{% if post_detail.comment_set.all %}
{% for comment in post_detail.comment_set.all %}
{{ comment.name }}
{{ comment.text }}
{% endfor %}
{% endif %}
<form action="" method="POST">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" name="submit" value="Submit" />
</form>
{% endblock %}
You set comment.post_detail to the current Article when saving, but there you don't actually seem to have a post_detail ForeignKey. In fact you don't seem to have any relationship between Comment and Article at all, or between Comment and anything.