Uploading file to website with android - site cant be reached - python

I am trying to upload a file in a website using the django framework. When i use my laptop i have no problem at all, but when trying to upload the exact same file with my android device i get 'This site cant be reached'
The problem happens when i click the submit button. I can normally access the main.html with my android device and can even access the get_post/ url without POST if i dont click the button. But when it is clicked i get 'This site cant be reached'
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.core.files.storage import default_storage
from .Uploaded_files import C_Convert as conv
from django.utils.datastructures import MultiValueDictKeyError
def main_view(request):
return render(request, 'main.html')
def get_file(request):
if request.method == 'POST':
print(1)
try:
uploaded_file = request.FILES['file']
except MultiValueDictKeyError:
return HttpResponse('<h1>Error</h1>')
default_storage.save('CSD_Project/Uploaded_files/'+uploaded_file.name, uploaded_file)
result = conv.convert(uploaded_file.name)
return HttpResponse('<h1>%s</h1>'%result)
else:
return HttpResponse('<h1>Error</h1>')
urls.py
from django.contrib import admin
from django.urls import path
from .views import get_file,main_view
urlpatterns = [
path('admin/', admin.site.urls),
path('', main_view),
path('get_file/', get_file) ]
main.html
<!DOCTYPE html>
<html lang="en" style = "background-color: darkslategrey">
<head>
<meta charset="UTF-8">
<title>HY100 Tests</title>
</head>
<body>
<div style="text-align: center;">
<form action="get_file/" method="POST" enctype=multipart/form-data>
{% csrf_token %}
<input type="file" name="file">
<button style="color: white; background-color: #222222; padding: 15px 32px; font-size: 15px;" class="button">Submit file</button>
</form>
</div>
</body>
</html>

Related

Django stops updating data to mysql after page refresh

