Django page not saving data correctly - python

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"/>

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);

changing form to search box

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.

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 form not rendering properly

I am following the documentation of the Django Forms but I do not know why my form does not want to show up !
I am creating a form that will get an email en create invitation for user to sign in using this app :https://github.com/bee-keeper/django-invitations
My forms.py:
class InviteForm(forms.Form):
email1 = forms.EmailField(label='Email 1')
My Views.py:
from django.shortcuts import render
from django.views.generic import TemplateView
from .forms import InviteForm
class candidateIndex(TemplateView):
template_name= 'candidateIndex.html'
class HRIndex(TemplateView):
template_name= 'HRindex.html'
def create_invite(request):
if request.method == 'POST':
form = InviteForm(request.POST)
if form.is_valid:
email = form.cleaned_data['email1']
invite = Invitation.create('form.email1')
invite.send_invitation(request)
print("The mail was went")
else:
print("Your form is not valid")
else:
form = InviteForm()
return render(request, 'HRindex.html', {'form': form})
My HTML:
{% extends 'base.html' %}
{% block body %}
<div class="jumbotron">
<h1>Welcome to SoftScores.com</h1>
<h2>Team analytics platfom</h2>
<h3>Welcome to {{user.username}}, it is your Page</h3>
</div>
<div class="container">
<p>
<a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
Create a new team
</a>
</p>
<div class="collapse" id="collapseExample">
<div class="card card-body">
In order to create a new team please invite new members. A link will be sent to them in order to give the access to the application
</div>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
</div>
</div>
urls.py:
from django.conf.urls import url
from website import views
app_name = 'website'
urlpatterns = [
url(r'^candidateIndex/$', views.candidateIndex.as_view(), name='candidate_index'),
url(r'^HRIndex/$', views.HRIndex.as_view(), name='HR_index'),
]
When it render the page I get only the button but the form does not seems to work
Do you habe any idea ?
You HR_index url is being handled by the HRIndex view, but this does not have any code to handle the form.
url(r'^HRIndex/$', views.HRIndex.as_view(), name='HR_index'),
Since a TemplateView is not really suited to handling a form, it would be better to modify the URL pattern to use the create_invite view instead:
url(r'^HRIndex/$', views.create_invite, name='HR_index'),

how create a login and registration page for a website using django framework?

I am new to Django. i am unable to store the user input values into the postgres DB. I have created a tables using Models.py file and create a user interface using template file .How can i pass the vaues to the database using view.py file . someone help me plsz
For simple log-in
in users/views.py
from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, logout,login
from django.http import HttpResponse, HttpResponseRedirect
def user_login(request):
if request.method == "POST":
phone = request.POST.get('phone')
password = request.POST.get('password')
user = authenticate(username=phone, password=password)
if user:
login(request,user)
return HttpResponseRedirect('/users/home')
else:
error = " Sorry! Phone Number and Password didn't match, Please try again ! "
return render(request, 'login/index.html',{'error':error})
else:
return render(request, 'login/index.html')
and in template login/index.html
<html>
<body>
{% if error %}
{{ error }}
{% endif %}
<form method="post" action="/users/login/">{% csrf_token %}
<input type=text placeholder="PhoneNo" name="phone">
<input type=password placeholder="Password" name="password">
<input type="submit" value="login">
</body>
</html>
for registration
login/signup.html
<html>
<body>
<form method=post action="users/signup/">{% csrf_token %}
<input type="text" name="phone" placeholde="Phone No">
<input type="text" name="email" placeholde="Email">
<input type="text" name="password1" placeholde="Password">
<input type="text" name="password2" placeholde="Password Again">
<input type="submit" value="signup">
</form>
</body>
</html>
in users/views.py
def users_signup(request):
if request.method == 'POST':
email = request.POST.get('email')
phone = request.POST.get('phone')
pass_1 = request.POST.get('password1')
pass_2 = request.POST.get('password2')
if pass_1 == pass_2:
user = User.objects.create_user(
username=phone,
email=email,
password=pass_1,
)
return HttpResponseRedirect("/")
else:
error = " Password Mismatch "
return render(request, 'login/signup.html',{"error":error})
else:
return render(request, 'login/signup.html')
main urls.py in main project folder where there is settings.py file would be
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^users/', include('users.urls')),
]
also url.py of app say "users"
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^login/', "users.views.user_login", name='login_url'),
url(r'^signup/', "users.views.user_signup", name='signup_url'),
)
Assuming your UI is based on a form, all you need to do in view.py is to handle a POST request which is sent from client when this form is submitted. So you define a method (say signup) which would get passed a request and possibly other parameters if needed. In it you do necessary validation (i.e. check if this user already exists) and return either new page with error messages via render() or a redirect to the next page if all is good.
More details in official tutorial which is quite good as correctly pointed out by #anuragal

Categories