Django-form not rendered in HTML - python

The view that **renders** is
def codequestion(request, question_id):
question = Question.objects.get(pk=question_id)
return render(request, 'polls/codequestion.html', {'question': question})
the view that is called on submission is
def codequestion_evaluate(request, question_id):
form = CodeForm()
print request.method
if request.method == 'POST':
form = CodeForm(request.POST)
if form.is_valid():
data = form.cleaned_data
return HttpResponse("Your code is %s" % data['solution'])
else:
return HttpResponse("not valid")
else:
return HttpResponse("Error")
class
from django import forms
class CodeForm(forms.Form):
solution = forms.CharField(widget=forms.Textarea)
template
<form action="{% url 'codequestion_evaluate' question.id %}" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Submit" />
</form>
I do not get the form field display in the HTML page, I can only see the submit button.

The view that is suppose to show the unfilled form doesn't create the form object at all. It should create a form object and pass it to the template, like this:
def codequestion(request, question_id):
question = Question.objects.get(pk=question_id)
form = CodeForm()
return render(request, 'polls/codequestion.html', {'question': question, 'form': form})
But better yet you should follow the pattern described in Django documentation. To do this you should:
Delete the codequestion. All actions (displaying the unfilled form, displaying a submitted form with errors, processing a correctly submitted form) will be handled by a single view.
Configure your url routing so codequestion_evaluate view handles the page showing the unfilled form.
Change codequestion_evaluate so it follows the pattern:
def codequestion_evaluate(request, question_id):
if request.method == 'POST':
form = CodeForm(request.POST)
if form.is_valid():
# The form has been submitted and is valid
# process the data and redirect to a "thank you" page
data = form.cleaned_data
return HttpResponseRedirect('/thanks/')
else:
# just display an empty form
form = CodeForm()
# you can optionally add 'question' if you need it in your template
question = Question.objects.get(pk=question_id)
return render(request, 'polls/codequestion.html', {'form': form, 'question': question})

form refers to a variable in your context data, since you haven't included it in the context data, it can't find it so there isn't anything to render, you need to include it.
def codequestion(request, question_id):
question = Question.objects.get(pk=question_id)
return render(request, 'polls/codequestion.html',
{'question': question, 'form': CodeForm()})

Try changing
class CodeForm(forms.Form):
to
class CodeForm(forms.ModelForm):
I faced same problem but it got resolved from this.

The recent distributions of django don't have widgets included. So:
pip install django-widgets
should do the trick.

Related

