I'm at the end of my rope trying to figure out why a simple form redirect is not working. I'm submitting a form with one text field via POST request that gets combined with some data from a function in the same views.py file, which is then saved to the model on the database. For some reason, with the redirect schemes that I've set up on submission of the form, I get either a second copy of the form.
feedbackapp/views.py
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.urls import reverse
from .forms import FeedbackForm
from .models import Feedback
def record_feedback(request):
if request.method == 'POST':
form = FeedbackForm(request.POST)
if form.is_valid():
feedback = Feedback()
feedback.submitter_ip = get_client_ip(request)
feedback.feedback_text = form.cleaned_data['feedback']
feedback.save()
return HttpResponseRedirect(reverse('feedbackapp:thanks'))
elif request.method == 'GET':
form = FeedbackForm()
return render(request, 'feedbackapp/feedback_form.html', {'form': form})
def thanks(request):
return render(template_name='feedbackapp/thanks.html',request=request)
# https://stackoverflow.com/questions/4581789/how-do-i-get-user-ip-address-in-django
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[-1] # needs to be the last element in array for Heroku
else:
ip = request.META.get('REMOTE_ADDR')
return ip
feedbackapp/forms.py
from django import forms
class FeedbackForm(forms.Form):
feedback = forms.CharField(label='Feedback', max_length=5000)
feedbackapp/templates/feedbackapp/feedback_form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Anonymous Feedback</title>
</head>
<body>
<form action="/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit"/>
</form>
<p><i>Note: IP addresses are collected with each submission.</i></p>
</body>
</html>
feedbackapp/templates/feedbackapp/thanks.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Thanks!</title>
</head>
<body>
<p>Thanks for your feedback.</p>
</body>
</html>
feedbackapp/urls.py
from django.conf.urls import url
from .views import record_feedback, thanks
urlpatterns = [
url('', record_feedback, name='feedback'),
url('thanks/', thanks, name='thanks'),
]
anonfeed/urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include('feedbackapp.urls'), namespace='feedbackapp'),
]
It is almost as if the thanks view is not associating with the url and the template.
Your empty regex overrides the one for thanks. Change the following line:
url('', record_feedback, name='feedback'),
to
url('^$', record_feedback, name='feedback'),
Related
I am new in Django. I want to write a very simple code to create a string in views.py and shows in an html file in templates.:
views.py
from django.shortcuts import render
from django.http import JsonResponse
def index(request):
F = 100
response = str(F + 10)
response1 = {"Main": response}
template_name = "homepage.html"
return render(request, template_name, response1)
urls.py
urlpatterns = [
path('', views.index, name='homepage.html'),
path('admin/', admin.site.urls)]
homepage.html
<html>
<head>
<h1>User Information</h1>
</head>
<h2>Answer: {{response1}}</h2>
</html>
What I get on webpage is the headers without {{response1}}
<html>
<head>
<h1>User Information</h1>
</head>
<h2>Answer: {{Main}}</h2>
</html>
Use this
I'm trying to make to make a django web app which has a form that asks a user to input a phone number and stores that number in a postgres database. The following code is giving me the error:
NoReverseMatch at /main/insert_num/
Reverse for '' not found. '' is not a valid view function or pattern name.
And I can't figure out what the issue is, can someone help?
index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Form 1</title>
</head>
<body>
<form action="{% url 'insert_my_num' %}" method="post" autocomplete="off">
{% csrf_token %}
<!-- {{ form.as_p }} -->
<input type="submit" value="Send message">
</form>
</body>
</html>
forms.py
from django import forms
from phone_field import PhoneField
from main.models import Post
class HomeForm(forms.ModelForm):
phone = PhoneField()
class Meta:
model = Post
fields = ('phone',)
models.py
from django.db import models
from phone_field import PhoneField
class Post(models.Model):
phone = PhoneField()
main/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('insert_num/', views.insert_my_num,name='insert_my_num')
]
project/urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('main/',include('main.urls'))
]
views.py
def insert_my_num(request: HttpRequest):
phone = Post(request.POST.get('phone'))
phone.save()
return redirect('')
Your views.py is a little off - you aren't rendering your form anywhere. I drafted up a quick app (which I think does what you're looking for) - let me know if this works:
main/templates/index.html
Here, I just set the form's action to "" (that's all you need here) and uncommented the form.as_p line
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Form 1</title>
</head>
<body>
<form action="" method="post" autocomplete="off">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Send message">
</form>
</body>
</html>
main/views.py
Note the differences here, we are testing the request type and taking appropriate action based on what kind of request is coming in. If it's a POST request we process the form data and save to the database. If not, we need to display a blank form for the user to complete.
from django.shortcuts import render, redirect
from .forms import HomeForm
def insert_my_num(request):
# Check if this is a POST request
if request.method == 'POST':
# Create an instance of HomeForm and populate with the request data
form = HomeForm(request.POST)
# Check if it is valid
if form.is_valid():
# Process the form data - here we're just saving to the database
form.save()
# Redirect back to the same view (normally you'd redirect to a success page or something)
return redirect('insert_my_num')
# If this isn't a POST request, create a blank form
else:
form = HomeForm()
# Render the form
return render(request, 'index.html', {'form': form})
Let me know if that works!
The form action is not redirecting from home.html to password.html in Django 2 even I recheck everything including URL pattern
Below I am sharing the basic code. My apologies if it's a basic question as I am very new to Django that's why I may not able to detect the issue.
urls.py code
from django.urls import path
from generator import views
urlpatterns = [
path('', views.home),
path('password/', views.password),
]
views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return render(request, 'generator/home.html')
def password(request):
return render(request, 'generator/password.html')
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<h1>Password Generator</h1>
<form action="password" method="get">
<select name="length">
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<input type="button" value="Generate Password">
</form>
</body>
</html>
password.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Password</title>
</head>
<body>
<h1>Password page</h1>
</body>
</html>
Error Log
File Structure
First of all give names in urls.py so you can access it by name.
urlpatterns = [
path('', views.home,name="index"),
path('password/', views.password,name="password"),
]
in home.html remove form's action
in views.py
from django.urls import reverse
def home(request):
if request.method == 'POST':
#you can access input items of form by `request.POST.get('attribute_name')`
# your logic
return redirect(reverse('password')
else:
return render(request, 'generator/home.html')
if still not getting error then please share whole code and what you want to achieve
A little description of what i m trying to do.
I want to make a User Interface (web/HTML) through which i can send the commands to router and display the result on the Webpage/HTML.
Here's the code i m using:-
Views.py
from django.shortcuts import render
from first_app.forms import CmdForm
from django.http import HttpResponse
def index(request):
my_dict = {'insert_me': ""}
return render(request,'first_app/index.html',context=my_dict)
def form_name_view(request):
if request.method == "POST":
form = CmdForm(request.POST)
if form.is_valid():
from netmiko import ConnectHandler
devices = {
'device_type':'cisco_ios',
'ip':'192.168.50.145',
'username':'me',
'password':'12345',
'secret':'12345',
'port':'22'
}
cmd = request.POST.get('command', '')
netconnect = ConnectHandler(**devices)
#print("connection established with", devices['ip'])
output = netconnect.send_command(cmd)
return render(request,'first_app/forms.html', {'form': form,
'output':output})
else:
form = CmdForm()
return render(request,'first_app/forms.html', {'form': form})
forms.py
from django import forms
class CmdForm(forms.Form):
command = forms.CharField(label='Command to execute')
urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
from first_app import views
urlpatterns = [
path('Automation_page/', views.form_name_view,name='IP form'),
path('admin/', admin.site.urls),
path('', views.index,name='first'),
path('first_app/',include('first_app.urls')),
]
forms.html
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>FORMS</title>
</head>
<body>
<h1> IP address form </h1>
<p>Run command:</p>
<form method="POST"> {% csrf_token %}
{{ form }}
<input type="submit" value="Run command!" />
</form><br>
{% if request.POST %}
<p>Command output:</p>
<pre>{{ output }}</pre>
{% endif %}
</body>
</html>
i am getting the error when i visit the Automation_page/
ValueError at /Automation_page/
The view first_app.views.form_name_view didn't return an HttpResponse object. It returned None instead.
Request Method: GET
Request URL: http://127.0.0.1:8000/Automation_page/
Django Version: 2.2.3
Exception Type: ValueError
Exception Value:
The view first_app.views.form_name_view didn't return an HttpResponse object. It returned None instead.
Exception Location: K:\Work\DevNet\ENV1\lib\site-packages\django\core\handlers\base.py in _get_response, line 126
Python Executable: K:\Work\DevNet\ENV1\Scripts\python.exe
Python Version: 3.7.3
Python Path:
['K:\Work\DevNet\first_project',
'K:\Work\DevNet\ENV1\Scripts\python37.zip',
'K:\Work\DevNet\ENV1\DLLs',
'K:\Work\DevNet\ENV1\lib',
'K:\Work\DevNet\ENV1\Scripts',
'c:\users\karti\appdata\local\programs\python\python37-32\Lib',
'c:\users\karti\appdata\local\programs\python\python37-32\DLLs',
'K:\Work\DevNet\ENV1',
'K:\Work\DevNet\ENV1\lib\site-packages']
Need help on this.
thanku who are willing to help
The last line needs to be moved one indent to the left, so it is hit if the form is invalid.
else:
form = CmdForm()
return render(request,'first_app/forms.html', {'form': form})
I was able to figure out the solution of my problem.
sharing it for others if they can relate. :-)
In views.py
Add the following code, with indent to first if statement.
else:
return render(request,'first_app/forms.html', {})
I am learning Django and am trying to create a form that I can submit a participant's information to the database.
I have an index view, which list all the participants:
http://127.0.0.1:8000/participants/
Clicking a button on the index will go to form submission:
http://127.0.0.1:8000/participants/add_participant/
After submitting the form, the page goes back to the index view, but the URL is not correct, it stucks at http://127.0.0.1:8000/participants/add_participant/
If I refresh the browser immediately, it will add another record to the database.
add_participant.html
<!DOCTYPE html>
<html>
<head>
<title>This is the title</title>
</head>
<body>
<h1>Add a Participant</h1>
<form id="participant_form" method="post" action="/participants/add_participant/">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit" value="Create Participant" />
</form>
</body>
</html>
views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseRedirect
from participants.models import Participant
from .forms import ParticipantForm
# Create your views here.
def index(request):
participant_list = Participant.objects.order_by('-first_name')[:50]
context = {'participants': participant_list}
return render(request, 'participants/index.html', context)
def add_participant(request):
if request.method == 'POST':
form = ParticipantForm(request.POST)
if form.is_valid():
form.save(commit=True)
return index(request)
else:
form = ParticipantForm()
return render(request, 'participants/add_participant.html', {'form': form})
urls.py
from django.conf.urls import url
from . import views
from .models import Participant
app_name = 'participants'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'add_participant/$', views.add_participant, name='add_participant'),
]
I tried switching the
return index(request)
to:
return HttpResponseRedirect("http://127.0.0.1:8000/participants/")
It solves the problem...but I doubt this is the "right" way to do it. What is the correct way to fix this issue?
You can pass just the path to the redirect response:
return HttpResponseRedirect("/participants/")
This way if you change your domain, the redirect will work.
an other solution is to use reverse
from django.core.urlresolvers import reverse
# ...
return HttpResponseRedirect(reverse(index))