python第一百零七天-- Django 基础 2

本文深入讲解了Django框架的工作原理,包括请求处理流程、视图函数、模板渲染、ORM操作等核心内容,并提供了详细的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、Django请求的生命周期

路由系统 -> 试图函数(获取模板+数据=》渲染) -> 字符串返回给用户

2、路由系统

/index/ -> 函数或类.as_view()
/detail/(\d+) -> 函数(参数) 或 类.as_view()(参数)
/detail/(?P<nid>\d+) -> 函数(参数) 或 类.as_view()(参数)
/detail/ -> include("app01.urls")
/detail/ name='a1' -> include("app01.urls")
- 视图中:reverse
- 模板中:{% url "a1" %}

3、视图

FBV:函数
def index(request,*args,**kwargs):
..

CBV:类
class Home(views.View):

def get(self,reqeust,*args,**kwargs):
..

获取用户请求中的数据:
request.POST.get
request.GET.get
reqeust.FILES.get()

# checkbox,
........getlist()

request.path_info


文件对象 = reqeust.FILES.get()
文件对象.name
文件对象.size
文件对象.chunks()

# <form 特殊的设置></form>


给用户返回数据:
render(request, "模板的文件的路径", {'k1': [1,2,3,4],"k2": {'name': 'xxx','age': 73}})
redirect("URL")
HttpResponse(字符串)


4、模板语言
render(request, "模板的文件的路径", {'obj': 1234, 'k1': [1,2,3,4],"k2": {'name': 'ssss','age': 73}})
 <html>
   
   <body>
      <h1> {{ obj }} </h1>
      <h1> {{ k1.3 }} </h1>
      <h1> {{ k2.name }} </h1>
      {% for i in k1 %}
         <p> {{ i }} </p>
      {% endfor %}
      
      {% for row in k2.keys %} #keys 通过字典键  取值
         {{ row }}
         {{forloop.counter}}#从1开始计数
         {{forloop.counter0}}#从0开始计数
         {{forloop.revcounter }}#从1开始计数倒降序
         {{forloop.revcounter0 }}#从0开始计数倒降序
         {{forloop.first}}#是否第一个循环
         {{forloop.last}}#是否最后一个循环
         {{forloop.parentloop}}#父级的循环计数
      {% endfor %}
      
      {% for row in k2.values %}  #直接取 字典值
         {{ row }}
      {% endfor %}
      
      {% for k,v in k2.items %} #取键和值的元组模式
         {{ k }} - {{v}}
      {% endfor %}
      
   </body>
   </html>

 



5、ORM

a. 创建类和字段
      class User(models.Model):
         age = models.IntergerFiled()#整数不用加长度
         name = models.CharField(max_length=10)#字符长度
         
      Python manage.py makemigrations
      python manage.py migrate
      
      # settings.py 注册APP

 



b. 操作

         models.User.objects.create(name='qianxiaohu',age=18)#方法一

         dic = {'name': 'xx', 'age': 19}#方法二
         models.User.objects.create(**dic)

         obj = models.User(name='qianxiaohu',age=18)#方法三
         obj.save()

 models.User.objects.filter(id=1).delete()

 


models.User.objects.filter(id__gt=1).update(name='alex',age=84)
dic = {'name': 'xx', 'age': 19}
models.User.objects.filter(id__gt=1).update(**dic)

 


      models.User.objects.filter(id=1,name='root')
         models.User.objects.filter(id__gt=1,name='root')#大于
         models.User.objects.filter(id__lt=1)#小于
         models.User.objects.filter(id__gte=1)#大于等于
         models.User.objects.filter(id__lte=1)#小于等于
         
         models.User.objects.filter(id=1,name='root')#条件  直接写入

         dic = {'name': 'xx', 'age__gt': 19}#通过定义字典
         models.User.objects.filter(**dic)
         
         v1 = models.Business.objects.all()
         # QuerySet ,内部元素都是对象
         
         # QuerySet ,内部元素都是字典
         v2 = models.Business.objects.all().values('id','caption')
         # QuerySet ,内部元素都是元组
         v3 = models.Business.objects.all().values_list('id','caption')
      
         # 获取到的一个对象,如果不存在就报错
         models.Business.objects.get(id=1)
         对象或者None = models.Business.objects.filter(id=1).first()

 




外键:
v = models.Host.objects.filter(nid__gt=0)
v[0].b.caption ----> 通过.进行跨表

filter(b__caption)# 条件查询跨表时用 __ 双下划线




