Django CheatSheet的代码
admin
2023-01-28 22:00:10
0

将写代码过程中较好的代码做个记录,下面代码段是关于Django CheatSheet的代码,希望能对大家也有帮助。

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.models import User
from django.http import HttpRequest
from django.conf import settings

request.GET.keys()
return render_to_response('content/auktionen/erstellen/wizard/zusammenfassung.html', locals())
return render('content/auktionen/erstellen/cc_wizard/zusammenfassung.html', locals(), request)
return HttpResponseRedirect('/login/?next=%s' % request.path)
request.GET.get('q', '')
username = request.POST['username']
request.method == 'POST'
HttpRequest.is_ajax()

p = get_object_or_404(Poll, pk=poll_id)
get_list_or_404()
return render_to_response('polls/detail.html', {'poll': p})
#------------- User ---------------------
if request.user.is_authenticated():

#User objects have two many-to-many fields: models.User. groups and user_permissions. User objects can access their related #objects in the same way as any other Django model:
myuser.groups = [group_list]
myuser.user_permissions = [permission_list]

from django.contrib.auth.decorators import user_passes_test

@user_passes_test(lambda u: u.has_perm('polls.can_vote'))
def my_view(request):

from django.contrib.auth.decorators import permission_required
def my_view(request):
    # ...
my_view = permission_required('polls.can_vote', login_url='/loginpage/')(my_view)

#-------------Model--------------------
cheese_blog = Blog.objects.get(name="Cheddar Talk")
Entry.objects.all()
Entry.objects.filter(pub_date__year=2006)
Blog.objects.filter(entry__author__name='Lennon')

>>> b = Blog.objects.get(id=1)
>>> b.entry_set.all() # Returns all Entry objects related to Blog.

#Many to Many
e = Entry.objects.get(id=3)
e.authors.all() # Returns all Author objects for this Entry.
e.authors.count()
e.authors.filter(name__contains='John')
a = Author.objects.get(id=5)
a.entry_set.all() # Returns all Entry objects for this Author.
#----------- Templates -------------

{% if user.is_authenticated %}
{% for group in user.groups.all %}
 {{group}}
{% endfor %}

settings.LOGIN_URL.

#-------------Forms-------------------
from django import forms
from django.forms import ModelForm

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    cc_myself = forms.BooleanField(required=False)

f = ContactForm({'subject': 'hello'})

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form

    return render_to_response('contact.html', {
        'form': form,
    })

#------
{{ form.as_p }} #------
{{ form.subject.errors }} {{ form.subject }}
#-----
{% for field in form %}
{{ field.errors }} {{ field.label_tag }}: {{ field }}
{% endfor %}

#----
{% with comment_form as form %} {% include "form_snippet.html" %} {% endwith %}

#---- class CommentForm(forms.Form): name = forms.CharField( widget=forms.TextInput(attrs={'class':'special'})) url = forms.URLField() comment = forms.CharField( widget=forms.TextInput(attrs={'size':'40'})) #----Model Forms----- # Create the form class. class ArticleForm(ModelForm): class Meta: model = Article # Creating a form to add an article. form = ArticleForm() # Creating a form to change an existing article. article = Article.objects.get(pk=1) form = ArticleForm(instance=article) # Create a form instance from POST data. f = ArticleForm(request.POST) # Save a new Article object from the form's data. new_article = f.save() # Create a form to edit an existing Article. a = Article.objects.get(pk=1) f = ArticleForm(instance=a).save() # Create a form to edit an existing Article, but use # POST data to populate the form. a = Article.objects.get(pk=1) f = ArticleForm(request.POST, instance=a) f.save() #------ class Musician(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField("Person's first name", max_length=30) poll = models.ForeignKey(Poll) toppings = models.ManyToManyField(Topping) gender = models.CharField(max_length=1, choices=(('M', 'Male'),('F', 'Female')) class Meta: ordering = ["horn_length"] verbose_name_plural = "oxen"

相关内容

热门资讯

德国总理:美国正在被伊朗羞辱 德国之声4月27日报道,德国总理默茨在访问一所学校时表示,在当前的持续冲突中,伊朗领导层正试图羞辱美...
理响中国|“长”歌以行,风云激... 光阴如梭,东方潮阔。这里是中国的长三角,世界的长三角。无论过去、现在还是未来,这片土地都因时代而生,...
白宫:特朗普及其国安团队开会讨... 新华社华盛顿4月27日电 美国白宫新闻秘书莱维特27日在记者会上证实,总统特朗普及其国家安全团队当天...
人民日报刊文:日本放开杀伤性武... 日本放开杀伤性武器出口推高地缘冲突风险(国际论坛)常思纯《人民日报》(2026年04月28日 第 0...
医疗保障法草案二审:明确生育保... 满足多样化健康保障需求本报记者 彭 波4月27日,医疗保障法草案二审稿提请十四届全国人大常委会第二十...
天津一景区发生自转旋翼机事故1... 澎湃新闻记者 吕新文中国民用航空华北地区管理局4月22日公布《豪客通航“10•1”天津长芦汉盐旅游区...
卡塔尔埃米尔与美国总统特朗普通... 当地时间24日,卡塔尔埃米尔塔米姆与美国总统特朗普通电话,重点就中东地区局势以及伊朗与美国谈判问题交...
男子30年前被扣押2859克黄... 澎湃新闻记者 王鑫家住辽宁省大连市的潘永嘉近日向澎湃新闻反映称,三十年前,他在大连周水子机场被盖州市...
商务部:取消反制欧盟两家金融机... 中华人民共和国商务部令二〇二六年 第1号鉴于欧盟已取消对中国两家金融机构的制裁措施,现公布《关于取消...
过去24小时共有5艘船只通过霍... 总台记者当地时间24日获悉,过去24小时内,共有5艘船只通过霍尔木兹海峡,其中包括一艘伊朗油轮。(总...