小编nas*_*yn8的帖子

什么时候在Django中使用get,get_queryset,get_context_data?

我最近了解到,当您特别想要执行默认视图以外的操作时,应该覆盖get方法:

class ExampleView(generic.ListView):
    template_name = 'ppm/ppm.html'

    def get(self, request):
        manager = request.GET.get('manager', None)
        if manager:
            profiles_set = EmployeeProfile.objects.filter(manager=manager)
        else:
            profiles_set = EmployeeProfile.objects.all()
            context = {
                'profiles_set': profiles_set,
                'title': 'Employee Profiles'
            }
Run Code Online (Sandbox Code Playgroud)

这很简单,但什么时候应该使用get_queryset或get_context_data来获取?对我来说,他们似乎基本上做同样的事情,或者我只是错过了什么?我可以一起使用它们吗?这对我来说是一个混乱的主要原因.

所以重申:在什么情况下我会使用get_queryset或get_context_data,反之亦然?

python django

55
推荐指数
2
解决办法
4万
查看次数

问题理解C中的块

我正在学习用C编程,我正在做一个练习,需要我编写一个程序来打印Isosceles三角形.

#include <stdio.h>

int main()
{
    int col, row;

    for(col = 0; col < 6; col++)
    {
       for(row = 0; row <= col; row++)
       {
          putchar('*');
            putchar('\n');
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码在一行上打印(*)21次.因此,经过几分钟的反复试验后,我删除了内部for循环的内括号.

#include <stdio.h>

int main()
{
    int col, row;

    for(col = 0; col < 6; col++)
    {
       for(row = 0; row <= col; row++)
          putchar('*');
            putchar('\n');
    }
}
Run Code Online (Sandbox Code Playgroud)

我终于实现了我想要的结果.

我的问题是:内部for for循环的内括号{}如何影响结果的打印方式?为什么第一组代码在一行上打印*也是21次?

我仔细查看了整本书,无法找到合理的解决方案来解决为什么内部for循环上的{}影响输出.

c syntax for-loop

3
推荐指数
1
解决办法
148
查看次数

超过最大递归深度,保存方法,Django

尝试使用 Python3.4 使用 QR-code 5.3 生成 QR 码时。我面临几个问题:

起初我使用 io.StringIO 并且我得到了一个预期字符串参数,得到了 'bytes'错误消息。所以我然后将 io.StringIO 更改为 io.BytesIO。然后我得到了另一个错误,它是'_io.BytesIO' 对象没有属性 'len'所以为了获得我使用的对象的长度buffer.getbuffer().nbytes但现在我得到了最大递归深度超过和它生成了 298 张二维码图像,而不仅仅是一张。任何想法我做错了什么?

from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
from django.core.files.uploadedfile import InMemoryUploadedFile

import random
import qrcode
import io
import sys

from PIL import Image

import pdb;


def qrcode_location(instance, filename):
    return '%s/qr_codes/%s' % (instance.user.username, filename)


# Create your models here.
class EmployeeProfile(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,  on_delete=models.CASCADE)
    qrcode = …
Run Code Online (Sandbox Code Playgroud)

python django

3
推荐指数
1
解决办法
3038
查看次数

通过JSON发送文件而不是上传到服务器,Django

我有一个应用程序,当前允许用户上传文件,它将文件保存在Web服务器上.我的客户现在决定使用第三方云托管服务来满足他们的文件存储需求.该公司有自己的API用于在其服务器上进行CRUD操作,因此我编写了一个脚本来测试他们的API,并将一个文件作为base64编码的JSON有效负载发送到API.该脚本工作正常但现在我仍然坚持我应该如何将这个功能实现到Django.

json_testing.py

import base64
import json
import requests
import magic

filename = 'test.txt'

# Open file and read file and encode it as a base64 string
with open(filename, "rb") as test_file:
    encoded_string = base64.b64encode(test_file.read())

# Get MIME type using magic module
mime = magic.Magic(mime=True)
mime_type = mime.from_file(filename)

# Concatenate MIME type and encoded string with string data
# Use .decode() on byte data for mime_type and encoded string
file_string = 'data:%s;base64,%s' % (mime_type.decode(), encoded_string.decode())
payload = {
    "client_id": 1,
    "file": …
Run Code Online (Sandbox Code Playgroud)

python django

3
推荐指数
1
解决办法
2454
查看次数

为什么我会收到此错误?"ch1.c:12:错误:被称为对象'a - b'不是函数"

我正在为一本编程书做一个简单的挑战,该编程书要求使用单个printf()函数输出公式f =(a - b)(x - y)的结果.我得到这个错误:"错误:被称为对象'a - b'不是一个函数"

这是代码:

#include <stdio.h>

 main()
 {
       int a = 5;
       int b = 1;
       int x = 10;
       int y = 5;

       printf("\nThe result of f = %d\n", (a-b)(x-y));
}
Run Code Online (Sandbox Code Playgroud)

c

1
推荐指数
1
解决办法
485
查看次数

我该如何压缩这个Jquery代码?

我已经学习了一段时间的Jquery,并且我创建了一个脚本,当我点击div(#click)时,另一个div(#slide)将向下滑动并显示内部的内容.下面是我为此编写的脚本,但我觉得它太重复了.必须有更好的方法来实现相同的结果,但代码要少得多.我用谷歌搜索但未能找到任何解决方案,任何人的想法?

$(document).ready(function(){
    $("#click").click(function(){
        $("#slide").slideToggle("slow");
    });
    $("#click2").click(function(){
        $("#slide2").slideToggle("slow");
    });
   $("#click3").click(function(){
        $("#slide3").slideToggle("slow");
    });
   $("#click4").click(function(){
        $("#slide4").slideToggle("slow");
   });
   $("#click5").click(function(){
        $("#slide5").slideToggle("slow");
   });
   $("#click6").click(function(){
        $("#slide6").slideToggle("slow");
   });
   $("#click7").click(function(){
        $("#slide").slideToggle("slow");
   }); 
   $("#click8").click(function(){
        $("#slide8").slideToggle("slow");
   });  
   $("#click9").click(function(){
        $("#slide9").slideToggle("slow");
   });  
   $("#click10").click(function(){
        $("#slide10").slideToggle("slow");
   });
   $("#click11").click(function(){
        $("#slide11").slideToggle("slow");
   });  
   $("#click12").click(function(){
        $("#slide12").slideToggle("slow");
   });  
   $("#click13").click(function(){
        $("#slide13").slideToggle("slow");
   });
   $("#click14").click(function(){
        $("#slide14").slideToggle("slow");
   }); 
   $("#click15").click(function(){
        $("#slide15").slideToggle("slow");
   });  
    $("#click16").click(function(){
        $("#slide16").slideToggle("slow");
   });  
    $("#click17").click(function(){
        $("#slide17").slideToggle("slow");
    });
    $("#click18").click(function(){
        $("#slide18").slideToggle("slow");
    });  
    $("#click19").click(function(){
        $("#slide19").slideToggle("slow");
    });   
});
Run Code Online (Sandbox Code Playgroud)

我知道这很难看,但我唯一的线索是使用关键字(this),但我不知道如何实现它.所以非常感谢帮助.

这是HTML:

    <div id="main">
        <div class="content">
            <img src="images/training.jpg" alt="banner" class="pic"/>
            <h3>10 Hour Construction</h3>
            <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; This <span class="theme">10 Hour</span> program is …
Run Code Online (Sandbox Code Playgroud)

javascript jquery

1
推荐指数
1
解决办法
177
查看次数

在django模板中显示外键值

我已经查看了类似的问题,无法找到合适的解决方案,或者我错过了什么?我有两个模型(SafetyCourse和SafetyCourseTaken)我有一个外键关系,从"安全课程"到安全课程,如下所示:

models.py

class SafetyCourse(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    name = models.CharField(max_length=128, unique=True)

    def __str__(self):
        return self.name


class SafetyCoursesTaken(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    profile = models.ForeignKey(EmployeeProfile, on_delete=models.CASCADE)
    course = models.ForeignKey(SafetyCourse, on_delete=models.CASCADE, related_name='course_name')
    conducted_date = models.DateTimeField(null=True, blank=True)
    expiration_date = models.DateTimeField(null=True, blank=True)

    class Meta:
        verbose_name_plural = 'Safety Courses Taken'
Run Code Online (Sandbox Code Playgroud)

views.py

class ManageSafetyCourseTakenView(LoginRequiredMixin, generic.ListView):
    login_url = reverse_lazy('users:login')
    model = SafetyCoursesTaken
    template_name = 'ppm/courses-taken.html'
    paginate_by = 10

    # override get_queryset to only show training related to employee profile
    def get_queryset(self):
        pk = self.kwargs['pk']
        return SafetyCoursesTaken.objects.filter(profile_id=pk) …
Run Code Online (Sandbox Code Playgroud)

python django django-templates django-models

1
推荐指数
1
解决办法
2866
查看次数

password_change_done 未在 Django 中使用自定义模板

我使用 Django 的auth_views.password_change来允许用户更改密码。它使用自定义模板并且运行良好,但我遇到的问题是它重定向到 Django 的密码更改成功管理模板,而不是我声明的自定义模板。

urls.py

from django.conf.urls import url
from django.contrib.auth import views as auth_views

from . import views

app_name = 'users'

urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^add-user/$', views.CreateUserView.as_view(), name='add-user'),
    url(r'^search/$', views.UserSearchView.as_view(), name='search-users'),
    url(r'^login/$', views.LoginView.as_view(), name='login'),
    url(r'^logout/$', views.LogoutView.as_view(), name='logout'),
    url(r'^(?P<pk>\d+)/settings/update$', views.UpdateAccountView.as_view(), name='update-account'),
    url(r'^settings/change/$', auth_views.password_change, {'template_name': 'users/forms/change-password.html'},
    name='change-password'),
    url(r'^settings/change-done/$', auth_views.password_change_done,
    {'template_name': 'users/forms/change-password-done.html'}, name='change-password-done'),
    url(r'^(?P<pk>\d+)/delete-user/$', views.DeleteUserView.as_view(), name='delete-user'),
Run Code Online (Sandbox Code Playgroud)

我错过了什么任何想法吗?

python django django-templates django-urls

1
推荐指数
1
解决办法
2082
查看次数

运行此代码时,为什么会出现分段错误?

我正在学习使用switch语句并使用rand()和srand()函数,但是当我尝试运行这本代码时,我得到了一个分段错误,我从这本书中学到了我正在学习C语言.可能导致这种情况发生的原因是什么?

#include <stdio.h>

int main(void)
{

int iRandomNum = 0;
srand(time());

iRandomNum = (rand() % 4) + 1;

printf("\nFortune Cookie - Chapter 3\n");

  switch (iRandomNum) {

   case 1:
      printf("\nYou will meet a new friend today.\n");
      break;
   case 2:
      printf("\nYou will enjoy a long and happy life.\n");
      break;
   case 3:
      printf("\nOpportunity knocks softly. Can you hear it?\n");
      break;
   case 4:
     printf("\nYou'll be financially rewarded for your good deeds.\n");
      break;

  } //end switch

printf("\nLucky lotto numbers: ");
printf("%d ", (rand() % 49) …
Run Code Online (Sandbox Code Playgroud)

c

0
推荐指数
1
解决办法
3700
查看次数

何时重写 Django CBV 中的 get 方法?

我一直在学习 Django,我的困惑来源之一是基于类的视图以及何时重写 get 方法。我查看了文档,它解释了 get 的作用,但没有解释何时应该覆盖 get。

我最初是这样创建视图的:

class ExampleView(generic.ListView):
    template_name = 'ppm/ppm.html'
    paginate_by = 5

    def get(self, request):
        profiles_set = EmployeeProfile.objects.all()
        context = {
            'profiles_set': profiles_set,
            'title': 'Employee Profiles'
        }
        return render(request, self.template_name, context)
Run Code Online (Sandbox Code Playgroud)

但最近有人告诉我,我的代码对于默认实现来说足够简单,而我所需要的就是这样:

class ExampleView(generic.ListView):
    model = EmployeeProfile
    template_name = 'ppm/ppm.html'
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:在什么场景/情况下我应该重写 get 方法?

python django django-class-based-views

0
推荐指数
1
解决办法
3883
查看次数