外键:
示例:
     class UserType(models.Model):
              caption = models.CharField(max_length=32)


            id  caption
         # 1,普通用户
         # 2,VIP用户
         # 3, 游客
            
         class User(models.Model):
            age = models.IntergerFiled()
            name = models.CharField(max_length=10)#字符长度
            # user_type_id = models.IntergerFiled() # 约束,
            user_type = models.ForeignKey("UserType",to_field='id') # 约束,外键
      
           name age  user_type_id     
         # 用户1  18     3  #表示用户1 为游客
         # 用户2  18     2 #表示用户2 为VIP用户
         # 用户3  18     2

窗口相对定位 开启相对定位 使用父级相对定位 单用 开始显示绝对定位
position: fixed relative absolute




Ajax

$.ajax({
url: '/host',
type: "POST",
data: {'k1': 123,'k2': "root"},
success: function(data){
// data是服务器端返回的字符串
var obj = JSON.parse(data);
}
})
$.get(url='xx',data='xxx')
$.getJson
$.post


建议:永远让服务器端返回一个字典

return HttpResponse(json.dumps(字典))




多对多:
创建多对多:
方式一:自定义关系表
         class Host(models.Model):
            nid = models.AutoField(primary_key=True)
            hostname = models.CharField(max_length=32,db_index=True)
            ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
            port = models.IntegerField()
            b = models.ForeignKey(to="Business", to_field='id')
         # 10
         class Application(models.Model):
            name = models.CharField(max_length=32)
         # 2
         
         class HostToApp(models.Model):
            hobj = models.ForeignKey(to='Host',to_field='nid')
            aobj = models.ForeignKey(to='Application',to_field='id')

         操作关联表与其他相同
         # HostToApp.objects.create(hobj_id=1,aobj_id=2)
            
            
            
   
            
            
      方式二:自动创建关系表
         class Host(models.Model):
            nid = models.AutoField(primary_key=True)
            hostname = models.CharField(max_length=32,db_index=True)
            ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
            port = models.IntegerField()
            b = models.ForeignKey(to="Business", to_field='id')
         # 10
         class Application(models.Model):
            name = models.CharField(max_length=32)
            r = models.ManyToManyField("Host")#自动关联,创建 与
            
         无法直接对第三张表进行操作
         
         obj = Application.objects.get(id=1)#取到一个记录对象
         obj.name
         
         # 第三张表操作
         obj.r.add(1)#这个记录对应的关系
         obj.r.add(2)
         obj.r.add(2,3,4)
         obj.r.add(*[1,2,3,4])
         
         obj.r.remove(1)
         obj.r.remove(2,4)
         obj.r.remove(*[1,2,3])
         
         obj.r.clear()#清楚当前对象所有对应关系
         
         obj.r.set([3,5,7])#修改当前对象的对应关系
         
         # 所有相关的主机对象“列表” QuerySet
         obj.r.all() #获取当前对象 的所有对应关系

 




转载于:https://www.cnblogs.com/uge3/p/7397096.html

就是普通的python文件运行报错:/usr/bin/python3 /Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pydev/pydevd.py --multiprocess --qt-support=auto --client 127.0.0.1 --port 64866 --file /Users/shenxin/Desktop/176All/project/jiaoben/scriptproject/great/takealot_review250609amz/takealot_review_20250609amz.py AmazonCategories_20241018.csv _tal AmazonCategories_20241018_1.csv > outputamz.log 2>&1 & Connected to pydev debugger (build 223.8836.43) /Users/shenxin/Desktop/176All/project/jiaoben/scriptproject/great/takealot_review250609amz/takealot_review_20250609amz.py:1: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp /Library/Python/3.9/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020 warnings.warn( Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Library/Python/3.9/site-packages/emoji/__init__.py", line 1, in <module> from .models import Emoji as emoji_class File "/Library/Python/3.9/site-packages/emoji/models.py", line 14, in <module> from . import settings File "/Library/Python/3.9/site-packages/emoji/settings.py", line 5, in <module> EMOJI_IMG_TAG = getattr(settings, 'EMOJI_IMG_TAG', ( File "/Users/shenxin/Library/Python/3.9/lib/python/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/Users/shenxin/Library/Python/3.9/lib/python/site-packages/django/conf/__init__.py", line 60, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting EMOJI_IMG_TAG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. python-BaseException Traceback (most recent call last): File "/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pydev/_pydevd_bundle/pydevd_xml.py", line 161, in _get_type def _get_type(self, o, type_object, type_name): File "/Users/shenxin/Library/Python/3.9/lib/python/site-packages/django/utils/functional.py", line 254, in inner def inner(self, *args): File "/Users/shenxin/Library/Python/3.9/lib/python/site-packages/django/conf/__init__.py", line 51, in _setup def _setup(self, name=None): django.core.exceptions.ImproperlyConfigured: Requested settings, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Process finished with exit code 1
06-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值