I have a Django Project I am currently working on where I want to be able to add a product to a database. I have a few fields where the user enters the details of the product and this is then sent to the create function and should save it to the Database. Unfortunately this isnt happening. This is my first use of Django so I'm not sure whats going wrong here. Here is the code I have so far:
My Index.html page:
<!DOCTYPE html>
<html>
<body>
<h2>Create product here</h2>
<div>
<form id="new_user_form" method="post">
{% 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>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type = "text/text/javascript">
$(document).on('submit', '#new_user_form', function(e)){
e.preventDefault()
$.ajax({
type: 'POST',
url:'/user/create',
data:{
name:$('#name').val(),
description:$('#description').val(),
price:$('#price').val(),
}
success.function(){
console.log('created')
}
})
}
</script>
</html>
Here is my urls.py code:
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_product, name='create_user')
]
My views.py code:
from django.shortcuts import render
from testapp.models import User
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
def index(request):
return render(request, 'index.html')
#csrf_exempt
def create_product(request):
if request.method == 'POST':
name = request.POST['name']
description = request.POST['description']
price = request.POST['price']
User.objects.create(
name = name,
description = description,
price = price
)
return HttpResponse('')
And the models.py code:
from django.db import models
# Create your models here.
class User(models.Model):
name = models.CharField(max_length = 32)
desscription = models.TextField()
price = models.CharField(max_length = 128)
The problem with this is the POST request is sent when run, but the data is not saved to the database and I can't figure out why. I have followed a couple tutorials and documentation to get to this stage but can't work out what it is that's not working correctly here. Can someone have a look and let me know please?
Related
I am trying to implement form in django, where I will take input from user, e.g, its table name and then I want to show all the content on the webpage. So, far I tried below code.
views.py
from django.shortcuts import render
# Create your views here.
from django.shortcuts import HttpResponse
from .models import my_custom_sql
from django.core.exceptions import *
def index(request):
return render(request, 'forms_spy/form.html')
def search(request):
if request.method == 'POST':
search_id = request.POST.get('textfield', None)
try:
webpages_list = my_custom_sql.objects.get(name = search_id)
data_list = {'access_record':webpages_list}
return render(request,'forms_spy/index.html', context=data_list)
except my_custom_sql.DoesNotExist:
return HttpResponse("no such user")
else:
return render(request, 'forms_spy/form.html')
forms_spy/models.py
from django.db import models
# Create your models here.
def my_custom_sql(TABLE):
with connections["my_oracle"].cursor() as cursor:
cursor.execute("SELECT * FROM {};".format(TABLE))
row = cursor.fetchall()
return row
templates/forms_spy/form.html
<form method="POST" action="/search">
{% csrf_token %}
<input type="text" name="textfield">
<button type="submit">Upload text</button>
</form>
urls.py under project folder:
from django.contrib import admin
from django.urls import path
from django.conf.urls import url,include
from forms_spy.views import *
urlpatterns = [
# url(r'^$', views.index, name='index'),
#url(r'^', include('livefleet.urls', namespace='livefleet')),
path('admin/', admin.site.urls),
url(r'^search/', search),
url(r'^index/', index),
]
I referred to this link. When I entered the value getting below error.
RuntimeError at /search
You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/search/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.
change in urls.py
from
url(r'^search/', search),
to
url(r'^search/', search, name='search'),
<form method="POST" action="{% url 'search' %}">
{% csrf_token %}
<input type="text" name="textfield">
<button type="submit">Upload text</button>
</form>
ur url is search/ , so u need to put the same in the form action
change urls to
path('search/', search)
slash character for dynamic route, example call in browser (http://domain/search) or (http://domain/search/) if you using both it's work.
templates
<form method="POST" action="/search/">
{% csrf_token %}
<input type="text" name="textfield">
<button type="submit">Upload text</button>
</form>
On the main page I have a text box. When I type text into it, after clicking the button I want to display that text below.
With ajax I get the text entered and pass it to views.py.
When rendering, the result I need is displayed on /localhost:8000/vk_u/
How do I display the result on the current page (localhost: 8000/)?
Thanks
//forms.py
from django import forms
from .models import *
class VK_LINK_Form(forms.Form):
enter_link = forms.CharField(widget = forms.TextInput(attrs={'id':'link_vk_enter'}))
//urls.py
from django.urls import path, include
from . import views
from django.http import HttpResponse
urlpatterns = [
path('', views.index, name = 'index'),
path('vk_u/', views.vk_u, name = 'vk_u'),
]
//js
$(document).on('submit','#vkht_form', function(e){
e.preventDefault();
var link_post_input = $(document.getElementById("link_vk_enter")).val()
$.ajax({
type: 'POST',
url: '/vk_u/',
data:{
link_post_input: link_post_input,
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
});
});
]
//views.py
def vk_u(request):
link_post_input = request.POST.get('link_post_input')
return render(request, "mainApp/homePage.html", {"link_post_input": link_post_input,})
<!-- html -->
<body>
<div>
<form action="" method="GET" id="vkht_form">
{% csrf_token %}
{{ form }}
text: {{ text_post_input }}
<input type="submit" value="CLICK">
</form>
</div>
</body>
I'm newbie and trying to do something pretty basic after reading the Django Doc Project Documentation, but can't seem to figure it out. I'm getting a user's name with a POST and trying to GET it and display it on the same page. I'm getting an error: hello() missing 1 required positional argument: 'greeting_id'
I'm using Django 2 and wondering if it could be something with the routing? I'm not exactly sure as I'm very new to MVC and Django.
Any help in the right direction would be greatly appreciated.
Here's my code so far:
Views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Greeting
# create hello view
def hello(request, greeting_id):
if request.method == 'POST':
if request.POST['firstname']:
greeting = models.Greeting()
greeting.firstname = request.POST['firstname']
greeting.save()
obj = models.Greeting.objects.get(pk=greeting_id)
context = {
'object': obj
}
return render(request, 'greetings/home.html', context)
return render(request, 'greetings/home.html')
Models.py
from django.db import models
# Create your models here.
class Greeting(models.Model):
firstname = models.CharField(max_length=100)
# returns post object in admin interface
def __str__(self):
return self.firstname
urls.py
from django.contrib import admin
from django.urls import path
from greetings import views #import greetings views into the url file
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', views.hello, name='hello'),
]
home.html
{% block content %}
<h2>Let's Say Hello!</h2>
<br/>
<br/>
<div>
<form method="POST" action="{% url 'hello' %}">
{% csrf_token %}
Enter your first name:
<br />
<input type="text" name="firstname" />
<br />
<br />
<input type="submit">
</form>
{{ object.firstname }}
</div>
{% endblock %}
Your view "hello" requires an parameter "greeting_id"
def hello(request, greeting_id):
These parameters are passed from the url routing to the view, for the view to work your url would have to look like this
path('hello/<int:greeting_id>/', views.hello, name='hello'),
Where is greeting_id supposed to be coming from?
Hello i can't make my form work. The button is displayed but the charfield never shows up. I tried to use a if statement with the "sent" parameter and it worked. I just followed the django doc. I did not find a solution in other posts.
Here is my forms.py:
from django import forms
class CharacterForm(forms.Form):
character_name = forms.CharField(label='Search', max_length=30)
views.py:
from django.shortcuts import render
from .forms import CharacterForm
def index(request):
return render(request, 'perso/pages/index.html')
def get_character(request):
character_name = ''
sent = False
if request.method == 'POST':
form = CharacterForm(request.POST)
if form.is_valid():
character_name = form.cleaned_data['character_name']
sent = True
else:
form = CharacterForm()
return render(request, 'perso/pages/index.html', {
'form': form,
'character_name': character_name,
'sent': sent
})
Perso is the name of the app, Urls.py in perso:
from django.conf.urls import url
from . import views
app_name = 'perso'
urlpatterns = [
url(r'^$', views.index, name="index"),
]
My form in template index of perso:
<form action="{% url "perso:index" %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
Here is what appears in the browser:
<form action="/perso/" method="post">
<input type='hidden' name='csrfmiddlewaretoken' value='IWmBEknyibHw4LpvjnyfLWKcUOXLbw27RdHgR7GjhTDelCLGZ51QeF3y9wRyC0Mg' />
<input type="submit" value="Submit" />
</form>
The charfield is missing. No error in the console.
You have some anomaly in your code you missed out the template name argument in your render function. Provide the template name of your corresponding HTML file in the render function. You also missed providing default arguments of character_name and sent variable. See docs here
from django.shortcuts import render
from .forms import CharacterForm
def get_character(request):
character_name = ''
sent = False
if request.method == 'POST':
form = CharacterForm(request.POST)
if form.is_valid():
character_name = form.cleaned_data['character_name']
sent = True
else:
form = CharacterForm()
return render(request, 'template_name.html', {
'form': form,
'character_name': character_name,
'sent': sent
})
You have made mistake to not make urls.py pattern for the function in views.py that is setting the form in the template
from django.conf.urls import url
from . import views
app_name = 'perso'
urlpatterns = [
url(r'^$', views.index, name="index"),
url(r'^character$', views.get_character, name="character"),
]
Also you need correction in your template in your post request URL link
<form action="{% url "perso:character" %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
Now your form will be avaliable at http://localhost:8000/character
I am trying to configure HTML formto work with Django Models rather than using built-in Forms in the framework. I have made the form using Html below and have pasted the code for Model, View and Urls.py. The problem is when I click the submit button, it doesn't perform any action. I am able to view the form but it doesn't serves the purpose. I know the question is very lame, but how would configure the HTML to work with the django model so that the data can be saved to the database?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body style="font-family:Courier New">
<h1>Add / Edit Book</h1>
<hr/>
<form id="formHook" action="/istreetapp/addbook" method="post">
<p style="font-family:Courier New">Name <input type="text" placeholder="Name of the book"></input></p>
<p style="font-family:Courier New">Author <input type="text" placeholder="Author of the book"></input></p>
<p style="font-family:Courier New"> Status
<select>
<option value="Read">Read</option>
<option value="Unread">Unread</option>
</select>
</p>
<input type="submit" id="booksubmit" value="Submit"></input>
</form>
</body>
</html>
View
from django.shortcuts import HttpResponse
from istreetapp.models import bookInfo
from django.template import Context, loader
from django.shortcuts import render_to_response
def index(request):
booklist = bookInfo.objects.all().order_by('Author')[:10]
temp = loader.get_template('app/index.html')
contxt = Context({
'booklist' : booklist,
})
return HttpResponse(temp.render(contxt))
Model
from django.db import models
class bookInfo(models.Model):
Name = models.CharField(max_length=100)
Author = models.CharField(max_length=100)
Status = models.IntegerField(default=0) # status is 1 if book has been read
def addbook(request, Name, Author):
book = bookInfo(Name = Name, Author=Author)
book.save
return render(request, 'templates/index.html', {'Name': Name, 'Author': Author})
Urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('app.views',
url(r'^$', 'index'),
url(r'^addbook/$', 'addbook'),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
You forgot to define name in each of your input
<form id="formHook" action="/addbook/" method="post">
{% csrf_token %}
<p style="font-family:Courier New">
Name <input type="text" name="name" placeholder="Name of the book"></input>
</p>
<p style="font-family:Courier New">
Author <input type="text" name="author" placeholder="Author of the book"></input>
</p>
<p style="font-family:Courier New">
Status
<select name="status">
<option value="Read">Read</option>
<option value="Unread">Unread</option>
</select>
</p>
<input type="submit" id="booksubmit" value="Submit"></input>
</form>
Your addbook must be in the views.py not in your models.py.
You don't have to define templates/index.html in your render, it is understood in your settings
def addbook(request):
if request.method == 'POST':
name = request.POST['name']
author = request.POST['author']
bookInfo.objects.create(Name = name, Author=author)
return render(request, 'index.html', {'Name': name, 'Author': author})
main urlconf
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'project_name.views.index'),
url(r'^addbook/$', 'project_name.views.addbook'),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
You need to add name attributes to your html form then process the form submission in the view. Something like -
from django.http import HttpResponseRedirect
from django.shortcuts import render
def book_view(request):
if request.method == 'POST':
name = request.POST['name']
author = request.POST['author']
book = BookInfo(name=name, author=author)
if book.is_valid():
book.save()
return HttpResponseRedirect('your_redirect_url')
else:
return render(request, 'your_form_page.html')
Have a look at the docs on the request.POST dictionary.
However you really would be better off doing this with a django ModelForm -
class BookForm(ModelForm):
class Meta:
model = BookInfo # I know you've called it bookInfo, but it should be BookInfo
then in your view -
from django.http import HttpResponseRedirect
from django.shortcuts import render
def book_view(request, pk=None):
if pk:
book = get_object_or_404(BookInfo, pk=pk)
else:
book = BookInfo()
if request.method == 'POST':
form = BookForm(request.POST, instance=book)
if form.is_valid():
book = form.save()
return HttpResponseRedirect('thanks_page')
else:
form = BookForm(instance=book)
return render(request, 'your_form_page.html', {'form': form)
And your_form_page.html can be as simple as -
<form action="{% url book_view %}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
Have a look at the docs on working with forms.