changing form to search box - python

Here is my code for form where a user insert stock symbol and the result of the input is shown in the new page.
What I did so far:
in models.py
from django.db import models
from django.contrib import auth
class Child(models.Model):
name = models.CharField(max_length=150, blank=True)
in forms.py
from django import forms
from .models import Child
class ChildlForm(forms.ModelForm):
class Meta:
model = Child
fields = ('name',)
In views.py
from django.shortcuts import render
from .forms import ChildForm
from pandas_datareader import data as wb
from yahoofinancials import YahooFinancials
# Create your views here.
def home(request):
form = ChildForm()
if request.method == "POST":
form = ChildForm(request.POST)
if form.is_valid():
data = form.save(commit=True)
name = data.name
symbols = [name]
yahoo_financials = YahooFinancials(symbols)
new_data = pd.DataFrame()
for s in symbols :
new_data[s] = wb.DataReader(s, data_source ='yahoo', start = '2014-1-1')['Adj Close']
a = new_data[s]
b = a[-1]
context={
'name':name,
'b':b,}
else:
form = ChildForm()
return render(request,'main/index.html',{'form':form})
return render(request,'main/index2.html',context)
return render(request,'main/index.html',{'form':form})
the index.html file
<form method="POST">
{{ form }}
{% csrf_token %}
<input class="form-control mr-sm-2" type="text">
<button type="submit">OK</button>
</form>
I realised that the form method has limitation and puts name in front of input box which looks ugly.
I tried to build serach box in index2.html file with search box but it does not work:
<nav class="navbar navbar-default">
<div class="container-fluid">
<form id="searchbox" method="get" autocomplete="off" class="navbar-form navbar-left" role="search">
<input name='q' type="text" type="text" class="form-control" placeholder="Search" />
<button id="button-submit" type="submit" value=" " class="btn btn-default" />
</form>
</div>
</nav>
I am confused how i should connect the form with the search box and should i even connect. What should i in this case do so the data from search box is converted to index and used in the next page. I also want in the next page to keep search box so a user do not have to return to the previous page to look for new symbols.
Would appreciate any help an advise.

Related

Django create user command issue while trying to add a new user through a html form

I have successfully created a table in the database and can add data from the admin panel onto the table but when i used the form displayed on a url by clicking submit a new user is not created.
views.py:
from django.shortcuts import render, redirect
from formRegister.models import FormRegister
# Create your views here.
def register(request):
if request.method == 'post':
first_name = request.POST['fisrt_name']
last_name = request.POST['last_name']
username = request.POST['username']
user = FormRegister.objects.create_user(username=username, first_name=first_name,
last_name=last_name)
user.save(commit = True);
return redirect('/')
else:
return render (request, 'formRegister.html')
**models.py**
This is the code for the model.py section
from distutils.command.upload import upload
from django.db import models
from .models import FormRegister
# Create your models here.
class FormRegister(models.Model):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
username = models.CharField(max_length=100)
**# admin.py**
Below is the code for the admin.py section
from django.contrib import admin
from .models import FormRegister
# Register your models here.
admin.site.register(FormRegister)
urls.py
This is the urls.py section of the code
from django.urls import path
from formRegister import views
urlpatterns = [
path("register", views.register, name="register"),
]
Below is the form created in a template folder named formRegister.html
# formRegister.html
<form action="register" method="post">
{% csrf_token %}
<input type="text" name="first_name" placeholder="First_Name"> <br>
<input type="text" name="last_name" placeholder="Last_Name"> <br>
<input type="text" name="username" placeholder="Username"> <br>
<input type="Submit" value="Submit"> <br>
</form>
<script src="" async defer></script>
</body>
Change if request.method == 'post': to if request.method == 'POST':
Change <input type="Submit" value="Submit"> to <input type="submit" value="Submit">
Omit user.save(commit = True);

Django page not saving data correctly

I have a form in a HTML page that I'm using for a Django project. This form takes the input from the user and sends it to a page which should save it to the database, but right now its not doing do. Here is the code:
<!DOCTYPE html>
<html>
<body>
<h2>Create product here</h2>
<div>
<form id="new_user_form" method="post" action="user/create"}>
{% csrf_token %}
<div>
<label for="name" > Name:<br></label>
<input type="text" id="name"/>
</div>
<br/>
<div>
<label for="description"> description:<br></label>
<input type="text" id="description"/>
</div>
<div>
<label for="price" > price:<br></label>
<input type="text" id="price"/>
</div>
<div>
<input type="submit" value="submit"/>
</div>
</div>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</html>
My urls.py file:
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from testapp import views
admin.autodiscover()
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index),
path('user/create', views.create_user, name='create_user')
]
The views.py file:
from django.shortcuts import render
from testapp.models import User
from django.http import HttpResponse
def index(request):
return render(request, 'index.html')
def create_user(request):
if request.method == 'POST':
name = request.POST.get('name')
description = request.POST.get('description')
price = request.POST.get('price')
newUser = User(
name = name,
description = description,
price = price
)
newUser.save()
return HttpResponse('')
And the models.py file:
from django.db import models
# Create your models here.
class User(models.Model):
name = models.CharField(max_length = 32, null = True)
description = models.TextField(null = True)
price = models.CharField(max_length = 128, null = True)
Now the problem is when the form data gets sent to the function create_user, it should take the data and create a object with that data and save it to the database. The database is set up correctly as when I use the Django shell to test it, users are created and saved. However, through the form and the python, something is going wrong here and I'm not sure why. Can someone help me out here?
You need to put the name in the inputs html tags
<input type="text" id="name" name="name"/>
<input type="text" id="description" name="description"/>
<input type="text" id="price" name="price"/>

