Django

Related

Django ImageField max_length error when uploading image

I'm using Django 4.2. I have a model whose fields containing ImageField, for example:class Example(models.Model) image = models.ImageField( blank=True, upload_to=my_image_path, )When I uploaded my image, I got this error from django: Ensure this filename has at most 100 characters (it has 107).Taken from the Django documentation:FileField instances are created in your database as varchar columns with a default max length of 100 characters. As with other fields, you can change the maximum length using the max_length argument.And note that ImageField is a subclass of FileField:Inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image.ImageField instances are created in your database as varchar columns with a default max length of 100 characters. As with other fields, you can change the maximum length using the max_length argument.Therefore, we just need to simply add max_length argument into the ImageField like ordinary CharField:class Example(models.Model) image = models.ImageField( blank=True, upload_to=my_image_path, max_length=500 )After this, don't forget to update it in your database:python manage.py makemigrations python manage.py migrate
2024-06-07 22:05:31

Keep user logged in using Django and Vue 3

The request.session object will automatically generate a cookie with the default name sessionid, which stores the session's session key value. When the session expires, the cookie will automatically removed. Only when the cookie is cleared can the logged in user log in again.Set the expiration time of the session through the backend, and when the time is up, you can see through the browser that the cookie will automatically disappear. Therefore, it is only necessary to set that the token value in the user's local storage disappears along with the cookie, and the duration of the user's login status can be controlled by setting the expiration time of the session, such as a seven day no login period.We may think that login status can be controlled based on cookies, but in reality, it is not easy to manipulate cookie values in Vue. In JavaScript, we can control cookies through instructions such as document. getElementId(). But in Vue, using the document instruction is likely to result in an empty return value. Therefore, controlling login status cannot be achieved through direct control of cookies.Therefore, we need to write an additional interface in the backend to verify the validity of the token and control the user's login status.Note: Cookies only affect whether users can log in again, and in Vue, it is inconvenient to use cookies to determine user login. Therefore, only tokens can be used to implement this. However, tokens and cookies are independent in the front-end, so if the cookie expires and the token is not cleared, it will result in continuous login. If the token is cleared and the cookie is not expired, it will cause the user to be unable to log in after the login status ends.
2024-05-02 18:25:10

Djano云服务器部署 uwsgi+nginx+https部署

Django启动服务器的命令runserver,其实也是启动了一个自带的uwsgi服务。如果想要一直在后台不停的运行django项目,需要部署uwsgi服务器。uwsgi安装官方文档:安装uWSGI — uWSGI 2.0 文档 (uwsgi-docs-zh.readthedocs.io)可以直接用pip安装uwsgi:pip install uwsgi在django项目根地址,即跟manage.py同目录下新建配置文件uwsgi.ini,如:mysite1/uwsgi.iniuwsgi.ini必须以[uwsgi]开头,内容如下:[uwsgi] chdir=/mysite1 module=mysite1.wsgi:application socket=127.0.0.1:8000 master=True pidfile=uwsgi.pid vacuum=True max-requests=5000 daemonize=uwsgi.logchdir为django项目根地址,socket为django启动服务器的ip地址,daemonize为日志地址。注意,每个django项目中自动生成一个mysite1/wsgi.py文件。接下来cd 到 uWSGI 配置文件所在目录,执行以下代码即可:uwsgi --ini uwsgi.iniuWSGI的运行说明无论是启动还是关闭,都要执行ps aux|grep 'uwsgi’确认是否符合预期当uwsgi启动后,当前django项目的程序已变成后台守护进程,在关闭当前终端时此进程也不会停止启动成功后,进程在后台执行,所有日志均输出在配置文件所在目录的uwsgi.log中Django中代码有任何修改,都需要重启uwsgi(重启即为先关闭,再开启)配置好uwsgi服务后,还需要进一步配置nginx服务器,原因见为什么有了uwsgi 还要 nginx 服务器?和Nginx服务器反向代理。为了更高的加密性,我们可以使用nginx配置HTTPS协议。以下我们以腾讯云服务器为例,通过nginx配置HTTPS:首先找到/etc/nginx/conf.d,然后创建新文件django_nginx.confsudo vim django_nginx.conf接下来输入以下设置# 这种写法比较方便配合负载均衡 upstream backend { # 这里的IP端口即Django项目的IP端口 server 127.0.0.1:8000; # 如果uwsgi使用的本地文件,此处写法参考 # server unix:/path/to/your/mysite/mysite.sock; } server { listen 443 ssl; autoindex on; client_max_body_size 1024m; #请填写绑定证书的域名 server_name example.com; #请填写证书文件的相对路径或绝对路径 ssl_certificate example.com_bundle.crt; #请填写私钥文件的相对路径或绝对路径 ssl_certificate_key example.com.key; ssl_session_timeout 5m; #请按照以下协议配置 ssl_protocols TLSv1.2 TLSv1.3; #请按照以下套件配置,配置加密套件,写法遵循 openssl 标准。 ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE; ssl_prefer_server_ciphers on; location /static { alias /path/to/your/mysite/static/; } location / { include uwsgi_params; uwsgi_pass backend; } }最后重新加载nginx,就大功告成啦!sudo nginx -s reload
2024-05-15 10:46:48

