I'm developing a django app. It has three apps in it, each with it's own template directory and index.html file. But when I call view from the second app it picks up the template file from the first app rather than the second one.
Is it a must that every template name be unique?
my projects directory:
├───jobs
│ ├───migrations
│ ├───static
│ └───templates
├───job_portal
├───main_app
│ ├───migrations
│ ├───static
│ └───templates
├───project_static
│ ├───css
│ ├───fonts
│ ├───images
│ └───js
└───recruiters
├───migrations
├───static
│ ├───css
│ ├───fonts
│ ├───images
│ └───js
└───templates
In Django you can use templates with the same names for different apps. But you should add subfolders inside app's template directory like this:
my_app/templates/my_app/base.html
second_app/templates/second_app/base.html
Now in views you should include app name to the template name:
return render(request, 'my_app/base.html')
return render(request, 'second_app/base.html').
Related
I am trying to create an extended Custom User model that adds a level field of 0 to the User model which is not displayed on the form. But when I try to do this, I get the error no such table: users_customuser. I am new to Django. How can I implement what I described earlier and what I am doing wrong? Just in case I have done migrations...
Here is a structure of the project:
│ db.sqlite3
│ manage.py
│
├───ithogwarts
│ │ asgi.py
│ │ settings.py
│ │ urls.py
│ │ wsgi.py
│ │ __init__.py
│ │
│ └───__pycache__
│
├───main
│ │ admin.py
│ │ apps.py
│ │ models.py
│ │ tests.py
│ │ urls.py
│ │ views.py
│ │ __init__.py
│ │
│ ├───migrations
│ │ │ __init__.py
│ │ │
│ │ └───__pycache__
│ │
│ ├───static
│ │ └───main
│ │ ├───css
│ │ │ footer.css
│ │ │ header.css
│ │ │ index.css
│ │ │
│ │ ├───img
│ │ │
│ │ └───js
│ │ script.js
│ │
│ ├───templates
│ │ └───main
│ │ index.html
│ │ layout.html
│ │ level_magic.html
│ │
│ └───__pycache__
│
├───templates
│ └───registration
└───users
│ admin.py
│ apps.py
│ forms.py
│ models.py
│ tests.py
│ urls.py
│ utils.py
│ views.py
│ __init__.py
│
├───migrations
│ │ 0001_initial.py
│ │ __init__.py
│ │
│ └───__pycache__
│
├───static
│ └───users
│ └───css
│ login.css
│ register.css
│
├───templates
│ └───users
│ login.html
│ register.html
│
└───__pycache__
models.py:
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
level = models.IntegerField(default=0)
forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from .models import CustomUser
class RegisterUserForm(UserCreationForm):
username = forms.CharField(label="Имя", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-input',
'placeholder': 'введите ваше имя'}))
email = forms.CharField(label="Почта", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-control',
'placeholder': 'введите вашу почту'}))
password1 = forms.CharField(label="Пароль", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-input',
'placeholder': 'введите пароль'}))
password2 = forms.CharField(label="Подтверждение пароля", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-input',
'placeholder': 'подтвердите ваш пароль'}))
def __init__(self, *args, **kwargs):
super(UserCreationForm, self).__init__(*args, **kwargs)
for field_name in ['username', 'email', 'password1', 'password2']:
self.fields[field_name].help_text = None
class Meta:
model = CustomUser
fields = ('username', 'email', 'password1', 'password2')
views.py:
from django.contrib.auth import logout
from django.contrib.auth.views import LoginView
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import RegisterUserForm, LoginUserForm
class RegisterUser(CreateView):
form_class = RegisterUserForm
success_url = reverse_lazy('login')
template_name = 'users/register.html'
settings.py:
AUTH_USER_MODEL = 'users.CustomUser'
You have to make use of these two commands -
python manage.py makemigrations (It creates the migration)
python manage.py migrate (Actually creates the table in database)
I have written some functions with python in separate files. My task is to transform these functions into services using fastAPI and the services should return a JSON that says if the operation is executed correctly or not (a code and a message).
For example, I have a file sum.py and inside there's a function that sums two numbers and returns the result:
def sum_of_two_numbers(a,b):
tot = a+b
return tot
Let's say I want to create a service using fastAPI, do you know if I can import sum_of_two_numbers from sum and use TestClient to complete this task without modyfing the code or re-writing it?
In this example the function is short, but have in mind my functions are different. I needed one month to write them all and make the connection to the Oracle db. While reading the documentation of fastAPI, I understood I should modify all the syntax to adapt it for fastAPI.
So, in short can I do this with fastAPI by simply importing the functions and without changing all the functions syntax? Or do you know if is there an easier way to do it?
In a basic fastapi app structure you often have something like this:
Example taken from Bastien-BO/fastapi-RBAC-microservice, inspired by Kludex/fastapi-microservices and tiangolo/full-stack-fastapi-postgresql
.
├── app
│ ├── __init__.py
│ ├── main.py
│ ├── dependencies.py
│ └── routers
│ │ ├── __init__.py
│ │ ├── items.py
│ │ └── users.py
│ └── models
│ │ ├── __init__.py
│ │ ├── items.py
│ │ └── users.py
│ └── schemas
│ │ ├── __init__.py
│ │ ├── items.py
│ │ └── users.py
│ └── internal
│ │ ├── __init__.py
│ │ └── crud
| | | └── user.py
| | | └── item.py
Often in your internal files you have functions or classes that you can serve with routes.
Example of a user route with internal db function call:
# app/routers/users.py
from app.internal.crud.user import crud_user
#router.get("/", response_model=List[UserOut])
async def read_users(offset: int = 0, limit: int = 100, session: Session = Depends(get_db)):
users = crud_user.get_multi(session, offset=offset, limit=limit)
return users
# app/internal/crud/user.py
def crud_user():
#do db stuff here
In this example, your sum_of_two_numbers function would be in the internal folder and you would wrap it in a route like what is done in read_users.
You should follow the user guide or the advanced user guide (fit better to your need i believe) from fastapi official doc. Also take a look at tiangolo (fastapi creator) Base Project Generator. You will have a good example on how to create a strong base for your API.
First of all: I know, there are a few solutions for this online, but they wont work for me (because they use e.g. Jason or are just outdated)
I work on a project in Django and want to use ajax for one task:
I want to pass data, after it was processed by ajax, from my template file to my views file (with a POST request), to again make it visible in my templates file.
Templates-file --> Proccessed data --> POST-request --> views.py --> Template-file
But it just wont work for me.
My HTML-Templates-File:
...
<script type="text/javascript">
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
url: "/save",
data: {
'value': inputDataArray //I have already defined "inputDataArray" before
},
success: function (res, status) {
alert(res);
alert(status);
},
error: function (res) {
alert(res.status);
}
});
</script>
My views.py file:
def save(request):
if request.method == 'POST':
request_getdata = request.POST.get("value", None)
return render(request, "response.html", {"data":request_getdata})
urls.py file:
urlpatterns = [
path('', views.index , name='index'),
path('save', views.save , name='save'),]
So I try display it at "response.html"...
{{data}}
...but it just will reload the current page and does not pass any data to the response.html-file.
Does anyone knows what my error is here?
Thanks a lot in advance
P.S.: This is my project structure:
│ db.sqlite3
│ manage.py
│
├───myapp
│ │ admin.py
│ │ apps.py
│ │ models.py
│ │ tests.py
│ │ urls.py
│ │ views.py
│ │ __init__.py
│ │
│ ├───migrations
│ │ __init__.py
│ │
│ └───__pycache__
│ urls.cpython-39.pyc
│ views.cpython-39.pyc
│ __init__.cpython-39.pyc
│
├───static
│ └───myapp
│ └───css
│ index.css
│
├───templates
│ index.html
│ result.html
│
└───myapp
│ asgi.py
│ settings.py
│ urls.py
│ wsgi.py
│ __init__.py
│
└───__pycache__
...
Instead of
urlpatterns = [
path('', views.index , name='index'),
path('save', views.save , name='save'),]
Try :
urlpatterns = [
path('', myapp.views.index , name='index'),
path('save',myapp.views.save , name='save')
Here is my project structure:
│ .gitignore
│ README.md
│ requirements.txt
│ start.py
│
├───app
│ │ main.py
│ │
│ ├───apis
│ │ └───v1
│ │ │ __init__.py
│ │ │
│ │ │
│ │ ├───routes
│ │ │ │ evaluation_essentials.py
│ │ │ │ training_essentials.py
│ │ │
│ │
│ ├───models
│ │ │ request_response_models.py
│ │ │ __init__.py
│ │ │
This is what the outermost, start.py looks like:
import uvicorn
if __name__ == "__main__":
from fastapi import Depends, FastAPI
from app.apis.v1 import training_essentials, evaluation_essentials
app = FastAPI(
title="Some ML-API",
version="0.1",
description="API Contract for Some ML API",
extra=some_important_variable
)
app.include_router(training_essentials.router)
app.include_router(evaluation_essentials.router)
uvicorn.run(app, host="0.0.0.0", port=60096)
And, all my endpoints and viewfunctions have been created in training_essentials.py and evaluation_essentials.py
for example, this is what training_essentials.py looks like:
from fastapi import APIRouter
from fastapi import FastAPI, HTTPException, Query, Path
from app.models import (
TrainingCommencement,
TrainingCommencementResponse,
)
router = APIRouter(
tags=["Training Essentials"],
)
#router.post("/startTraining", response_model=TrainingCommencementResponse)
async def start_training(request_body: TrainingCommencement):
logger.info("Starting the training process")
## HOW TO ACCESS APP HERE?
## I WANT TO DO SOMETHING LIKE:
## some_important_variable = app.extra
## OR SOMETHING LIKE
## title = app.title
return {
"status_url": "some-status-url",
}
How do I access APP properties, its variables inside that viewfunction in my endpoint?
You can access the request.app as
from fastapi import Request
#router.post("something")
def some_view_function(request: Request):
fast_api_app = request.app
return {"something": "foo"}
Completely new to Django. I'm building a website where users can make profiles, search for other profiles, and view basic information.
I'm unsure about how to organize the apps. I want to following things on the navigation bar:
"About Us", "How it Works", "Join", "Login"
I know that users (join + login) will be its own app, but how would I bundle all of the information that will show up on the navigation bar? Will that just be one main app because it doesn't really do anything complex and really just presents text?
The concept of app in Django is that it does thing. For example if you are creating a website for school you have students as an app which manages students, an app for exams which only manages exams, grades etc. So your app should typically do one thing, if it does not break it down. The whole idea behind Django is having modular components which can act on their own.
In your case, what I would do is create an app called userapp. In userapp, I will have profile as a model containing username, password, fname, lname, picture, dob, hobbies etc.
On your home page, you can have separate flatpages for about us, how it works. These do not have to be app.
My project structure
├───.idea
├───firstapp
│ ├───migrations
│ │ └───__pycache__
│ └───__pycache__
├───myproj
│ └───__pycache__
├───secondapp
│ ├───migrations
│ │ └───__pycache__
│ └───__pycache__
├───static
│ ├───admin
│ │ ├───css
│ │ ├───fonts
│ │ ├───img
│ │ │ └───gis
│ │ └───js
│ │ ├───admin
│ │ └───vendor
│ │ ├───jquery
│ │ └───xregexp
│ ├───css
│ ├───fonts
│ ├───img
│ └───js
└───templates
└───firstapp