django : unable to call a python function by clicking submit button - python

Trying to call Installation function when we click a submit button on HTML Page and taking the data from HTML only,i am new to django.
Help me out..!
Views File:
from .forms import Details
from django import forms
from django.shortcuts import render
from django.http import HttpResponseRedirect
from . import installation
def output(request):
if request.method == 'POST':
details=Details(request.POST)
if details.is_valid():
Obj=details.cleaned_data
path=Obj['Path']
device_type=Obj['Device']
image_version=Obj['Version']
return installation()
else:
raise TypeError
App/urls.py File:
from django.conf.urls import url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',views.output,{'template_name':'home_page.html'}),
]
Forms.py File :
from django import forms
class Details(forms.Form):
Device=forms.CharField(required=True, label='Device_Type', max_length=32)
Path=forms.FileField(required=True, label='Path_to_install_build')
Version=forms.CharField(required=True, label='Version_type',max_length=32)

Where is your HTML? if your frontend (HTML) is not reaching your backend at your views, probabily your action is not right, so check if your form have the right action
<form action="/" method="POST">
{% csrf_token %}
<!-- Rest of the HTML code to your form -->
<input type="submit">Submit</input>
</form>
Im setting you action to / because you using root path to your views, if you change it to like detail, the action should be /detail/
BTW you can use the built-in form from django
{% csrf_token %}
{{ form.as_p }}
<input type="submit">Submit</input>

Related

Django - Urls are appending to one another

I'm making a web app in django and currently I'm facing this problem. I have a dashboard page and an upload page. There's a button in dashboard page which links to the upload page. but whenever I click the button then the upload page url appends the dashboard page.
below is the code:
views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from .models import Registration
from .forms import UploadForm
from django.urls import reverse
# Create your views here.
def homepage(request):
return render(request, 'index.html', {})
def dashboard(request):
posts = Registration.objects.all()
return render(request, "dashboard.html", {'posts': posts})
def upload(request):
form = UploadForm()
return render(request, "upload.html", {'form': form})
def uploadimage(request):
if request.method == 'POST':
form=UploadForm(request.FILES['image'], request.POST)
if form.is_valid():
pic = request.FILES['image']
desc = request.POST
post = Registration(pic='pic', desc='desc')
post.save()
urls.py
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
path('', views.homepage, name='homepage'),
path('dashboard/', views.dashboard, name='dashboard'),
path('upload/', views.upload, name='upload'),
path('create/', views.uploadimage, name='uploadimage'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
dashboard.html
<div class="profile">
<div class="left-s col s12 m3 l3">
<div class="profile-overview">
<img src="{%static 'images/group.jpg' %}" alt="profile-pic" class="circle responsive-img">
<p>Daljit Singh</p>
<p>Lorem ipsum dolor sit amet.</p>
</div>
<hr>
<div class="container">
<ul>
<li>About</li>
<li>Friends</li>
<li>Photos</li>
<li>Likes</li>
</ul>
</div>
<hr>
<button>Upload post</button>
</div>
error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/dashboard/upload/
Using the URLconf defined in main.urls, Django tried these URL patterns, in this order:
[name='homepage']
dashboard/ [name='dashboard']
upload/ [name='upload']
create/ [name='uploadimage']
^media\/(?P<path>.*)$
The current path, dashboard/upload/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
Help would be appreciated.
It should be - Upload post
If you enter '/' (/upload/) before the path it will append to the base URL and if '/' (upload/) doesn't exist then it will append to the existing path.
Or the Different way suggested in the comment -
Upload post

django: Take table name as input from user and show the content of the table from database

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>

Trouble Getting User Input in Django

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?

Method Not Allowed (POST) using DeleteView

I am new to Django and i using Class based views to add a delete option to my Restaurant List, However when i click the delete button i am getting a blank screen and getting the following error in the console
"Method Not Allowed (POST):"
Below is my code
views.py
from __future__ import unicode_literals
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView, ListView, DetailView,
CreateView,DeleteView
from django.urls import reverse_lazy
class RestaurantDeleteView(DeleteView):
model = RestaurantLocation
success_url = reverse_lazy('restaurants:list')
urls.py
from django.conf.urls import url, include
from .views import (
RestaurantListView,
RestaurantDetailView,
RestaurantCreateView,
RestaurantDeleteView,
)
urlpatterns = [
url(r'^create/$', RestaurantCreateView.as_view(), name= 'create'),
url(r'^$',RestaurantListView.as_view(), name= 'list'),
url(r'^(?P<slug>[\w-]+)/$',RestaurantDetailView.as_view(),
name="detail"),
url(r'^(?P<slug>[\w-]+)/delete/$', RestaurantDeleteView.as_view(),
name="restaurant-delete"),
]
delete.html
<form method="post" action="" >{% csrf_token %}
<p>Are you sure you want to delete <strong> {{ obj }}</strong>?</p>
<input type="submit" value="DELETE" />
</form>
method in your delete.html is currently "t", change to "post" and see if that works.
Your form action is pointing to root url that is /.
This route is determined by the RestaurantListViews and it is accesed via GET method.
In your example, you are trying to access this using POST, thus you're getting the error.
To make use of your RestaurantDeleteView change the action property in your form to point to an existing restaurant, like:
<form method="post" action="{your_existing_restaurant_slug}/delete" >
{% csrf_token %}
...
...

Html form and Django login system

i want to make simple login system with Django.I want to send a user to a page named 127.0.0.1:8000/login after submitting the form.From then i want to get the post data sent with the request, check if the users exist in the date base and return a html page if he logged in or anothet html page if the user has not logged in.The problem is when i click the submit button of the form, it doesnt make request to /login.It stays at the same page.Any help?
<!DOCTYPE html>
<html>
<body
<form action="/login/" method = "POST">
<input type="text" name="name"><br>
<input type = "submit" value = "Submit">
</form>
</body>
</html>
Urls.py:
from django.conf.urls import url
from django.contrib import admin
from simple import views as f
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^form/$', f.form),
url(r'^login/$', f.data)
]
Views.py
from django.shortcuts import render,render_to_response
from django.http import HttpResponse
from django.template import Context, loader
def form(request):
return render(request,"doccument.html")
def data(request):
name = request.POST.get('name')
return HttpResponse(name)
In your form method should be inside quotes,
<form action="/login/" method="POST">

Categories

Resources