Incorporating existing html pages into Django - python

I have several hundred static html pages, with an index html page, that I need to bring into Django. I can't figure out the easiest way to do that, I know I'm missing something simple. Any advice?
Nothing fancy needed, just need to dump them in a directory and allow users to navigate to them.

You need to create a view and a url for each html template, iI'm going to put you a simple example here but it's highly recommended that you read Django's documentation or a tutorial :
First, you create a view in a views.py file :
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views.generic import View
class LoadTemplateView(View):
template_name = ['thenameofyourdjangoapp/yourtemplatename.html']
#You put any code you may need here
def get(self, request, *args, **kwargs):
return render(request, self.template_name)
Then, you must create a url that reads that view in a urls.py file :
from django.conf.urls import patterns, url
#Here you import from views the view you created
from .views import LoadTemplateView
urlpatterns = patterns(
url(r'^myurl/$', LoadTemplateView.as_view(), name="load_template"),
)
Last, in your let's say home html template, you assign this url to a submit button in order to call it by the name you gave it on urls.py (load_template in this case) :
<html>
<body>
<div>
<a class="option-admin" id="id_go" href ="{% url 'yourdjangoappname:load_template' %}"> Go to template </a>
</body>
</html>
</div>
As I said anyway, it's better that you read the complete Django documentation as well:
https://docs.djangoproject.com/en/1.9/

