Django - vimlesh-verma16/Notes GitHub Wiki
Repo link https://github.com/Pierian-Data?tab=repositories
Repo link:: https://github.com/codingforentrepreneurs/eCommerce
Date : March 4 2025
python -m venv env
env\Scripts\activate
pip freeze > requirements.txt
pip3 install -r requirements.txt
conda create --name env_name python=3.6 [for specific version]
python -m django --version
conda create --name myDjangoEnv django
conda info --envs
conda env list (conda activate envname)
conda remove --name ecommerce --all
django-admin startproject first_project
python manage.py runserver
python manage.py startapp first_app
ADD first_app in INSTALLED_APPS [settings.py]
full Flow Client → Django URLs → Middleware (pre-processing) → View → Middleware (post-processing) → Response to Client
The name="index" Parameter This assigns a name (index) to this URL pattern, making it easier to reference in templates and redirects: < href="{% url 'index' %}">Home
If the URL changes, you only need to update urlpatterns without changing every reference in your templates.
BASE_DIR = Path(file).resolve().parent.parent
TEMPLATE_DIR=os.path.join(BASE_DIR,"templates")
STATIC_DIR=os.path.join(BASE_DIR,"static")
Now add TEMPLATE_DIR in Dirs
CRUD Operations: Create -- POST Retrieve/List/Search -- GET Update -- PUT/Patch/POST Delete -- Delete
Model class should always be named as: Product(ProductCategory) and not Products
python manage.py makemigrations
python manage.py migrate
Now go to admin and register your models admin.site.register(Webpage)
python manage.py shell (to test our models)
from first_app.models import Topic print(Topic.objects.all()) <QuerySet []> t= Topic(top_name = "Social Network") t.save() print(Topic.objects.all()) <QuerySet [<Topic: Social Network>]> quit()
python manage.py createsuperuser
vimlesh
vimmu1998
test
test
Now go to admin
http://127.0.0.1:8000/admin
Flow
Model -> Template -> View
first grab all the data view.py file in index function and now inject it to template and then set in url.py
When form method is POST use
<form method = "POST"> {% csrf_token %}
<input type = "text" class = "form-control" placeholder="Name" name = "FullName">
<button type = "Submit" class = "btn btn-default"> Submit</button>
</form>
This is how we can get content from frontend
<input type = "text" class = "form-control" placeholder="Name" name = "fullname">
"fullname" is dictionary.
if request.method == "POST":
print(request.POST)
print(request.POST.get("fullname"))
built in django form flow
Now Instead of using the entire Hardcoded Form, we can use django built in form.
1.
form.py file.
class ContactForm(forms.Form):
fullname = forms.CharField(
widget=forms.TextInput(
attrs={"class": "form-control", "placeholder": "Your Full Name"}
)
)
2.
from .form import ContactForm
contact_form = ContactForm()
context = {
"title": "Contact Page -> from view.html",
"content": "Welcome to contact page",
"form": contact_form,
}
if request.method == "POST":
# print(request.POST)
print(request.POST.get("fullname"))
3.
<form method = "POST"> {% csrf_token %}
{{ form }}
<button type = "Submit" class = "btn btn-default"> Submit</button>
</form>
4. Now you need to modify to get clean data
contact_form = ContactForm(request.POST or None)
if contact_form.is_valid():
print(contact_form.cleaned_data)
{'fullname': 'vimmu', 'email': '[email protected]', 'content': 'hello 3nd hit'}
5. validation check to raise error in frontend
def clean_email(self):
email = self.cleaned_data.get("email")
if "gmail.com" not in email:
raise forms.ValidationError("Email has to be gmail.com")
return email
def clean(self): (method is called by itself) all_cleaned_data = super().clean()
app_name = 'basic_app' urlpatterns = [ path('relative/',views.relative ,name='relative'), path('other/',views.other,name='other') ]
template tagging ->
'basic_app:other' dont give space here or you will get error
filter for django templates {{ username|default:"Guest" }} {{ "This is a long sentence."|truncatewords:3 }} {{ vimlesh| upper }}
pip install bcrypt pip install django[argon2]
in login
check whether the user is authicated or not
Add this arrays in settings.py
PASSWORD_HASHERS = [
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
"django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher",
"django.contrib.auth.hashers.Argon2PasswordHasher",
"django.contrib.auth.hashers.BCryptSHA256PasswordHasher",
"django.contrib.auth.hashers.ScryptPasswordHasher",
]
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
"OPTIONS": {"min_length": 9},
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
-
Now create a User:Model
-
Now register the model like this in admin.py of app
from basic_app.models import UserProfileInfo admin.site.register(UserProfileInfo)
-
Create a function in view.py file to handle request
-
Create a login.html and create a user_login fucntion in views.py
-
Create a user_login fun in view.py and do some code in main html file to show whether the user is loggin in or logged out
class Meta: flow models -> form -> admin
:: BACKEND
if form.is_valid():
print("üser logged in :", request.user.is_authenticated)
print(form.cleaned_data) # cleaned_data is a dictionary
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
def home_page(request):
context = {
"title": "Home Page -> from home.html",
"content": "Welcome to home page",
}
if request.user.is_authenticated:
context["premium_content"] = "YEAHhhhhhhh!"
return render(request, "home.html", context)
::FRONTEND
{% if premium_content %}
{% comment %} {% if request.user.is_authenticated %} {% endcomment %}
<div class='text-center'>
<h1> Premium Content </h1>
<p>{{ premium_content }}</p>
</div>
{% endif %}
# cleaned data is dictionary
def clean(self):
data = self.cleaned_data
password = self.cleaned_data.get("password")
password2 = self.cleaned_data.get("password2")
Creating a new user in register page
User = get_user_model()
username = form.cleaned_data.get("username")
email = form.cleaned_data.get("email")
password = form.cleaned_data.get("password")
User.objects.create_user(username, email, password)
Always add css file after bootstrap css or it will overwrite