Various Usage Tips

linkaiyi
Follow

modify the first element of Queryset

The object must be assigned to a variable, otherwise can not be saved,

queryset.first() or
queryset[0] or
queryset[:1] slice of queryset
first_element = queryset.first()
first_element.attr = value
first_element.save()

intranet test for mobile devices and others

./manage.py runserver 192.168.1.23:8000

Python String manipulation

If you want to remove leading and ending spaces, use str.strip():

sentence = ' hello  apple'
sentence.strip()
>>> 'hello  apple'

If you want to remove all spaces, use str.replace():

sentence = ' hello  apple'
sentence.replace(" ", "")
>>> 'helloapple'

If you want to remove duplicated spaces, use str.split():

sentence = ' hello  apple'
" ".join(sentence.split())
>>> 'hello apple'

If you want to set all to lowercases
Use .lower() - For example:

s = "Kilometer"
print(s.lower())

Customize the ModelChoiceField display label per item

from django.forms import ModelChoiceField

class NamesChoiceField(ModelChoiceField):

    def label_from_instance(self, obj):
        return '{firstname} {lastname}'.format(firstname=obj.first_name, lastname=obj.last_name)

JsonResponse return with status code

JsonResponse normally returns HTTP 200, which is the status code for ‘OK’. In order to indicate an error, you can add an HTTP status code to JsonResponse as it is a subclass of HttpResponse:

response = JsonResponse({'status':'false','message':message}, status=500)

use celery under windows

celery -A <module> worker -l info -P gevent
celery -A [project-name] beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler

delete keys from dictionary

get the company instance’s data as a dict
data = companyinstance._dict.copy()

# remove the `id` and `origin_company` keys. don't need these
del data['id']
del data['origin_company_id']
# update the origin company instance
Company.objects.filter(id=company_instance.origin_company.id).update(**data)

send django mail for both html and text format with attachment

mail = EmailMultiAlternatives(subject, text_message, to=receiver, from_email=sender)
mail.attach_alternative(html_message, 'text/html')
if type == 'CERTIFICATE':
    certificate = UserCertificate.objects.filter(id=context['certificate_id']).first().certificate.path
    # content_type = mimetypes.guess_type(certificate.name)[0]
    mail.attach_file(certificate)
mail.send()

render string as template

Based on the the docs for using the template system:

from django.template import Template, Context

t = Template("My name is {{ my_name }}.")
c = Context({"my_name": "Adrian"})
t.render(c)

convert word (docx) or other office document to pdf

C:\Program Files (x86)\LibreOffice 4\program\soffice.exe" --headless --convert-to pdf "input_file_path" --outdir "output_dir_path"

save existing file to filefield

set field_name.name to file path

class Document(models.Model):
    file = FileField(upload_to=get_document_path)
    description = CharField(max_length=100)

doc = Document()
doc.file.name = 'path/to/file'  # must be relative to MEDIA_ROOT
doc.save()
# return the file absolute path
absolute_path = doc.file.path
Object has 0 attachments

Was this article helpful?

This article is viewed 188 times!

Recent Viewed Articles

0 Comments

Leave a Comment

Support