小编Sta*_*ato的帖子

Django EmailField接受无效值

我目前正在使用EmailField表单上的默认属性.我遇到的问题是表单认为无效的电子邮件name@mail.56是有效的.我是否需要validators在此字段上实现自己的功能才能使其正常工作?

我的印象是:

#models.py
email = models.EmailField(max_length=254, blank=False, unique=True,
        error_messages={'required': 'Please provide your email address.',
                        'unique': 'An account with this email exist.'},)
Run Code Online (Sandbox Code Playgroud)

或者:

#forms.py
email = forms.EmailField()
Run Code Online (Sandbox Code Playgroud)

我会照顾这种类型的验证,但似乎并非如此.

django django-forms

10
推荐指数
2
解决办法
8430
查看次数

Django:仅更新UpdateView中已更改的字段

我正在使用UpdateView来更新一系列字段.但是,我只希望将已修改的字段保存到数据库中.如果在更新过程中没有为字段提供值,我希望将前一个值用作默认值.如果为字段提供了新值,则只应更新该字段.我该如何完成这项工作?

#views.py
class AccountUpdate(UpdateView):
""" Updates an account; unchanged fields will not be updated."""
context_object_name = 'account'
form_class = UpdateForm
template_name = 'accounts/update_account.html'
success_url = '/accounts/home'

def get_object(self, queryset=None):
    return self.request.user

def form_valid(self, form):
    clean = form.cleaned_data
    #encrypt plain password
    form.instance.password = hash_password(clean['password'])
    context = {}
    self.object = context.update(clean, force_update=False)
    return super(AccountUpdate, self).form_valid(form)

#templates
{% extends 'base.html' %}
<title>{% block title %}Update Account{% endblock %}</title>
{% block content %}
{{ account.non_field_errors }}
<div class="errors" style="list-style-type: none;">
    {% if account.first_name.errors %}{{ …
Run Code Online (Sandbox Code Playgroud)

django django-forms django-class-based-views

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

Django 模板中的计数方法未按预期工作

我正在构建一个新闻应用程序,允许成员对文章发表评论。我想在我的模板中显示文章,并显示对每篇文章发表的评论数。我尝试使用 count 方法,但它检索的是我的评论表中的评论总数,而不是特定文章的评论数。

#models.py
class Article(models.Model):
    #auto-generate indices for our options
    ENTRY_STATUS = enumerate(('no', 'yes'))
    #this will be a foreign key once account app is built
    author = models.CharField(default=1, max_length=1)
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=50)
    entry = models.TextField()
    dateposted = models.DateTimeField(default=timezone.now, auto_now_add=True)
    draft = models.IntegerField(choices=ENTRY_STATUS, default=0)
    lastupdated = models.DateTimeField(default=timezone.now, auto_now=True)

    #prevents the generic labeling of our class as 'Classname object'
    def __unicode__(self):
        return self.title


class Comment(models.Model):
    #this will be a foreign key once account app is built
    author = …
Run Code Online (Sandbox Code Playgroud)

django django-templates django-views django-class-based-views

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