How can make join with django orm?

categroy_filter = CategoryFilter.objects.values('filter__filter_id', 'filter__filter_title').filter(
category_id=1,
filter__filter_title="xxxxx")
get_first_filter_id = categroy_filter[0:1][0]['filter__filter_id']
View More...

How Can Upload Files/Images using Django Form

# Create your views here.

def html_view(request):

   if request.method == 'GET':

       return render(request, "form.html")

dd = request.FILES['image_url']

 dd2 = request.FILES['image_url2']

 dd3 = request.FILES['image_url3']

 dd4 = request.FILES['image_url4']

 images = [dd, dd2, dd3, dd4]

 for image in images:

   ProductImage.objects.create('product'=request.POST['product'], 'image_url': image)

return render(request, "form.html")

View More...

Django Python Command

Verify Python Installation

>python

Check Python Version

>python --version

shortcut command

>python -V

>python3 -V

Check if PIP is Already Installed

>pip help

Installing PIP On Windows Machine

Download PIP get-pip.py

Copy PIP code and save file name is get-pip.py

PIP is a command-line program. When you install PIP, the PIP command is added to your system.

>python  get-pip.py

Check PIP Version

>pip --version

shortcut command

>pip -V

Upgrading PIP for Python on Windows Machine

>python -m pip install --upgrade pip

Downgrade PIP Version

>python -m pip install pip==18.1

Creating virtual environment for window Machine

>python -m virtualenv env

Activate virtual environment for window Machine

>env\scripts\activate

Create Virtual environment for ubuntu/linux machine

>python -m venv env

Activate virtual environment for ubuntu/linux machine

>source env/bin/activate

Deactivate virtual environment

>deactivate

Install django and mysqlclient sh > pip install django > pip install mysqlclient

Install Django

>python -m pip install django

shortcut command

>pip install django

If you wante to install Specific version of django

>pip install django==3.1.7

Check Django Version

>django-admin --version

Install mysqlclient for MYSQL Database

>pip install mysqlclient

if you got installation error in window 

 then download whl files from here

Download :  https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient

for window 32 bit

>pip install mysqlclient-1.4.6-cp38-cp38-win32.whl

for window 64 bit

>pip install mysqlclient-1.4.6-cp38-cp38-win_amd64.whl

Creating Django Project

>django-admin startproject demo_project

Creating Django APP

>django-admin startapp demo_app

Note: django-admin is equal to python manage.py command

i.e django-admin = python manage.py

>python manage.py startapp demo_app

Django Migration Command

>python manage.py makemigrations

>python manage.py migrate

Create Super User for Django admin

>python manage.py createsuperuser

Run Server for Django Project

>python manage.py runserver

Exporting data from a Django project

>python manage.py dumpdata > vishavjeet_data.json

If you want the exported file to have a readable JSON,

 then you can use "--indent".

>python manage.py dumpdata --indent=4 > dumped_data.json

Importing data from a Django project

>python manage.py loaddata < vishavjeet_data.json

View More...

Upload CSV file using Django

Djnago Project Setup for upload CSV file

Import CSV data into mysql database using django

# Step1: Installation or Setup

Creating virtual environment for window and activate

>python -m virtualenv env

>env\scripts\activate

Create Virtual environment for ubuntu/linux and activate

>python -m venv env

>source env/bin/activate

Install django and mysqlclient

> pip install django

> pip install mysqlclient

Creating Project and App

> django-admin startproject test_demo

> django-admin startapp dump_csv_import

#Step2: Change database connection in settings.py for mysql instead of default sqllite


DATABASES = {

'default':{

'ENGINE':'django.db.backends.mysql',

'NAME':'dump_tender',

'USER':'root',

'PASSWORD':'',

'HOST':'localhost',

'PORT':3306

}

}


#Step3: Create a model name DumpTender, which code given below


from django.db import models

import random

import string

from django.db.models.signals import pre_save

from django.utils.text import slugify

# Create your models here.

STATUS = (

('Active', 'Active'),

('Deactive', 'Deactive')

)

def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):

rand_str = ''.join(random.choice(chars) for _ in range(size))

return rand_str

def unique_slug_generator(instance, new_slug):

if new_slug is not None:

slug = new_slug.replace(" ", "-")

else:

slug = slugify(instance.product_title)

klass = instance.__class__

qs_exists = klass.objects.filter(product_slug=slug).exists()

if qs_exists:

rand_str = random_string_generator(4)

new_slug = f"{slug}-{rand_str}"

return unique_slug_generator(instance, new_slug)

return slug

class DumpTender(models.Model):

id = models.AutoField(primary_key=True, unique=True)

product_id = models.IntegerField()

product_sku = models.CharField(max_length=64)

product_title = models.CharField(max_length=128)

product_slug = models.SlugField(max_length=256, default='', null=True, blank=True)

product_price = models.FloatField(default=0.0)

quantity = models.IntegerField()

total_price = models.FloatField(default=0.0)

created_datetime = models.DateTimeField(auto_now_add=True)

updated_datetime = models.DateTimeField(auto_now=True)

status = models.CharField(max_length=32, default='Deactive', choices=STATUS)