If these are legacy static pages that you do not plan to touch again, then I'd leave django out of it. I'd put them all in a directory or subdomain and serve them directly from the server (probably nginx, maybe apache, whatever you're using). As a general rule, you don't want Django serving static assets, you want the proxy server serving them.
You COULD move them into Django and manage them like other Django static assets, as described in the Managing Static Files Documentation, but if they're already out there, then there's not a whole lot of advantage over just serving them as outlined above.
And finally, if you wish to fully integrate them into your Django site, then you should probably start with the template documentation.

Related

redirection from old urls to new urls

Hello everyone I want to redirect URLs like this
from
https://www.example.co.uk/pages/terms-conditions
to
https://www.example.co.uk/terms-conditions
I developed the updated site using the Django framework and now want to redirect old site URLs to new URLs and not losing traffic. what is the best way of doing…?
New site is not published it is on local machine
my view.py
my urls.py
I guess this is not best practice but you can just redirect the user to the right url if he hits the other one in your views.py like:
def old_view(request):
return redirect('https://www.example.co.uk/terms-conditions')
def new_view(request):
return render(request, "your_app/conditions.html")
with urls.py like:
path('pages/terms-conditions/', views.old_view, name='old_view')
path('terms-conditions/', views.new_view, name='new_view')
Assuming you want to remove the application name from the urls. In your project's urls.py NOT your applications urls.py. You should have a line similar to the following:
path('pages/', include('pages.urls', namespace='pages')),
replace the 'pages/' with just ''.
Note: Using the pages/ allows you to provide segregation between your applications to ensure the urls do not conflict

Build HTML from Django View

I need to construct the HTML body from a Django view and I cannot find a solution to refer correctly a JPG file ( must say that the HTML is much larger then this, but with other stuff seems that is working for me
):
I've tried this:
from django.template import Template
...
html = Template('<IMG SRC="{% static "base/images/course/website-46-2.jpg" %}">')
return HttpResponse( html )
And I get this error:
Invalid block tag on line 1: 'static'. Did you forget to register or load this tag?
In Django template I resolve this by loading the static files:
{% load static %}
How can I do this in Python ( Django View ) ? Or any other suggestion is much appreciated.
I've tried different solution that I have found on this site and others but none seems to work for me.
Django Version: 2.2.1
You can create an engine with the static library as a built-in. This makes it available to the template without calling {% load static %} first.
from django.template import Template, Context, Engine
engine = Engine(builtins=['django.templatetags.static'])
template = engine.from_string('<IMG SRC="{% static "base/images/course/website-46-2.jpg" %}">')
return HttpResponse(template.render(Context()))
Have you set your STATIC_URL in settings.py? You can do this by the following:
STATIC_URL = '/static/'
Your image would then be found under 'your_app/static/base/images/course/website-46-2.jpg'.
Does the folder structure follow this convention? If not you can set the STATIC_URL to '/base/'
def startchat(request):
template=loader.get_template('app1/chatbot.html')
return HttpResponse(template.render())
This function loads the html page into Django.
Before that , we need to import the module
from django.template import loader

DRF does not reverse Django url pattern: NoReverseMatch

There is a complex app (not possible to just paste the code). Going to try to explain.
Django
There is a urls.py file from the native Django app. The urlpatterns defines and register its urls. The ^foo/ defines a group of related urls and the foonamepsace.
urlpatterns = patterns('',
...
url(r'^foo/', include('foo.urls', namespace='foonamespace')),
...
Now there is a method generate_report which does some logic inside and then uses render_to_string to return the HTML:
def generate_report(..):
...
return render_to_string('foo/foo_report.html', args)
Everything works inside the app, the url get reversed successfully.
Django Rest Framework (DRF)
Now there is a DRF implementation and one of its resources is supposed to return a report in a binary format.
class PDFReportViewSet(APIView):
renderer_classes = (BinaryFileRenderer, )
def get(..):
...
pdf = generate_report() # <-- fails with NoReverseMatch
...
return response
Problem
The ViewSet calls the generate_report, however one gets an error when trying to parse the HTML:
NoReverseMatch: foonamespace' is not a registered namespace
Question
Any clues why DRF cannot reverse the namespcae/url from the the core of Django app? How to make sure DRF can reverse a namespace from the core urls.py urlpattern?
Added
After investigation, inside the foo_report.html any usage of the url, for example {% url 'foonamespace:123' %} or {% url 'barnamespace:123' %} produces the error - only if ran from the DRF (running the same page using native Django works fine).
URLS
foo.urls.py
from django.conf.urls import patterns, url
from foo.views import (FooListView, FooDetailView...)
urlpatterns = patterns('',
url(r'^$', FooListView.as_view(), name='foo_list'),
url(r'^(?P<pk>\d+)/$', FooDetailView.as_view(), name='foo_details'),
Important note. The app is served at some.domain.com/, while the REST is served from some.domain.com/rest. So may be this way /rest just don't include anything because it is a parent of the root (which includes the foo.urls.py)
I was managed to resolve my issue with the help from #dirkgroten. It was difficult to see the problem without looking at the source code.
Solution
Updated the routers.py file:
urlpatterns = router.urls
urlpatterns += patterns('',
url(r'^foo/', include('foo.urls', namespace='foonamespace')),
)
Explanation
Basically, the app was serve from the root url / while the rest was served from /rest. The DRF router simply didn't include any of the root routes. Adding them manually like it is shown in solution resolved the problem and made foonamespace visible for all DRF elements.

Django display user uploaded content

I have yet to wrap my head around django and URLs, and my confusion is now preventing me from doing what I feel like should be a very simple task.
I have successfully implemented file upload.
In my settings.py file, I have added the specifications for where to store the uploaded files and the URL Django should use to serve them.
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL= '/media/'
I also added the necessary line to urls.py to allow Django to serve files from MEDIA_URL.
from django.conf.urls import url, include
from django.contrib import admin
from login_app import views as login_app_views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/', login_app_views.login_user),
# creating registered namespaces for each app
url(r'^login/', include('login_app.urls', namespace = "login_app")),
url(r'^CMIRS/', include('dashboard_app.urls', namespace = "dashboard_app")),
url(r'^CMIRS/', include('submit_app.urls', namespace = "submit_app")),
url(r'^CMIRS/', include('filter_app.urls', namespace = "filter_app")),
url(r'^CMIRS/case/',include('report_app.urls', namespace = "report_app")),
url(r'^CMIRS/', include('search_app.urls', namespace = "search_app")),
url(r'^search/', include('haystack.urls')), ##used in navbar-search
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In an app report_app, I want the webpage to display a hyperlink that can be used to view an uploaded file. When I click on the hyperlink, I want it to request the URL to the uploaded file.
The upload looks like such in my models:
upload1 = models.FileField(upload_to = 'documents/%Y/%m/%d/')
I am having trouble figuring out what to use in the render(request) in my view and how to correctly code this in HTML. When I attempt to use "media", I get an error saying it cannot be matched.
Here is a snippet of the HTML I am trying:
<dt>Upload</dt><dd><tr><td>{{ case.upload1 }}</td></tr></dd>
I am also confused as how to set up my render(request) so that it knows to access media/, and then go to the correct documents/Y/M/D depending on the primary key.
You don't want to use the url tag here at all. Your media's URL is stored in your model, and has nothing to do with Django's path resolution logic. Just reference the url method of the field:
<a href="{{ case.upload1.url }}">
See the docs.
(Note also that serving files via your urls.py like this works in dev only; for prod you'll need to configure your webserver to do it.)

How do I use generic views in Django?

I am trying to use Django's generic views to make a user registration page. I have the following code in my app's urls.py
from django.conf.urls.defaults import *
from models import Ticket
urlpatterns = patterns('',
(r'^new/$', 'django.views.generic.create_update.create_object', { 'model': User } ),
)
Now when I go to that url I get the following:
TemplateDoesNotExist at /new/
auth/user_form.html
I have tried making a template to match it but I keep getting that message. Any advice?
Also, I assumed that this would make the template for me. What do I actually put in the template file when I make it?
EDIT: Coming from rails I was mixing templates and views. I am still stuck but I think I need to make a function in my view. Something like:
def user_form:
#stuff
You will need to create the template file using the format <app_label>/<model_name>_form.html. Place this template into the template directory as defined in TEMPLATE_DIRS in your settings file.
In the template file itself, you will need to use the context as defined by the standard ModelForm.
{{ form.name.label_tag }} {{ form.name }}
i don't think you need to create a view function. you need to provide a template (auth/user_form.html in this case, is also configurable) in your templates directory. The template needs to contain the necessary fields to create the new user object.
see the docs for this.
ans also check out this similar discussion

Categories

Resources