小编Ala*_*air的帖子

Django表示:当文件POST到文件字段时,"此字段是必需的"

我出于某种原因无法在我的ModelForm中将文件存入我的文件字段.提交文件并且文件名在相应的POST请求中,但是在form.is_valid()它声明时失败{'the_file': [u'This field is required.']}

我为一个带有文件字段的模型和另一个模型的外键编写了一个ModelForm,因此:

class AccountFile(models.Model):
the_file = models.FileField(upload_to='{}/%Y/%m/%d/'.format(
    settings.MEDIA_ROOT,
))
account = models.ForeignKey(
    Account,
    blank=True,
    null=True,
    related_name='account_files'
Run Code Online (Sandbox Code Playgroud)

然后我生成了一个表单来上传文件,因此:

class UploadFileForm(forms.ModelForm):
class Meta:
    model = models.AccountFile
    fields = ['the_file' ]


def clean_file(self):
    file = self.cleaned_data.get("the_file", False)
    filetype = magic.from_buffer(file.read())
    if not "pdf" in filetype:
        raise forms.ValidationError("File is not pdf.")
    return file
Run Code Online (Sandbox Code Playgroud)

当我至少可以完成一件事时,进行一些非常基本的验证(将会扩展!).

表单处理如下:

if request.method == 'POST':
    form = forms.UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        handle_uploaded_file(request.FILES['file'])
        return redirect(
            'account_url',
            acc_manager_pk=acc_manager.pk,
            account_pk=account.pk,
            )
else:
    form = forms.UploadFileForm()
Run Code Online (Sandbox Code Playgroud)

这是在Django …

forms django

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

带有关键字参数uidb64和Django 2.0的NoReverseMatch

我无法理解为什么我的代码不起作用.在它运行之前,但现在,当我运行服务器并进行测试时,代码不起作用.

当用户注册时,我发送激活邮件,如下所示:

def send_activation_email(serializer, request, user):
    current_site = get_current_site(request)
    message = render_to_string('acc_active_email.html', {
        'user': user,
        'domain': current_site.domain,
        'uid': urlsafe_base64_encode(force_bytes(user.pk)),
        'token': account_activation_token.make_token(user),
    })
    mail_subject = 'Activate your blog account.'
    to_email = serializer.data['email']

    email = EmailMessage(mail_subject, message, to=[to_email])
    email.send()
Run Code Online (Sandbox Code Playgroud)

acc_active_email.html

{% autoescape off %}
Hi {{ user.username }},
Please click on the link to confirm your registration,

http://{{ domain }}{% url 'activate' uidb64=uid token=token %}
{% endautoescape %}
Run Code Online (Sandbox Code Playgroud)

和我的网址文件

.
.
    url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
        views.activate_account, name='activate'),
.
.
Run Code Online (Sandbox Code Playgroud)

但我有这个错误:

Exception Type:     NoReverseMatch
Exception Value: …
Run Code Online (Sandbox Code Playgroud)

python django django-templates python-3.x django-2.0

16
推荐指数
2
解决办法
5695
查看次数

从Django模板中的URL访问kwargs

我可以在Django模板中访问命名参数的值(来自URL)吗?

我可以this_name从django模板中访问下面的值吗?

url(r'^area/(?P<this_name>[\w-]+)/$', views.AreaView.as_view(), name="area_list")
Run Code Online (Sandbox Code Playgroud)

我可以获取整个URL路径并将其分解但是想要检查是否有直接的方法来执行此操作,因为它已经有了名称.

在视图中的上下文数据中传递它可能是另一种选择,但不确定我是否需要传递它,因为我猜模板已经以某种方式已经拥有它?但是在请求API中找不到直接方法.

django django-templates django-urls

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

jquery tablesorter插件 - 保留替代行颜色

我拿了一个html表,我正在应用替代行颜色,并在其上添加了jquery表分类器,以便用户可以对表进行排序.

问题是替代的行颜色现在都搞砸了(基于排序),有多个行具有相同的背景颜色.

有没有办法用jquery表分类器重置替代行颜色?

jquery tablesorter row backcolor

14
推荐指数
3
解决办法
2万
查看次数

Django在原始请求中选择相关

如何制作"手动"select_related模仿以避免不良的数据库命中?

我们有:

class Country:
    name = CharField()
class City:
    country = models.ForeignKey(Country)
    name = models.CharField()

cities = City.objects.raw("select * from city inner join country on city.country_id = country.id where name = 'london'")

#this will hill hit DB
print cities[0].country.name
Run Code Online (Sandbox Code Playgroud)

如何告诉django相关模型已经被提取.

django orm django-models

14
推荐指数
3
解决办法
4187
查看次数

Django唯一,null和空白CharField在管理页面上给出"已存在"错误

我一直在收到最奇怪的错误.我有一个人模型

class Person(models.Model):
    user = models.OneToOneField(User, primary_key=True)
    facebook_id = models.CharField(max_length=225, unique=True, null=True, blank=True)
    twitter_id = models.CharField(max_length=225, unique=True, null=True, blank=True)
    suggested_person = models.BooleanField(default=False)