The view users.views.RegisterView didn't return an HttpResponse object. It returned None instead

I am using this code for a register form. But the post request doesn't work and give me an error :
ValueError at /register/
The view users.views.RegisterView didn't return an HttpResponse object. It returned None instead.
views.py
class RegisterView(View):
def get(self,request):
register_form = RegisterForm()
return render(request, 'register.html',{'register_form':register_form})
def post(self,request):
register_form = RegisterForm(request.POST)
if register_form.is_valid():
user_name = request.POST.get("email", "") user_psw = request.POST.get("password", "")
user_profile=UserProfile()
user_profile.username = user_name
user_profile.email = user_name
user_profile.password=make_password(user_psw)
user_profile.save()
send_register_email(user_name,"register")
pass
urls.py
from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView
import xadmin
from users.views import LoginView , RegisterView
import xadmin
urlpatterns = [
path('xadmin/', xadmin.site.urls),
path('',TemplateView.as_view(template_name="index.html"),name="index"),
path('login/',LoginView.as_view(),name="login"),
path('register/',RegisterView.as_view(),name="register"),
path("captcha/", include('captcha.urls'))
]
forms.py
class RegisterForm(forms.Form):
email = forms.EmailField(required=True)
password = forms.CharField(required=True, min_length=5)
captcha = CaptchaField(error_messages={"invalid":"please input correctly"})
register.html
<div class="tab-form">
<form id="email_register_form" method="post" action="{% url 'register' %}" autocomplete="off">
<input type='hidden' name='csrfmiddlewaretoken' value='gTZljXgnpvxn0fKZ1XkWrM1PrCGSjiCZ' />
<div class="form-group marb20 ">
<label>邮 箱</label>
<input type="text" id="id_email" name="email" value="None" placeholder="请输入您的邮箱地址" />
</div>
<div class="form-group marb8 ">
<label>密 码</label>
<input type="password" id="id_password" name="password" value="None" placeholder="请输入6-20位非中文字符密码" />
</div>
<div class="form-group marb8 captcha1 ">
<label>验 证 码</label>
{{ register_form.captcha }}
<img src="/captcha/image/2f3f82e5f7a054bf5caa93b9b0bb6cc308fb7011/" alt="captcha" class="captcha" /> <input id="id_captcha_0" name="captcha_0" type="hidden" value="2f3f82e5f7a054bf5caa93b9b0bb6cc308fb7011" /> <input autocomplete="off" id="id_captcha_1" name="captcha_1" type="text" />
</div>
<div class="error btns" id="jsEmailTips"></div>
<div class="auto-box marb8">
</div>
<input class="btn btn-green" id="jsEmailRegBtn" type="submit" value="注册并登录" />
<input type='hidden' name='csrfmiddlewaretoken' value='5I2SlleZJOMUX9QbwYLUIAOshdrdpRcy' />
{% csrf_token %}
</form>
</div>
request information
Request information
USER
AnonymousUser
GET
No GET data
POST
Variable Value
csrfmiddlewaretoken
'9dQylxY3htVbBMNFunnYwgnarkfjSVioz5rhu0uADk0ShssTFGl9144OEwJoUlPX'
email
'1#1.com'
password
'123456'
captcha_0
'2f3f82e5f7a054bf5caa93b9b0bb6cc308fb7011'
captcha_1
''
FILES
No FILES data
no matter whether the verification code I input is wrong or right, the error is always The view users.views.RegisterView didn't return an HttpResponse object. It returned None instead.
Django's view should return some response.
From doc:
A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image . . . or anything, really.
So you need to add return statement to post() method, e.g. like this:
def post(self,request):
...
return render(request, 'register.html',{'register_form':register_form})

Django Model Form not appearing in admin