I'm fairly new to using the django framework and recently I made a system with it where it submits data to mysql db through a html form. I got it working eventually and everything seemed quite fine, though I noticed a bug where if I refresh the page django stops sending data to mysql, has this ever happened to anyone?
Stuff for reference:
views.py
from django.shortcuts import render
from websiteDB.models import dbInsert
from django.contrib import messages
def insertToDB(request):
if request.method == "POST":
if request.POST.get('uname') and request.POST.get('email') and request.POST.get('message'):
post = dbInsert()
post.uname = request.POST.get('uname')
post.email = request.POST.get('email')
post.message = request.POST.get('message')
post.save()
messages.success(request, "Message sent successfully.")
return render(request, "contact.html")
else:
return render(request, "contact.html")
models.py
from django.db import models
class dbInsert(models.Model):
uname = models.CharField(max_length=100)
email = models.EmailField()
message = models.TextField()
class Meta:
db_table = "contactrequest"
urls.py
"""
websiteDB URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
from . import views
from . import index
urlpatterns = [
#path('admin/', admin.site.urls),
path('homepage', index.page_home, name= 'hpage'),
path('', views.insertToDB),
path('contactpage', index.contact_page, name= 'cpage')
]
contact.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght#200&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{% static 'css/css/styles.css' %}">
<title>Document</title>
</head>
<body style="background-color: rgb(74, 36, 110);">
<script src="{% static 'js/main.js' %}"></script>
<div class="top-nav">
HOME
PRODUCTS
CONTACT
ABOUT
COMMUNITY
</div>
<div class="div-align">
<h2>Contact</h2>
<p>Reach us for questions/concerns through the form below.</p>
</div>
<form class="fontmaker" method="post">
{% csrf_token %}
<label for="Username">Username:</label><br>
<input type="text" id="Username" name="uname" required><br>
<label for="E-mail">E-mail:</label><br>
<input type="text" id="Email" name="email" required>
<label for="Reason" class="margin">Message:</label>
<textarea id="Reason" name="message" rows="10" cols="60" required>Type your reason of contact here.</textarea>
<input type="submit" value="Submit" class="rounded-corners" id="submitBtn">
{% if messages %}
{% for message in messages %}
{{message}}
{% endfor %}
{% endif %}
</form>
</body>
</html>
There are no errors in terminal, and the button click also properly sends a POST req:
Terminal output
I'm also new to posting on stackoverflow, tell me if there's something else to improve on in the future when posting.
index.py
from django.http import HttpResponse
from django.shortcuts import render
def page_home(request):
return render(request, 'index.html')
def contact_page(request):
return render(request, 'contact.html')
Thanks in advance.
If you render the contactpage/ URL, then if you submit the form, you will submit it to the contact view, but that view does not handle the data, nor does it create any entry. You must make sure that you post the form to the insertToDB view. You can do this by giving the view a name:
urlpatterns = [
# …,
path('', views.insertToDB, name='insertToDB'),
# …
]
and then specify the endpoint in the form:
<form class="fontmaker" method="post" action="{% insertToDB %}">
<!-- … -->
</form>
In case of a successful POST request, you should also redirect, for example with:
from django.shortcuts import redirect
def insertToDB(request):
if request.method == 'POST':
if request.POST.get('uname') and request.POST.get('email') and request.POST.get('message'):
post = dbInsert.objects.create(
uname = request.POST['uname'],
email = request.POST['email'],
message = request.POST['message']
)
messages.success(request, 'Message sent successfully.')
return redirect('cpage')
return render(request, 'contact.html')
else:
return render(request, 'contact.html')
I would advise to work with Django forms [Django-doc], for example a modelform [Django-doc] to validate and clean form input and remove a lot of boilerplate code.

Write contents of ace.js editor to file in Django

I am playing around with the idea of editing my Django templates from the server. I know this is a far shot from that but I wrote this bit of code:
def editor(request):
handle=open(os.path.join(settings.BASE_DIR, 'app/code/test.html'), 'r+')
var=handle.read()
context = {
"message": "editor",
"code": var
}
return render(request, 'app/editor.html', context)
That reads a file and passes it's contents to the template where ace.js displays it in the editor.
<div id="editor-container">
<div id="editor">{{code}}</div>
</div>
It displays just fine and I can edit the text, but if I wanted to save my edits, writing them to the file, the button would need to go to a save route because I'm not using ajax, but how would I pass the new version of the document to the view to be written to the file?
To make this work you need to have an hidden input. Whenever the contents of the editor are updated, the input is also update. Saving the contents is just now a matter of submitting the form. Here is what I came up with.
First is the html template where the editor is.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ace editing</title>
<style type="text/css" media="screen">
#editor {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.editor-container {
position: relative;
height: 300px;
width: 100%;
}
</style>
</head>
<body>
<div class="editor-container">
<div id="editor">
{{code}}
</div>
</div>
<form method="POST">
{% csrf_token %} {{form.as_p}}
<button type="submit">Save</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js"></script>
<script>
var editor = ace.edit('editor');
editor.setTheme("ace/theme/monokai");
editor.session.setMode("ace/mode/html");
editor.on('change', function() {
code_hidden_input = document.querySelector('#id_code');
code_hidden_input.value = editor.getValue();
console.log(editor.getValue())
})
</script>
</body>
</html>
Now in your views.py the code will be like the following.
from django.shortcuts import render
from .forms import MyForm
import os
from django.conf import settings
# Create your views here.
def index(request):
form = MyForm()
handle = open(os.path.join(settings.BASE_DIR, 'core/templates/core/test.html'))
code = handle.read()
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
print(form.cleaned_data['code'])
# This is the part where you save the code you have
# edited to some file
context = {
'form': MyForm(),
'code': code
}
return render(request, "core/index.html", context)
In your forms.py file create a class called My Form like below
from django import forms
class MyForm(forms.Form):
code = forms.CharField(max_length=10000, widget=forms.HiddenInput())
That's all, note when submiting html using forms you need to sanitize your input.

POST method is not working when submitting form in django

I created feedback form using form module in django. i wrote the code for printing form data entered by user when submitting form. But when i submit the form post is not working as a result user data is not printing . I am beginner in django .I tried lots to solve this .but i couldn't. please help me if anyone know what is my wrong in code
forms.py
from django import forms
class feedbackForm(forms.Form):
Name=forms.CharField()
RollNo=forms.IntegerField()
Email=forms.EmailField()
feedback=forms.CharField(widget=forms.Textarea)
views.py
from django.shortcuts import render
from .import forms
def feedback_view(request):
form=forms.feedbackForm()
if request.method=='POST':
form=forms.feedbackForm(request.POST)
if form.is_valid():
print('form validation success and printing feeback info')
print('student name :',form.cleaned_data['Name'])
print('student RollNo:',form.cleaned_data['RollNo'])
print('student Email :',form.cleaned_data['Email'])
print('student feedback :',form.cleaned_data['feedback'])
return render(request,'testapp/feedback.html',{'form':form})
urls.py
from django.conf.urls import url
from django.contrib import admin
from testapp import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^feed/', views.feedback_view),
]
feedback.html
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="{%static "css/demo1001.css"%}">
<title></title>
</head>
<body>
<div class="container" align=center>
<h1>ShefJaz Student 2feedbackform </h1><br>
<form method="post">
{{form.as_p}}
{%csrf_token%}
<button type="button" class="btn btn-primary">sumbit feedback</button>
</form>
</div>
</body>
</html>
You are using a function as a API view so, It should be mentioned in the method decorator like shown below
from rest_framework.decorators import api_view
#api_view(['POST'])
def feedback_view(request):
.....
your code
.....
Hope it will give you the solution.
more than one HTTP methods can be used like shown here.
#api_view(['POST', 'GET'])

Google Search using python

I get data from input. When I click to search button I need to open webbrowser page and see my input data in google. How can I do that? Many thanks.
This is my code:
views.py:
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
if request.method == 'GET':
return render(request, 'index.html', context={})
# Handles the search once the submit button in the form is pressed
# which sends a "POST" request
if request.method == 'POST':
# Get the input data from the POST request
search_query = request.POST.get('search', None)
# Validate input data
if search_query and search_query != "":
return HttpResponse(search_query)
try:
from googlesearch import search
except ImportError:
print("No module named 'google' found")
for j in search(search_query, tld="co.in", num=10, stop=1, pause=2):
print(j)
else:
return HttpResponse('Invalid input.')
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form method="POST">
{% csrf_token %}
<input type="text" name="search" placeholder="some text"><br>
<button class="button" name="submit" type="submit">Search</button>
</form>
</body>
</html>
urls.py
from django.urls import path
from firstapp import views
urlpatterns = [
path('', views.index, name='home')
]
All files are in hello folder. My app namely firstapp path: C:\Users\user\Desktop\hello\firstapp
index.html path is:
C:\Users\user\Desktop\hello\firstapp\templates
In order to redirect to google you need to have your search textfield to use a parameter called q. Here is an index.html file that would work:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form action="https://google.com" method="GET">
{% csrf_token %}
<input type="text" name="q" placeholder="some text"><br>
<input type="submit" name="submit" value="Search">
</form>
</body>
</html>

Django POST request not working correctly

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?

Categories

Resources