how can i prepopulate this update form [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
i want the form to be prepopulated with data when i am editing the form
views.py
def edit_task(request, post_id):
post = Post.objects.get(id=post_id)
form = TaskForm(request.POST, instance=post)
if request.method == 'POST':
print(request.POST)
form = TaskForm(request.POST, instance=post)
if form.is_valid():
form.save()
return redirect('task')
context = {'form': form}
return render(request, 'List/add_task.html', context)
add_task.html
{% extends "List/Home.html" %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
{% endblock content %}
Think carefully about how you instantiate forms. At the moment, you are using the same code TaskForm(request.POST, instance=post) for GET and POST requests:
def edit_task(request, post_id):
post = Post.objects.get(id=post_id)
form = TaskForm(request.POST, instance=post)
if request.method == 'POST':
print(request.POST)
form = TaskForm(request.POST, instance=post)
...
But request.POST is empty for GET requests, so you'll get an empty form with errors when you load the form with a GET request.
You can fix it by removing request.POST for GET requests
def edit_task(request, post_id):
post = Post.objects.get(id=post_id)
# Instantiate form without any data
form = TaskForm(instance=post)
if request.method == 'POST':
print(request.POST)
# replace the form for POST requests
form = TaskForm(request.POST, instance=post)
...
It might be clearer to use if...else instead of replacing the form:
def edit_task(request, post_id):
post = Post.objects.get(id=post_id)
if request.method == 'POST':
print(request.POST)
# instantiate form for POST requests
form = TaskForm(request.POST, instance=post)
...
else:
# instantiate the form for GET requests
form = TaskForm(instance=post)
context = {'form': form}
return render(request, 'List/add_task.html', context)
you can populate this form with data, providing initial
def edit_task(request, post_id):
post = Post.objects.get(id=post_id)
form = TaskForm(request.POST if request.POST else None, instance=post, initial={
'initial_field_name_1': 'initial_field_value_1',
...
'initial_field_name_n': 'initial_field_value_n',
})
if request.method == 'POST':
print(request.POST)
if form.is_valid():
form.save()
return redirect('task')
context = {'form': form}
return render(request, 'List/add_task.html', context)

ImageField not accepting value from html file in DJANGO

I am making a custom CMS platform in Django. I want to upload a featured image from user.
Here is my forms.py
class CkEditorForm(ModelForm):
..........
..........
featuredImage = forms.ImageField(required=True)
My models.py
class Post(models.Model):
..........
..........
featuredImage = models.ImageField(upload_to="featured_image/")
My HTML Template
<div class="col-sm-6">
{{myForm.featuredImage}}
</div>
I used one more method in template but it didn't work for me-
<input type="file" name="featuredImage" accept="image/*" required id="id_featuredImage">
Note- Image is successfully uploaded via Django admin panel, But not working when I try to upload via Templates (HTML file)
Also, it was working when I use this method to render my form in html
{{myForm.as_p}}
But I want to render each form's input method as differently.
{{myForm.category}}
{{myForm.tags}}
{{myForm.featuredImage}}
Here is the views.py
def postView(request):
if request.method== "GET":
form = CkEditorForm()
return render(request,"post/post.html",{'myForm':CkEditorForm})
else:
if request.method == 'POST':
form = CkEditorForm(request.POST)
if form.is_valid():
form.save()
return render(request,"post/post.html",{'myForm':CkEditorForm})
else:
messages.error(request, "Error")
return render(request,"post/post.html",{'myForm':CkEditorForm})
I changed my Views.py and it worked for me...
def postView(request):
if request.method== "GET":
form = CkEditorForm()
return render(request,"post/post.html",{'myForm':CkEditorForm})
else:
if request.method == 'POST':
form = CkEditorForm(request.POST,request.FILES)
if form.is_valid():
form.save()
return render(request,"post/post.html",{'myForm':CkEditorForm})
else:
messages.error(request, "Error")
return render(request,"post/post.html",{'myForm':CkEditorForm})
I just change this. Add request.FILES to get image data.
form = CkEditorForm(request.POST,request.FILES)

Django edit Form doesn't save

I'm a Django beginner and i have a little problem. I made a form for create the model FantaSquadra, and this works. Then I made a form to edit the model and when I press the submit button it doesn't do anything.
Can someone help me?
urls.py:
path('add/fantasquadra/', views.addFantaSquadra, name='creazione_fanta'),
path('edit/fantasquadra/<int:fantasquadra_id>/', views.editFantaSquadra, name='edit_fanta'),
views.py:
def addFantaSquadra(request):
elenco_fantasquadre = FantaSquadra.objects.all()
if request.method == "POST":
form = NewFantaSquadraForm(request.POST)
if form.is_valid():
fanta_item=form.save(commit=False)
fanta_item.save()
else:
form = NewFantaSquadraForm()
return render(request, 'sondaggio/fantasquadre.html', {'form': form})
def editFantaSquadra(request, fantasquadra_id):
item = get_object_or_404(FantaSquadra, pk=fantasquadra_id)
form = NewFantaSquadraForm(request.POST or None, instance=item)
elenco_fantasquadre = FantaSquadra.objects.all()
if form.is_valid():
form.save()
return render(request, 'sondaggio/fantasquadre.html', {'form': form})
forms.py:
class NewFantaSquadraForm(forms.ModelForm):
class Meta:
model = FantaSquadra
fields = ['nome_fantasquadra','proprietario']
fantasquadre.html
<html>
<h1>Scrivi il nome della tua fantasquadra</h1>
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
</html>
You have a link inside your button, for some reason. The link is taking priority over the button submission, so the data is never actually posted to the view.
Remove that <a> element.

Django Forms vs Templates

Sorry the inconvenient, but I am extremely newbie on Django. I imagined that Django would create the forms for me if I use forms.py, I would not need to create an input tag on template, so I created a test template only, since I created the forms.py. However, running my code I was told that my view didn't return an HttpResponse object, and I suspect it was due to my template having only text on it. Could you help me creating a template to have my forms working ? We can use the example posted above. I will paste it bellow:
def create_post(request):
if request.method == 'POST':
form = CreatePostForm(request.POST)
if form.is_valid():
my_model = form.save()
return redirect('/posts/')
else:
form = CreatePostForm()
c = {'form' : form}
return render(request,'create_post.html',c)
You should return render() instead of HttpResponse:
from django.shortcuts import render
def create_a_my_model(request):
...
return render(request, 'template.html', c)
template.html can be very primitive:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button>Save</button>
</form>
Also note that the good practice is to redirect to some page after the post request. This will prevent the double submit. So the whole code of your view will be:
from django.shortcuts import redirect, render
def create_a_my_model(request):
if request.method == 'POST':
form = MyModelForm(request.POST)
if form.is_valid():
my_model = form.save()
return redirect(my_model) # if the model has `get_absolute_url()`
else:
form = MyModelForm()
return render(request, 'template.html', {'form': form})
If you model doesn't have the get_absolute_url() method the you can redirect to any other url: return redirect('/success/page/')

displaying django form validation errors for ModelForms

I often find myself using a ModelForm in views to display and translate views. I have no trouble displaying the form in the template. My problem is that when I am working with these, the forms often don't validate with the is_valid method. The problem is that I don't know what is causing the validation error.
Here is a basic example in views:
def submitrawtext(request):
if request.method == "POST":
form = SubmittedTextFileForm()
if form.is_valid():
form.save()
return render(request, 'upload_comlete.html')
return render(request, 'failed.html')
else:
form = SubmiittedTextFileForm()
return render(request, 'inputtest.html', {'form': form})
I know that the form is not validating because I am redirected to the failed.html template, but I never know why .is_valid is false. How can I set this up to show me the form validation errors?
Couple of things:
You are not taking the POST being sent to the POST.
To see the error message, you need to render back to the same template.
Try this:
def submitrawtext(request):
if request.method == "POST":
form = SubmittedTextFileForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'upload_comlete.html')
else:
print form.errors #To see the form errors in the console.
else:
form = SubmittedTextFileForm()
# If form is not valid, this would re-render inputtest.html with the errors in the form.
return render(request, 'inputtest.html', {'form': form})
I faced the same annoying problem and solved it by returning the form.errors.values() back with HttpResponse. Here is the code:
#csrf_exempt
def post(request):
form = UserForm(request.POST)
if form.is_valid():
return HttpResponse('All Good!')
else:
return HttpResponse(form.errors.values()) # Validation failed
In my case it returned:
<ul class="errorlist"><li>This field is required.</li></ul>
<ul class="errorlist"><li>This field is required.</li></ul>
<ul class="errorlist"><li>This field is required.</li></ul>
<ul class="errorlist"><li>This field is required.</li></ul>
It doesn't provide much information, but it is enough to give you an idea.

Categories

Resources