Send data with POST-request wont work in Django with AJAX - python

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')

Related

no such table: users_customuser in Django

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)

How to access APP properties inside my endpoint view function in FastAPI?

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"}

Django - Determining how to split into apps based on functionality

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

Should django templates name for each app be unique?

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').

How to use app_context in Flask?

This is my structure. I have problem about implementing flask large application.
├─flasky
│ ├─app/
│ │ ├─templates/
│ │ ├─static/
│ │ ├─main/
│ │ │ ├─__init__.py
│ │ │ ├─errors.py
│ │ │ ├─forms.py
│ │ │ └─views.py
│ │ ├─__init__.py
│ │ ├─email.py
│ │ └─models.py
│ ├─migrations/
│ ├─tests/
│ │ ├─__init__.py
│ │ └─test*.py
│ ├─venv/
│ ├─requirements.txt
│ ├─config.py
│ └─manage.py
...
I encountered some problem When I was coding in email.py.
def send_email(to, subject, template, **kwargs):
msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
with the_app.app_context():
msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs)
thr = Thread(target=send_async_email, args=[app, msg])
thr.start()
return thr
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
I don't know how to call modules to implement the_app.app_context(). I hope that it can direct send_email function to get app/templates of location to be successful.
I found what the problem was. I needed to define a flask app in email.py:
import os
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
the_app = Flask(__name__, template_folder=tmpl_dir)
I encountered a new problem with werkzeug.routing.BuildError, and I am searching for a solution. I found "Flask error: werkzeug.routing.BuildError" mentioned my problem.
werkzeug.routing.BuildError
BuildError: ('index', {}, None)
Because views.py had a typo arg of url_for(), I should type 'main.index'. It's right.
#main.route('/', methods=['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit():
...
return redirect(url_for('main.index'))
return render_template('index.html',
form=form, name=session.get('name'),
known=session.get('known', False),
current_time=datetime.utcnow())
But it can't enable the feature of sending email. I found "Python Flask Email KeyError KeyError: 'mail'" mentioned my problem. I needed to downgrade to flask_mail==0.9.0, which solved the problems.

Categories

Resources