为什么有了uwsgi 还要 nginx 服务器?

有关nginx的简单介绍,详见Nginx服务器反向代理。uwsgi是python的一个通信协议,同时也是一种web服务器,而nginx则是高性能反向代理的web服务器。在Django项目服务器部署中,uwsgi几乎是不可替代的。然而部署好了uwsgi,其实django接口已经能够响应请求,为什么还要额外配置nginx服务器?因为,相比于直接将真实地址暴露在公网上,在外面套一层nginx安全性更高,具体如下:安全问题,程序不能直接被浏览器访问到,而是通过nginx,nginx只开放某个接口,uwsgi本身是内网接口,这样运维人员在nginx上加上安全性的限制,可以达到保护程序的作用。负载均衡问题,一个uwsgi很可能不够用,即使开了多个work也是不行,毕竟一台机器的cpu和内存都是有限的,有了nginx做代理,一个nginx可以代理多台uwsgi完成uwsgi的负载均衡。静态文件处理效率问题,用django或是uwsgi这种东西来负责静态文件的处理是很浪费的行为,而且他们本身对文件的处理也不如nginx好,所以整个静态文件的处理都直接由nginx完成,静态文件的访问完全不去经过uwsgi以及其后面的东西。这就是这几者之间的关系。
2024-05-15 00:06:04

How to split views.py to several smaller files in Django

When your views.py is too large, it becomes much more difficult to manage your code. So you might want to split views.py into several subviews, each of which contains a single sort of views.To split views.py, you could follow the following steps. Your original views.py might look like this:import ... def view1(request): pass def view2(request): passNow, create a new folder subviews aside with views.py , i.e. /Django/mysite/MyAPI/subviews. Next, create __init__.py, viewsa.py, and viewsb.py in the folder subviews to form the following folder/file structure :subviews/ __init__.py subviews1.py subviews2.pysubviews1.py :from .views import * def view1(request): passsubviews2.py :from .views import * def view2(request): pass__init__.py :from subviews1 import * from subviews2 import *Then this would work the same as a single views.py file. Don't forget to change the urls.py file before you reloading Django.
2024-05-01 14:11:30

Django combine multiple QuerySets

Suppose that we have two different models.class Author(models.Model): name = models.CharField(max_length=50) class Article(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author)In certain circumstances, you might want to merge two querysets into one queryset. For example, you may want to combine Author.objects.all() and Article.objects.all(). You could accomplish this by pure python method itertools.chain, or using Django's inbuilt queryset method union . However, these are no more intuitive than combining two querysets directly.We recommend to use the package django-querysetsequence. To combine Author.objects.all() and Article.objects.all(), you just need to call QuerySetSequence directly :from queryset_sequence import QuerySetSequence authors = Author.objects.all() articles = Article.objects.all() authors_articles = QuerySetSequence(authors, articles)If you have multiple models A, B, C, D, E, F , and have an array data containing their querysets, e.g. A.objects.all(), B.objects.all() , etc. To combine querysets in an array, you could make use of python's inbuilt method reduce :from functools import reduce from queryset_sequence import QuerySetSequence q = reduce(QuerySetSequence, data)
2024-05-03 00:33:49

Django change an existing field to foreign key