I've got a feedback app in django and it all seems to work fine, no errors i can submit the form and it all seems to work, however i have my model registered into my admin however when i submit the form i doesn't appear in my admin. Sorry if this is very basic i just cant get my head around it please help.
in my models.py
class Feedback(models.Model):
email = models.CharField(max_length=100)
message = models.CharField(max_length=1000)
def __unicode__(self):
return self.title
which i then pass through to forms.py
class FeedbackModelForm(forms.ModelForm):
class Meta:
model = Feedback
fields = ["email", "message"]
and my view is
def feedbackform(request):
form = FeedbackModelForm(request.Post or None)
if form.is_valid():
form.save()
return render(request, "feedback.html", {"form": form})
now in my html looks like this
{% block content %}
<div id="feedback">
<div id="feedback-form" style='display:none;' class="col-xs-4 col-md-4 panel panel-default">
<form method="POST" action="{{ form }}" class="form panel-body" role="form">{% csrf_token %}
<div class="form-group">
<input class="form-control" name="email" autofocus placeholder="Your e-mail" type="email" />
</div>
<div class="form-group">
<textarea class="form-control" name="message" required placeholder="Please write your feedback here..." rows="5"></textarea>
</div>
<button class="btn btn-primary pull-right" type="submit">Send</button>
</form>
</div>
<div id="feedback-tab">Feedback</div>
</div>
{% endblock %}
and in my admin
from .models import Feedback
from .forms import FeedbackModelForm
class FeedbackAdmin(admin.ModelAdmin):
form = FeedbackModelForm
admin.site.register(Feedback, FeedbackAdmin)
You have passed the
{{ form }}
as the action attribute, which is completely wrong. Put it inside a div as
{{ form.as_p }}
that will work for you.
And in the action attribute pass a url in the form of
{% url 'home_page_example' %}
if you wanted to remain in the same page and redirect via view
you can write
action = "."
Show us how did you register your model in the admin.
Make sure that you explicit config the form, like this
class FeedbackAdmin(admin.ModelAdmin)
form = FeedbackModelForm
admin.site.register(Feedback, FeedbackAdmin)
You should return email or message in def __unicode__(self):, not title.
class Feedback(models.Model):
email = models.CharField(max_length=100)
message = models.CharField(max_length=1000)
def __unicode__(self):
return self.email
I think that you should check if the view is currently saving your Feedback.
Try inspecting the DB or in a manage.py shell check if len(Feedback.objects.all()) change when you submit a Feedback in your view.
Also, I recommend you to change the email field to an EmailField and use the FormView class based view.

Django Form Submission Failing

I'm working on a little app that allows you to save specific location information about places you've been. The issue I'm having is that clicking the submit button on the 'save new location' page doesn't seem to be doing much of anything. It redirects to .../locationlib/savenew/, which is supposed to be the url that saves the form input as a new model object, but both according to debugging print statements and what actually happens, that function is just never called. I've had success with other forms using django but this one seems to be tripping me up. Can someone give me an idea of what's going on here?
views.py
def new(request):
return render(request, 'locationlib/new.html')
def savenew(request):
print 'savenew called'
name = request.POST['name']
latitude = float(request.POST['latitude'])
longitude = float(request.POST['longitude'])
desc = request.POST['description']
user = User.objects.get(username=str(request.POST['user']))
print 'all variables set'
l = Location(
name=name,
longitude=longitude,
latitude=latitude,
custDescription=desc,
user=user,
)
print 'l defined'
l.save()
print 'l saved'
return HttpResponseRedirect(reverse('locationlib:detail', args=[l.id]))
new.html
<div id='new-location-form'>
<form action="{% url 'locationlib:savenew' %}" method="post">
{% csrf_token %}
Name: <input type='text' name='name' value='Place Name' required><br>
User: <input type='text' name='user' value='User' required><br>
Longitude: <input type='text' name='longitude' value="Longitude Coordinate" required><br>
Latitude: <input type='text' name='latitude' value='Latitude Coordinate' required><br>
Description: <textarea name='description'>Description of Place</textarea><br>
<input type="submit" value="Save">
</form>
</div>
urls.py
urlpatterns = patterns( '',
...
url(r'new/', views.new, name='new'),
url(r'^savenew/', views.savenew, name='savenew'),
)
Your first URL pattern, new, is not anchored to the start of the string. That means that it matches anything that ends with "new" - and that includes "savenew". So your request for "savenew" is being caught by that pattern, and being sent to the new view.
Just put a ^ character at the front, as you have done with the other pattern.
try to use Modelforms
forms.py:
from django.forms import ModelForm
from myapp.models import Location
# Create the form class.
class LocationForm(ModelForm):
class Meta:
model = Location
view.py
def savenew(request):
if request.method == 'POST':
form = LocationForm(request.POST)
if form.is_valid():
new=form.save()
return HttpResponseRedirect(reverse(reverse('locationlib:detail', args=[new.id])))
return render(request,'reservetion/sign.html',{'form': form})
else:
form = SignForm()
return render(request, 'reservetion/sign.html',{'form': form})
new.html
<form action="{% url 'locationlib:savenew' %}" method="post">
{% csrf_token %}
{{ form}}
</form>

Categories