def __str__(self):

return self.product_title

class Meta:

db_table = 'products'

ordering = ('-created_datetime',)

def dumptender_pre_save_receiver(sender, instance, *args, **kwargs):

if not instance.product_slug:

instance.product_slug = unique_slug_generator(instance, instance.product_title)

klass = instance.__class__

qs_exists = klass.objects.filter(product_slug=instance.product_slug).exists()

if qs_exists:

instance.product_slug = unique_slug_generator(instance, instance.product_title)

pre_save.connect(dumptender_pre_save_receiver, sender=DumpTender)


# Step4: Register our model in the admin.py file:

from django.contrib import admin

# Register your models here.

from dump_csv_import.models import DumpTender

admin.site.register(DumpTender)

# Step5: Let's migrate our model:

>python manage.py makemigrations

>python manage.py migrate

>python manage.py createsuperuser

# Step6: Now, let's write on our views.py file to create a function-based view:

import csv

from datetime import datetime

import io

from django.contrib import messages

from django.shortcuts import render

# Create your views here.

from dump_csv_import.models import DumpTender

def dump_tender(request):

prompt = {

'order': 'Product of the CSV should be product_id, product_sku, product_title, product_slug,'

'product_price, quantity, total_price, created_datetime, updated_datetime, status',

'products': DumpTender.objects.all()

}

if request.method == "GET":

return render(request, "dump_tender.html", prompt)

if not request.FILES['file'].name.endswith('.csv'):

messages.error(request, 'THIS IS NOT A CSV FILE')

if request.FILES['file'].name.endswith('.csv'):

data_set = request.FILES['file'].read().decode('UTF-8')

io_string = io.StringIO(data_set)

next(io_string)

i=0

for column in csv.reader(io_string, delimiter=',', quotechar="|"):

i+=1

_created_at = datetime.strptime(column[6].replace('/','-'), "%m-%d-%Y %H:%M")

_updated_at = datetime.strptime(column[6].replace('/', '-'), "%m-%d-%Y %H:%M")

_, created = DumpTender.objects.update_or_create(

product_id=int(column[0]),

product_sku=column[1],

product_title=column[2],

product_slug=column[3],

product_price=int(column[4]),

quantity=int(column[5]),

total_price=int(column[4]) * int(column[5]),

created_datetime=_created_at,

updated_datetime=_updated_at,

status=column[8]

)

context = {

'messages': [f' {i} Products uploaded successfully'],

'products': DumpTender.objects.all()

}

return render(request, "dump_tender.html", context)

# Step7: Create a templates folder in the app dump_csv_import

 directory and a new HTML file named dump_tender.html (dump_csv_import/templates/dump_tender.html)



<!DOCTYPE html>

<html lang="en">

<head>

<title>Dump Tender</title>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

</head>

<body>

<div class="container">

<h2>Upload Dump Tender Products</h2>

<p>Only CSV File accept</p>

{% if messages %}

{% for message in messages %}

<!-- | means OR operator-->

<div class="alert alert-success alert-dismissible">

<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>

<strong>{{message|safe}}</strong>

</div>

{% endfor %}

{% else %}

<div class="alert alert-success alert-dismissible">

<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>

<strong>{{order}}</strong>

</div>

<form class="form-inline" action="" method="POST" enctype="multipart/form-data">

{% csrf_token %}

<div class="form-group">

<label class="sr-only" for="file1">Upload a file:</label>

<input type="file" class="form-control" id="file1" name="file">

</div>

<button type="submit" class="btn btn-default">Upload</button>

</form>

{% endif %}

<h2>Products List</h2>

<table class="table">

<thead>

<tr>

<th>S.No</th>

<th>Name</th>

<th>Slug</th>

<th>Price</th>

<th>QTY</th>

<th>Total Price</th>

<th>Created Date</th>

<th>Updated Date</th>

<th>Status</th>

</tr>

</thead>

<tbody>

{% for product in products %}

<tr>

<td>{{ forloop.counter }} </td>

<td>{{product.product_title}}</td>

<td>{{product.product_slug}}</td>

<td>{{product.product_price}}</td>

<td>{{product.quantity}}</td>

<td>{{product.total_price}}</td>

<td>{{product.created_datetime}}</td>

<td>{{product.updated_datetime}}</td>

<td>{{product.status}}</td>

</tr>

{% endfor %}

</tbody>

</table>

</div>

</body>

</html>


#Step8: Add Templates directory in settings.py

TEMPLATES = [

{

......

'DIRS': [os.path.join(BASE_DIR, "templates"), ],

......

},

]

#Step9: Create urls.py files in app directory and write code which are given below.

from django.urls import path

from dump_csv_import import views

urlpatterns = [

path('', views.dump_tender),

]

#Step10: include urls path in projcect's urls.py(test_demo/urls.py)


from django.contrib import admin

from django.urls import path, include

urlpatterns = [

path('admin/', admin.site.urls),

path('dump-tender', include('dump_csv_import.urls')),

]


# Step11: Now, create a new product_demo.csv file and try to upload it:

product_id, product_sku, product_title, product_slug, product_price, quantity, total_price, created_datetime, updated_datetime, status


View More...