Run Code Online (Sandbox Code Playgroud)

我最近添加了twitter_id字段.当我访问Django管理页面,并尝试将'person'更改为suggested_person时,我收到以下错误:

 Person with this Twitter id already exists.
Run Code Online (Sandbox Code Playgroud)

我发现这个错误非常奇怪,因为Facebook_id字段的设计方式与Twitter_id字段完全相同.

这可能是什么原因?

python django django-models django-admin

13
推荐指数
6
解决办法
2万
查看次数

相当于boto3中的get_contents_to_file

在boto3中,有没有相当于get_contents_to_file,将对象的内容复制到文件句柄?

在boto中,如果我有一个S3对象key,我可以将内容复制到一个临时文件中:

from tempfile import TemporaryFile
key = code_that_gets_key()

with TemporaryFile() as tmp_file:
    key.get_contents_to_file(key, tmpfile)
Run Code Online (Sandbox Code Playgroud)

我还没有找到boto3中的等价物.

我已经能够替换使用get_contents_to_filenamedownload_file.但是,这涵盖了我提供文件名的情况.在这种情况下,我想提供文件句柄作为参数.

目前,我可以通过遍历正文来获取代码在boto3中工作,如下所示:

with TemporaryFile() as tmp_file:
    body = key.get()['Body']
    for chunk in iter(lambda: body.read(4096), b''):
        filehandle.write(chunk)
Run Code Online (Sandbox Code Playgroud)

在boto3中有更好的方法吗?

python amazon-s3 boto3

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

Django'AnonymousUser'对象没有属性'_meta'

我在我的Django应用程序中使用社交登录.所以,我在我的settings.py文件中添加了额外的后端.

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'social_core.backends.open_id.OpenIdAuth',
    'social_core.backends.google.GoogleOpenId',
    'social_core.backends.google.GoogleOAuth2',
    'social_core.backends.google.GoogleOAuth',
    'social_core.backends.twitter.TwitterOAuth',
    'social_core.backends.facebook.FacebookOAuth2',
    'social_core.backends.github.GithubOAuth2',
Run Code Online (Sandbox Code Playgroud)

]

我也用于UserCreationForm注册,

class SignupForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=True, help_text='Required.')
    last_name = forms.CharField(max_length=30, required=True, help_text='Required.')
    email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2' )
Run Code Online (Sandbox Code Playgroud)

这是视图文件,

def signup(request):
    if request.method == 'POST':
        form  = SignupForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_pass = form.cleaned_data.get('password')
            user = authenticate(request, username=username, password=raw_pass)
            login(request,user,backend='django.contrib.auth.backends.ModelBackend')
            url = …
Run Code Online (Sandbox Code Playgroud)

python django

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

自从潜入Python以来对Python的改变

我一直在通过Mark Pilgrim的Dive Into Python教自己Python .我完全推荐它,就像其他Stack Overflow用户一样.

然而,Dive Into Python的最后一次更新是在五年前.我期待将新Dive入Python 3当我切换到3.x时,但是现在,使用django意味着我将坚持2.x.

我很想知道我错过了什么Python的新功能,如果我使用Dive Into Python作为我学习语言的主要资源.我遇到的几个例子是

  • itertools
  • ElementTree的

还有什么我错过了吗?

编辑:正如Bastien在他的回答中指出的那样,我可以阅读Python页面中的新内容,但有时在Stack Overflow上发现一个有用的技巧很有趣,而不是在官方文档中通过完整,全面的答案.

python

12
推荐指数
2
解决办法
1444
查看次数

Django __call__() 缺少 1 个必需的仅关键字参数:'manager'

我有两个模型:

class Someinfo(models.Model):
name = models.CharField(max_length=200)
#something else

class OtherInfo(models.Model):
name2 = models.CharField(max_lenth=200)
related_someinfo = models.ManyToManyField(Someinfo)
#something else
Run Code Online (Sandbox Code Playgroud)

现在我已经创建了 CBV 视图来创建和查看它们。CreateView 工作正常并保存可以在管理员中查看的信息,但我无法让模板在任何其他视图上显示数据,无论是 FormView、DetailView 还是任何其他视图,因为我收到此错误:

__call__() missing 1 required keyword-only argument: 'manager'

Request Method:     GET
Request URL:    http://something
Django Version:     2.0.3
Exception Type:     TypeError
Exception Value:    

__call__() missing 1 required keyword-only argument: 'manager'

Exception Location:     /usr/local/lib/python3.5/dist-packages/django/forms/forms.py in get_initial_for_field, line 494
Python Executable:  /usr/bin/python3
Python Version:     3.5.3
Run Code Online (Sandbox Code Playgroud)

检查 forms.py 中的行,它表明不起作用的函数是:

def get_initial_for_field(self, field, field_name):
    """
    Return initial data for field on form. …
Run Code Online (Sandbox Code Playgroud)

django

12
推荐指数
2
解决办法
8507
查看次数