I have a Django model that used to look like this:class Car(models.Model): manufacturer_id = models.IntegerField()There is another model called Manufacturer that the id field refers to. However, I realized that it would be useful to use Django's built-in foreign key functionality, so I changed the model to this:class Car(models.Model): manufacturer = models.ForeignKey(Manufacturer)This change appears to work fine immediately, queries work without errors, but when I try to run migrations, Django outputs the following:- Remove field manufacturer_id from car - Add field manufacturer to carDoing this migration would clear all the existing relationships in the database, so I don't want to do that. I don't really want any migrations at all, since queries like Car.objects.get(manufacturer__name="Toyota") work fine. I would like a proper database foreign key constraint, but it's not a high priority.So my question is this: Is there a way to make a migration or something else that allows me to convert an existing field to a foreign key? I cannot use --fake since I need to reliably work across dev, prod, and my coworkers' computers.内容来源于 Stack Overflow, 遵循 CCBY-SA 4.0 许可协议进行翻译与使用。原文链接:Django change an existing field to foreign key
2024-08-17 16:03:04

Django count RawQuerySet

QuestionHay, I'm using django 1.2 and i want to know how to count rows from a raw queryset(RawQuerySet).The traditional .count() method doesn't work.Heres my queryquery = "SELECT *, ((ACOS(SIN(%s * PI() / 180) * SIN(lat * PI() / 180) + COS(%s * PI() / 180) * COS(lat * PI() / 180) * COS((%s - lon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance FROM app_car WHERE price BETWEEN %s AND %s HAVING distance<=%s ORDER BY distance ASC" cars = Car.objects.raw(query, [lat, lat, lon, min_price, max_price, miles]) return HttpResponse( cars )And its returningCar_Deferred_model_id_user_id objectAny ideas?Answer 1Use the 'len()' function. This would give:query = "SELECT *, ((ACOS(SIN(%s * PI() / 180) * SIN(lat * PI() / 180) + COS(%s * PI() / 180) * COS(lat * PI() / 180) * COS((%s - lon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance FROM app_car WHERE price BETWEEN %s AND %s HAVING distance<=%s ORDER BY distance ASC" cars = Car.objects.raw(query, [lat, lat, lon, min_price, max_price, miles]) return HttpResponse(len(list(cars))Aside: there's some useful information on the Django 1.2 Model.objects.raw() method at: http://djangoadvent.com/1.2/smoothing-curve/ [Looks like that site might have expired, but the Internet Archive has it at: http://web.archive.org/web/20110513122309/http://djangoadvent.com/1.2/smoothing-curve/ ]The content is from StackOverflow which is translated and used in accordance with the CCBY-SA 4.0 license agreement. Original link: Django count RawQuerySet
2024-08-21 18:49:27

django object has no attribute 'count'

QuestionI am learning django / python and I am stuck on an issue.I have a view: create_document.py in which I want to count the number of name details from a models class: NameDetails.I cannot get the correct syntax!Here is my models.py code:class NameDetails(FillableModelWithLanguageVersion): user = models.ForeignKey(User) name_details_prefix_title = models.CharField(null=True, blank=True, max_length=25) name_details_first_name = models.CharField(null=False, blank=False, max_length=50) name_details_middle_name = models.CharField(null=True, blank=True, max_length=100) ....Here is my create_document.py code in which I have a django wizard. I want to make sure the user has more than 1 name before they can create a document:from app_name.core.models import NameDetails class CreateDocumentWizard(SessionWizardView): template_name = 'documents/document_create.html' form_list = [ core_forms.CreateDocumentWizardForm01, core_forms.CreateDocumentWizardForm02, core_forms.CreateDocumentWizardForm03, core_forms.CreateDocumentWizardForm04, ] def get_form_kwargs(self, step=None): kwargs = super(CreateDocumentWizard, self).get_form_kwargs(step) kwargs.setdefault('user', self.request.user) return kwargs def get_context_data(self, form, **kwargs): name_details_count = NameDetails(user=self.request.user).count() if name_details_count < 1: return redirect(settings.MENU_DETAIL_LINK_NAME_DETAILS)When I use the line to determine the count of NameDetails of the user: name_details_count = NameDetails(user=self.request.user).count(), I get the following error:NameDetails' object has no attribute 'count'I have tried many permutations, but I am stuck.Answer 1It should be like that in your get_context_data function:name_details_count = NameDetails.objects.filter(user=self.request.user).count()Answer 2At the moment you're creating a brand new NameDetails instance with request.user as the user. Instead, you should query the database for existing NameDetails for the current user, and count them. You can query the database through NameDetails.objects:name_details_count = NameDetails.objects.filter(user=self.request.user).count()The content is from StackOverflow which is translated and used in accordance with the CCBY-SA 4.0 license agreement. Original link: django object has no attribute 'count'
2024-08-21 17:45:15
Get connected with us on social networks! Twitter

©2024 Guangzhou Sinephony Technology Co., Ltd All Rights Reserved