I am beginner at Django. I was wondering what is the best practice to place the user login and logout functions. I already have a global static folder and templates.
Should I create a view.py under my Project-Root folder for the functions? Or should I create a separate APP just to put this functions in?
I already have this functions and templates inside myapp view.py
projectname]/ <- project root
├── [projectname]/ <- Django root
│ ├── __init__.py
│ ├── settings/
│ ├── urls.py
│ └── wsgi.py
├── myapp/
│ ├─ __init__.py
│ └── view.py
│
├── manage.py
│
├── static/
│ └── GLOBAL STATIC FILES
└── templates/
└── GLOBAL TEMPLATES
You should use some user authentication within one App which you have created, or create one App just for managing accounts.
Since you are a beginner you should take a look at Django-admin user authentication.
https://docs.djangoproject.com/en/1.10/topics/auth/
The answer to the question is quite subjective i.e. varies from project to project, or developer to developer. My suggestions 'd be:
As you have asked for the log-in and log-out functions, this means you'll be handling users for your app - so a good approach 'd be to have a users app, and place the functions in users/views.py
For complex system - where you may have different types of users i.e. users, admin_users, partners, etc. You can have separate directory at project root e.g. lib/ and have functions.py in it, keep all the project wide usable functions, utilities in this file.
projectname]/ <- project root
├── [projectname]/ <- Django root
│ ├── __init__.py
│ ├── settings/
│ ├── urls.py
│ └── wsgi.py
├── myapp/
│ ├─ __init__.py
│ └── view.py
│
├── lib/
│ ├─ __init__.py
│ └── functions.py
│
├── manage.py
│
├── static/
│ └── GLOBAL STATIC FILES
└── templates/
└── GLOBAL TEMPLATES
Your question is not clear as to what you want to place. Is the template files you want to place in or the view function "logout" and "login"? I assume it has to be the "login" and "logout" function what you are looking for.
You have to create a views.py file under "[projectname]/apps" folder.
view for login
def login_validate(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username= username, password= password)
if user is not None:
login(request,user)
return HttpResponseRedirect('/--template name--/')
else:
return HttpResponseRedirect('/--template name--/')
else:
return HttpResponseRedirect('/--template name--/')
view for logout
def logout_page(request):
logout(request)
return render(request,"logout_page.html",{})
Above are the functions. You will have to add few things in settings.py before doing this.
And also create a urls.py file under apps folder and link it to main urls.py file.
I hope this is clear.
https://docs.djangoproject.com/en/1.10/topics/auth/default/
https://www.youtube.com/watch?v=eMGtdtNR4es
The above links are helpful.
Related
I have a Lambda layer which includes my shared code (data models) and pip packages. I would like to import that to my Lambda function and use it. I am able to add the Lambda Layer, use the pip packages without any issues but when I try to import my models from this common layer. I keep getting the following error.
'errorMessage': "Unable to import module 'app': attempted relative import beyond top-level package"
I believe it is related to the folder structure of layer or function (more probable). I followed the convention for the Lambda Layer.
Below is the folder structure for my Layer.
├── LICENSE
├── README.md
├── __init__.py
├── python
│ ├── lib
│ │ └── python3.9
│ │ └── site-packages
│ ├── model
│ │ ├── __init__.py
│ │ ├── a.py
│ │ ├── b.py
├── requirements.txt
├── samconfig.toml
└── template.yaml
Here is the structure for my Lambda function:
├── README.md
├── __init__.py
├── events
│ └── event.json
├── openapi.yml
├── requirements.txt
├── samconfig.toml
├── src
│ ├── __init__.py
│ ├── app.py
│ ├── db.py
│ ├── service.py
├── template.yaml
What I try to do is import for example, a.py from model folder inside db.py, such as:
from model import a
but it results in the error I mentioned:
'errorMessage': "Unable to import module 'app': attempted relative import beyond top-level package", 'errorType': 'Runtime.ImportModuleError'
Resolved: Apparently it is not possible to import from a folder like this. I have deleted the model folder and created a new file under python directory, such as models.py, copy and pasted all my models inside that single file.
Now importing models in the form of: import A from models.py works.
One solution that could work is have my models in separate files but import all them into a models.py file and import from it from the function itself.
I have an app
main/
├── asgi.py
├── celery.py
├── __init__.py
├── settings.py
user/
├── admin.py
├── apps.py
├── __init__.py
├── migrations
│ ├── 0001_initial.py
│ ├── ...
├── models.py
├── tests.py
├── urls.py
└── views.py
In admin.py the admin page title is set like this:
from django.contrib import admin
admin.site.site_header = settings.HOME_TITLE
Which works on localhost:8000/admin/.
But http://localhost:8000/accounts/password_reset/ still shows the standard Django Administration title. Is there a way to change that consistently or would I have to create my own template for this?
Make this changes in project urls.py:
from django.contrib import admin
admin.site.site_header = settings.HOME_TITLE
admin.site.site_title = settings.HOME_TITLE
Currently trying to make a social application. I created two apps Main and posts. My post app will handle all functionality for creating, deleting a post, list of posts. My Main app is my homepage which would display all posts, for example similar to a facebook's homepage.
Main app currently authenticates users and what not. I created views and template for my posts app and I now want to include it on the Main's app homepage. Not sure how to go out about doing this. Not asking for anyone to write up the code but at least give a structure on how to achieve this.
Basic Structure of the app:
--Main_app
--_views.py
--templates
--home.html
--posts_app
--_views.py
--templates
--posts.html
One of the files my posts_app views contains currently is:
def posts_list(request):
#return HttpResponse("<h1> List a posts. </h1>")
render(requests, "posts.html", {})
templates/posts.html contains this file:
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Posts template is working</h1>
</body>
</html>
And in my main_app templates/html:
{% if user.is_authenticated %}
<h1>Homepage</h1>
<!-- Posts template -->
{% include "posts/templates/posts.html" %}
{% endif %}
It made sense to me at the time to just import the template from the posts app to the main app and it would work. Did not work obviously, so I did a bit of research and couldn't find a definite solution, is there thing called templates inheritance, should import my views from posts into main. I'm not sure. Any help is appreciated.
Best way is to add a template in the project directory not in app, if you want to use that same template.
-myproject\
-Main_app\
-posts_app\
-templates\
-template_name.html
And in settings add,
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],# Add this line
'APP_DIRS': True,
........
In your views you can refer that directly like template_name.html
Other way is to create template in the directory like
myproject\
-Main_app\
-templates\
-Main_app\
mytemplate.html
-posts_app\
Now you can use that by referring Main_app\mytemplate.html
The first one is very efficient in this case.
What you can do is place your templates folder on the root of your project directory. So instead of having
--Main_app
--_views.py
--templates
--home.html
--posts_app
--_views.py
--templates
--posts.html
You can do
--Main_app
--_views.py
--posts_app
--_views.py
--templates
--SHARED.html
--main
--home.html
--posts
--posts.html
And in your views you could do something like:
return render(request, 'SHARED.html', context) # For shared
return render(request, 'posts/posts.html', context) # For template in posts
It would be best to create a separate templates directory in your root project folder. This way you can access html files in any app you wish. Your directory structure would look something like this:
.
├── blog
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── __init__.py
│ │ └── __pycache__
│ │ ├── 0001_initial.cpython-35.pyc
│ │ └── __init__.cpython-35.pyc
│ ├── models.py
│ ├── __pycache__
│ │ ├── admin.cpython-35.pyc
│ │ ├── apps.cpython-35.pyc
│ │ ├── __init__.cpython-35.pyc
│ │ ├── models.cpython-35.pyc
│ │ ├── urls.cpython-35.pyc
│ │ └── views.cpython-35.pyc
│ ├── tests.py
│ ├── urls.py
│ └── views.py
├── blog_project
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-35.pyc
│ │ ├── settings.cpython-35.pyc
│ │ ├── urls.cpython-35.pyc
│ │ └── wsgi.cpython-35.pyc
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── db.sqlite3
├── manage.py
├── Pipfile
├── Pipfile.lock
├── static
│ └── css
│ └── base.css
└── templates
├── base.html
├── home.html
├── post_detail.html
└── post_new.html
This is a simple blog I made using Django
It might be of some help if you want a reference.
As for cross loading templates via different apps, I would recommend structuring your project so that templates is a separate directory, this will benefit you in two ways:
It will be easier to totally separate front-end from back-end later on.
It will add modularity since it will decrease coupling between your apps.
Example Templates Director:
── templates
│ ├── main
│ ├── another_cool_app
│ ├── accounts
│ ├── posts
│ │ ├── timeline.html
│ │ ├── post_details.html
And so on.
For loading templates inside other templates you can simply:
{% include "posts/timeline.html" with posts_list=user.friends_posts %}
Happy coding.
I'm trying to create a website with a mobile application. I worked with web apps and REST apis separately but with this project I have to combine both.
My question is how do I have to combined this two sides of the projects.
Suposse I have a User model which has Tasks. Currently I have those models in an app called, for example, myRESTapp. But now, I want to be able to edit the tasks and take advantage of Django forms, but I'm not to do another application called webapp and implement forms based on models that are inmyRESTapi. I think it would not be a good practice considering the modularity of applications.
You can have multiple apps in one Django project. I usually have one main app that contains the main models and additional apps build on it.
Also, if you want to use apps in different projects, just make them reusable and put them into separate repositories (which you could add as requirements and install with pip).
As for a REST API, check out the great Django Rest Framework. It provides full CRUD functionality and in combination with crispy forms you can even add/modify data with a simple web UI.
An example of how I structured one of my projects:
base # basic application
├── __init__.py
├── admin
│ ├── __init__.py
├── ├── filters.py # custom filters for the Django Admin
│ └── models.py # enhancements for the Django Admin
├── apps.py
├── db_router.py # database router to distinguish between default and legacy DB
├── migrations # DB migrations (default & legacy)
├── models
│ ├── __init__.py
│ └── default.py # default models
│ └── legacy.py # legacy models
├── services
│ ├── __init__.py
│ ├── service1.py
│ ├── service2.py
├── tests.py
manage.py
my_api_app
├── __init__.py
├── apps.py
├── serializers.py # DRF Serializers
├── services.py # specific services for this app
├── tests.py
├── urls.py # API URLs
├── views.py # DRF ViewSets
my_web_app
├── __init__.py
├── apps.py
├── services.py # specific services for this app
├── static
├── ├── css
├── ├── img
├── ├── js
├── templates
├── tests.py
├── urls.py # website URLs
├── views.py # web views
projectname
├── __init__.py
├── settings
├── ├── __init__.py
│ ├── base.py # base settings for all environments
│ ├── dev.py # local dev settings (DEBUG, etc)
│ ├── prod.py # production settings (default)
│ └── test.py # test settings (sqlite DBs for testing)
├── urls.py # urlpatterns (API, website & admin)
├── wsgi.py
requirements
├── base.txt # requirements for all environments
├── dev.txt # local dev requirements
├── optional.txt # optional requirements for HTML doc creation
├── prod.txt # production requirements
└── test.txt # test env requirements
requirements.txt # default requirements (prod)
scripts
├── post-merge.sh # githook for deployment on server
├── doc.sh # create the code doc
├── coverage.sh # create the code doc
So I have my base app, that contains the models and everything that's used in both of the other apps and an app for the API and one for the website.
I come from PHP and Symfony, where I really fell in love with the idea of reusable services. That's how I keep logic out of my views and keep closer to an actual MVC (which is something Django isn't)
How can I import a custom template tag or filter in the interactive shell to see if the everything is working fine?
I have two machines behaving differently and I don't have a clue of how to do some debugging.
On the production machine I can't load a template filter, I get the error "Template library not found".
On the local machine everything works fine.
Importing filters like this:
from django.template import defaultfilters as filters
filters.date( date.today() )
Instead default filters you should import your custom filter:
from myApp.templatetags import poll_extras
poll_extras.cut( 'ello' )
Double check settings installed app in your production server.
If you're worried about typos, missing __init__.py problems or masked ImportErrors, you could just import the function. Assuming the following structure:
foo
├── bar
│ ├── __init__.py
│ ├── models.py
│ ├── static
│ │ └── ..
│ ├── templates
│ │ └── ..
│ ├── templatetags
│ │ ├── __init__.py
│ │ └── baz.py
│ ├── views.py
├── manage.py
└── foo
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
and the following contents of baz.py:
from django import template
register = template.Library()
#register.filter
def capitalize(value):
return value.capitalize()
you would just run
>>> from bar.templatetags import baz
>>> print baz.capitalize('test')
'test'