I have a small blog app I have built using Django 1.4 and recently, I have been learning "bits and pieces" of html5 and css3. I am about the start transitioning my site to html5/css3 and I was wondering if Django widgets support html5(?)
My blog is nothing special - a few forms, a few tables etc.. For example when I do,
{{form_as_p}}
I was wondering if django would generate the required html5 markup(?) I read the docs, and it says the admin pages support html5, but I could not find any docs for regular apps.
If html5 is not supported by Django, what is the best way going about achieving this?
Thanks for your time.
Django's form output is XHTML. Django does not snip with support for the new HTML5 input types such as number, email, url, etc but it is not difficult to add them. See https://code.djangoproject.com/ticket/16630 or https://github.com/rhec/django-html5 That being said I don't know any place where Django generates markup that is invalid for HTML5.
"If html5 is not supported by Django, what is the best way going about achieving this?"
I have been trying a monkeypatch approach with very encouraging results so far, the big bonus for me is that there is no need to change your existing code, or for modifying third party apps, or Django admin. This keeps things very clean and central and there is no need for hairy and repetitive admin.site.register(...)/admin.site.register(...).
https://github.com/danielsokolowski/django-html5monkeypatch
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Thanks in advance! This is more a "philosophical" question then a direct request for opinions on code, though I would greatly appreciate anyone's input on code examples to look at.
I've been a "traditional" developer for as long as I can remember, and now I work professionally as a data scientist. That being said, the one frontier I've never truly touched is web development.
For a project I'm working on, I need to build (and in a somewhat expedited timeframe) a good-looking web application that functions somewhat similarly to a Wiki website (using existing codebases like Mediawiki is not an option here, so assume everything has to be built from the ground-up).
In trying to do things the "right way", I've set things up as follows:
Django models are built that seem to correctly capture the relational structure of data for the webapp, at least as tested by playing with Django's admin portal
Django is hooked up to a Postgres database
(1) and (2) are running inside Docker containers
The most important piece here left, obviously, is the frontend. I've tried to ask several friends and acquaintances for advice, and have been pointed in the Bootstrap direction.
From here, I admit, I'm a bit stuck.
I see examples on the Django docs that don't involve any Javascript (it seems, with minimal lift, HTML pages can directly interact with the database, using what seems like a pretty simple "insert-placeholder-here" logic, as I have set it up through the Django models). I see a similar construction here and here.
But then I see a whole other set of instruction on the web about how to make a functional webapp-- creating serializers for the Django models to JSON, building a REST api, writing the frontend page logic using Javascript and using a library imported into Javascript to interact with the manually-built API(s) to interact with the backend.
Now, of course, the "first" approach seems much simpler. The second feels like reinventing the wheel-- if I can simply use a construction like {{ num_books }}, why would I go about building all those APIs and worrying about JSON? But I feel confused. Is there a "right" choice, thinking long-term? It seems like I can find people using Bootstrap and other frameworks taking both approaches. Can I not use Javascript code unless I take the JSON/API approach? Does that even matter? What truly are the differences here?
A compass on the rough seas would be much appreciated. Surely I cannot be the first to try to build a functional webapp with Django... the frontend is totally foreign to me.
Thank you all!
In the first place, Django is a framework which means that it contains already a predefined set of necessary functionality that most people need, sometimes people say "with batteries included".
Before REST architecture was invented front-end and back-end were closely related to each other. There wasn't a straight line between them and it was hard to share business logic with other services.
Basically we can say that there are two options, how to organize front-end and back-end workflow with Django:
Using Django templates:
The most simple and easiest way to get started. All that you need already presented in Django. Let's take a look at this simple example:
views.py
def index(request):
fruits = Fruit.objects.all()
render(request, 'index.html', {'fruits': fruits})
And after that you can use variables from the context in your template like so:
index.html
<ul>
{% for fruit in fruits %}
<li>{{ fruit }}</li>
{% endfor %}
</ul>
Django template system is really powerful and customizable if the default template engine doesn't suit your needs there is a possibility to choose another one, for example Jinja.
You can do a lot of stuff there, but as a general recommendation, all the "computing" stuff shouldn't be stored on the template level because it can dramatically increase the time rendering of the page. The better place to put business logic is views and most of the work with the database on custom managers.
For dynamic parts of your application, you could use AJAX probably from JQuery library.
It's also quite simple to work with forms, Django by default handle it with csrf protection. Default validators and model forms give you real power.
When you use templates you depend on them, most likely you couldn't reuse your endpoints somewhere else and that's why you need REST. Django has a little set of features that can help you with it and most likely you would end up with django-rest-framework usage which one of the most popular libraries used with Django today.
Using REST architecture:
The example above would look like this, though there is ModelViewSet, which do the most of boilerplate stuff for you:
class FruitViewSet(viewsets.ViewSet):
def list(self, request, *args, **kwargs):
fruits = Fruit.objects.all()
ser = FruitSerializer(fruits, many=True)
if not ser.is_valid():
return Response({}, status=status.HTTP_400_BAD_REQUEST)
return Response(ser.data, status=status.HTTP_200_OK)
You can use ModelSerializer or write your own serializers. The validation process is simple and straightforward:
class FruitSerializer(serializers.ModelSerializer):
def validate(self, attrs):
# validate your data here
pass
class Meta:
model = Fruit
fields = '__all__'
To display this data on a web page you could use whatever you want, vanilla javascript or any javascript framework which supports REST, the most popular today: React, Angular, Vue.
With REST you could use the same API for your web, mobile application and so on. In the end, implement once use everywhere.
As soon as you want to have dynamic parts in your frontend, you will need Javascript at some point. To fasten up development I highly suggest to use a framework like Vue, React or Angular. They have dozens of tools to use for particular needs within your project. Also you might look into jQuery when using Javascript.
I am currently building a Django web application myself (started like 3 months ago). I use Javascript a lot to manipulate the Django rendered templates.
Why Django might be your right choice
The nice part about Django is the Model-View-Template architecture which by my opinion is an excellent framework for your wiki app. You request a http, Django fires the linked view-function and renderes the template - et voila!. And if you need data transmission from/to PostgreSQL you just build a model and include the data calls into the view-function to use the data on the frontend.
You won't have to build a user management system (built-in
django-admin)
You will have a lot of frontend required business logic included in the Django orbit
No need to worry about JSON. You just fetch the data from the database using python objects and work with that data in the frontend. If at some point json would be a better choice for whatever reason, you just manipulate it with a Python serializer.
It is pretty easy to deploy/publish a Django based application using e.g. digitalocean.com or heroku.com
Since this was some broad question, I hope I could provide you some hints on how to proceed with your development. However, feel free to comment this post for further questions.
To give you a brief feeling I will attach some snippets of my current project, using basic HTML, CSS and Javascript along with Django as the python based backend.
I need to make objects editable in frontend by clicking on it and enable a form field to edit the text. i.e. in a ToDo-list which tasks can be edited by clicking on the task like shown in the following graphics:
I am working with Django 2.x and unfortunately, I'm a little inexperienced.
Is it a good practice to realize this with REST API and/or Angular/React?
I would be glad about a few experiences, how something is feasible.
I have found a good solution to implement the desired functionality with Jeditable
https://github.com/NicolasCARPi/jquery_jeditable
I've had a look at some really good website layout and design using Django, pinterest, (former)curse, disqus, and the django design template lpoks impressive.
Was just pondering thoughts as to were it is necessary to add css3 or html5 to enhance page design and interaction or would using Django features for eg. divs and headers, boxing text good enough or even better visually.
Lets for argument sake, say we are developing an extensive auction site like e-bay or networking site like facebook.
Django doesn't have any design. There is zero front-end included, so that if you made a template page and added divs/headers/whatnot in there it would have absolutely no custom formatting whatsoever beyond the specifications of vanilla HTML.
So if you want to design a site like Pinterest you'll definitely need your own CSS and HTML.
So, django make a view with HTML and CSS (you will have some div..) but no div will be declared and you will have a white page withall things aligned to left..
It is not complicated, if you want a beautiful site (or just not hugly :)) you will need both html and css, but not last versions if you don't wand (but its better..)
I'm looking at porting a custom-written PHP CMS into Django. One of the features the CMS currently has is an image upload function. I write an article, tag it with information, then choose a photo for it. If the system has any photos which have been added to articles with tags in common with the new one, it will suggest the photo for that article too. If there are no matches then a new image can be added.
In case this doesn't make sense, let's say I tag an article as Bruce Springsteen, The Beatles and Led Zeppelin. Next time I add an article with the tag The Beatles, it should suggest I use the image added for the first article.
What would be the best Django-applicable way to implement this? I've looked at the Photologue app and have integrated it, and I know it has tagging support (the problem here is that I'm using django-taggit, whereas Photologue supports django-tagging). One approach could be simply building it myself -- when a user uploads an article, I run a hook after they save it to associate the tags with the image. I'm just not sure how to then autosuggest an image in the admin tools based on that info.
Any ideas/approaches greatly appreciated.
This is almost certainly something you're going to have to build yourself. Django has a moderate number of libraries out there (that you've clearly already found). Unlike other solutions, it doesn't have a lot of things that get you 100% to your desired solution (whereas something like Drupal might get you 100% of the way there).
What you will probably need to do (at a high level) is something like this:
Create an AJAX view that takes the current tags as an argument and does a query on the existing posts to see what tags match and returns images from those posts.
Use jQuery/javascript on your view to call your AJAX view on the page as tags are added
Use jQuery to update a <div> on your page and show all the images that your view returned
Here is a similar example that might help get you started.
You might look into django-ajax as a helper library for your requests, but it definitely isn't necessary.
The hook between the your image module and any other django module can be implemented using django's contenttypes framework which also provides some useful instance methods for returning related/hooked objects.
Please share your thoughts abouts the following
When to use Django Forms to produce the HTML fields
When to avoid it and use the plain HTML
Any other tips and best practices
I use django forms or maybe another forms helper if I need something specific in every case, no matter what. I never compose forms using plain-old html.
Many aspects of form processing are not related to presentation. What kind of information needs to be collected and how to validate that certainly falls outside of the domain of presentation. Using a forms helper can help to unify all of this work in a pretty convenient way.
The fact that a forms helper can also render html is sort of coincidental to it's use. Certainly, if that's all they did, they wouldn't be worth much, but since they do all of that and stay in sync with the needs of the business logic, it somewhat requires using the html rendering from the form helper to reap the maximum benefit from the assistance it offers the rest of the app.
When to use Django Forms to produce the HTML fields
Django forms provide HTML forms for models, user-built as well as combination of both. One should be using Django forms most of the times since it considerably reduces the redundant templating effort. The tightly controlled security provided by Django forms along with the strong validation support is worth the effort to use Django forms.
When to avoid it and use the plain HTML
A good use-case to avoid Django forms is when you need to fire javascript events or there is a lot of style deviation from your main stylesheet.
Any other tips and best practices
Derive maximum advantages of the framework by using maximum features of the framework as possible.