I have this fragment of code in Flask
#app.route('/search', methods = ['POST'])
def search():
if request.method == 'POST':
results_arr = []
img_path = request.form.get('img')
How to make this in Django or where I can read about it?
The route in the flask fragment will be put up in the urls.py with an entry which might look as follows
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index , name='index'),
url(r'^search/$', views.search, name='search'),
]
and in the views.py you'll have a function which will look as follows assuming the corresponding HTML form has enctype multipart/form-data and the html is a file upload.
<input type="file" name="myimage">
The corresponding function assuming you've set the MEDIA_URL and MEDIA_ROOT in the settings can be translated as:
from django.shortcuts import render
from django.conf import settings
from django.core.files.storage import FileSystemStorage
def search(request):
if request.method == 'POST' and request.FILES['myimage']:
results_arr = []
imagefile = request.FILES['myimage']
fs = FileSystemStorage()
filename = fs.save(imagefile.name, imagefile)
file_url = fs.url(filename)
return render(request, 'templateToRender.html', { 'filepath': file_url }) # in case you want to show the user the URL of the upload.
You could also use forms.py an example is provided in their documentation here
Related
In my Django app I want to modify urls.py in order to add an end-point users as localhost:8000/users:
from rest_framework import routers
# ...
router = routers.DefaultRouter()
router.register(r'users', ???)
urlpatterns = [
path('admin/', admin.site.urls),
path(r'', include(router.urls))
]
However I don't know how to modify views.py to enable an endpoint. Should I create a class inside views.py?
from django.http import HttpResponse
import pandas as pd
import datetime
import json
def index(request):
#...
response_data = {}
response_data['prediction'] = y_pred
response_data['probability'] = round(y_prob,2)
response_json = json.dumps(response_data)
return HttpResponse(response_json)
If I'm understanding you correctly, and all you want is for a URL to return some JSON, you just have to alter your urls.py in the usual way.
urls.py
from [app-name] import views
urlpatterns = [
#...,
path("users", views.users_endpoint, name='users_endpoint'),
#...,
]
views.py
# ...
def users_endpoint(request):
#...
response_data = {}
response_data['prediction'] = y_pred
response_data['probability'] = round(y_prob,2)
response_json = json.dumps(response_data)
return HttpResponse(response_json)
So the entry in urls.py is saying:
When the path is ROOT_URL/users, call the view users_endpoint from the views.py file in the app. [app-name].
I am newbie Django dev, I have a bit problem about urls config. I want to make url http://localhost:8000/user-auth/register/
In my project, there is user_auth app with below urls:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^register$', views.register),
]
In register this url within urls in my site:
from django.conf.urls import include, url
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^polls/', include('polls.urls')),
url(r'^user-auth/', include('user_auth.urls')),
]
In my view user_auth/views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .forms import RegisterForm
def register(request):
if request.method == 'POST':
response = HttpResponse()
response.write("<h1>Thanks for registering</h1></br>")
response.write("Your username:" + request.POST['username'])
response.write("Your email" + request.POST['email'])
return response
registerForm = RegisterForm()
return render(request, 'user_auth/register.html', {'form':registerForm})
In my user_auth/forms.py
from django import forms
class RegisterForm(forms.Form):
username = forms.CharField(label='Username', max_length=100)
password = forms.CharField(widget=forms.PasswordInput)
email = forms.EmailField(label='Email')
When I access to the link http://localhost:8000/user-auth/register/, the console announce "Not Found: /user-auth/register/". I dont know reason why and where. Could you please help me on this problem?. Tks
I am attempting to access a page in my application but I keep getting this error :
Page not found (404) Request Method: GET Request
URL: http://127.0.0.1:8000/nesting/Identity-nest/%7B%25%20url%20'nesting:Symptoms_nest_list'%7D
Using the URLconf defined in Identity.urls, Django tried these URL
patterns, in this order:
^admin/ ^Identity/
^nesting/ ^$[name='nesting']
^nesting/ ^Identity-nest/$[name='Identity_nest_list']
^nesting/ ^Symptoms-document/$[name='Symptoms_nest_list']
^$ [name='login_redirect']
The current URL, nesting/Identity-nest/{% url
'nesting:Symptoms_nest_list'}, didn't match any of these.
This is my main urls.py
from django.conf.urls import url, include
from django.contrib import admin
from Identity import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^Identity/', include('Identities.urls', namespace = 'Identities')),
url(r'^nesting/', include('nesting.urls', namespace = 'nesting')),
url(r'^$', views.login_redirect, name = 'login_redirect'),
]
This is my nesting urls.py
from django.conf.urls import url
from nesting.views import Identity_view, Identity_nest_list_view, Symptoms_document_view
from . import views
urlpatterns = [
url(r'^$', Identity_view.as_view(), name = 'nesting'),
url(r'^Identity-nest/$', Identity_nest_list_view.as_view(), name = 'Identity_nest_list'),
url(r'^Symptoms-document/$', Symptoms_document_view.as_view(), name = 'Symptoms_nest_list')
]
This is my views.py
class Symptoms_document_view(TemplateView):
model = Symptoms
template_name = 'nesting/Symptoms_list.html'
def get(self, request):
form = Symptom_Form()
Symptoms_desc = Symptoms.objects.all()
var = {'form':form, 'Symptoms_desc':Symptoms_desc}
return render(request, self.template_name, var)
def post(self, request):
form = Symptom_Form(request.POST or None)
Symptom_content = None
if form.is_valid():
Symptoms_description = form.save(commit = False)
Symptoms_description.user = request.user
Symptoms_description.save()
Symptoms_content = form.cleaned_data['Symptoms_description']
form = Symptom_Form()
redirect('nesting:nesting')
var = {'form': form, 'Symptoms_content': Symptoms_content}
return render(request, self.template_name, var)
This is the line in the HTML template that is the link the Symptoms_document_view view
<li class = "list-group-item"><a class = "nav-link" href="{%url 'nesting:Symptoms_nest_list'%}">{{Identity.First_Name}} {{Identity.Last_Name}} </a> <p>NIS: {{ Identity.NIS }}</p></li>
You need spaces around the url tag in your template:
href="{% url 'nesting:Symptoms_nest_list' %}">
Django's template parser is pretty basic and won't recognise a tag without the spaces.
So, I'm trying to create a table filled with contacts in Python/Django. When I attempt to run the program, I get the above error message ("ImportError: Could not import 'edit_contact'. The path must be fully qualified.")
Here is the views.py I'm using:
from contacts.models import Contact
#, Address, Telephone
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404, render
from django.template import Context, loader
from django.forms.models import inlineformset_factory
from django.template import loader, Context, RequestContext
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
# Create your views here.
def index(request):
#return HttpResponse("Hey! You can see contacts here!")
contact_list = Contact.objects.all().order_by('last_name')
return render_to_response('contacts/index.html', {'contact_list': contact_list},
RequestContext(request))
def detail(request, contact_id):
c = get_object_or_404(Contact, pk=contact_id);
def new_contact(request):
print "new_contact"
#AddressInlineFormSet = inlineformset_factory(Contact,
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
contact = form.save()
return HttpResponseRedirect(reverse('contacts.views.detail', args=(contact.pk,)))
else:
form = ContactForm()
return render_to_response("contacts/form.html",{
"form": form,
}, RequestContext(request))
def edit_contact(request, contact_id):
contact = Contact.objects.get(pk=contact_id)
if request.method == "POST":
form = ContactForm(request.POST, instane=contact)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('contacts.views.detail', args=(contact.pk,)))
else:
form = ContactForm(instance = contact)
return render_to_response("contacts/form.html", {
"form": form,
}, RequestContext(request))
This is the urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<contact_id>\d+)/$', 'detail', name='contactdetailsurl'),
url(r'^new/$', 'new_contact', name='newcontacturl'),
url(r'^(?P<contact_id>\d+)/edit/$','edit_contact', name='editcontacturl'),
]
And the error is pointing to this line in my site_base.html file:
<li id="tab_first"><a href="
{% url contacts.views.index %}
"><i class="icon-book"></i> Contacts</a></li>
Let me know if you need any more info. Thanks!
The error is telling you that you should use the full path to the view, for example 'contacts.views.edit_contact' (assuming the app is called contacts).
However, using strings in your URL patterns is deprecated in Django 1.8, and not supported in Django 1.10+. You should using callables instead. You are already using the callable views.index for your index URL pattern.
I would convert the rest of your URL patterns as follows:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<contact_id>\d+)/$', views.detail, name='contactdetailsurl'),
url(r'^new/$', views.new_contact, name='newcontacturl'),
url(r'^(?P<contact_id>\d+)/edit/$', views.edit_contact, name='editcontacturl'),
]
I am trying to upload files using django forms and save those files in the database itself.
I have been able to save the link of the file in database and save the file itself in a directory which i specified in Media_root.Can you please help me and tell me what can i change in my code so that files are saved in the database.
here is my code:
models.py
from django.db import models
class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')
forms.py
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file',
)
views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from .models import Document
from .forms import DocumentForm
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('upload.views.list'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'list.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
def index(request):
return render_to_response('index.html')
app\urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import RedirectView
from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'^upload/', include('upload.urls')),
(r'^$', 'upload.views.index'),
(r'^admin/', include(admin.site.urls)),) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
project\urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('upload.views',
url(r'^$', 'list', name='list'),
url(r'^list/$', 'list', name='list'),)
Django provides BinaryField that lets you store any binary data, including file contents.
Please do note that the documentation also says:
Although you might think about storing files in the database, consider that it is bad design in 99% of the cases. This field is not a replacement for proper static files handling.
If you'd rather not store the files on your web server's file system, you can explore other options such as Amazon S3 or just an FTP server. Have a look at the django-storages library, it provides a nice bunch of options.