小编Ala*_*air的帖子

在现有表中生成slug字段

我有数据表.是否可以在现有表格上自动生成slug字段?还是有其他选择吗?谢谢这是我的桌子

在此输入图像描述

python django

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

Django:如何在通用创建视图上设置隐藏字段?

我正在运行Django 1.6.x.

为了扩展我的用户,我添加了另一个存储数据的模型:

class UserProfile (models.Model):
    user = models.ForeignKey(User)
    height = models.IntegerField(blank=True, null=True)
Run Code Online (Sandbox Code Playgroud)

现在我想添加一个视图,允许用户在那里添加自己的信息.开始django.views.generic.edit.CreateView,但也想提供至少编辑/更新一个.

所以我添加了导入并创建了一个视图:

from django.views.generic.edit import CreateView, UpdateView
# .... 
class UserProfileCreateView(CreateView):
    model = UserProfile
    fields = ['height']
Run Code Online (Sandbox Code Playgroud)

我还在urls.py中添加了条目:

    url(r'^userprofile/new/$', login_required(UserProfileCreateView.as_view()), name="add_userprofile")
Run Code Online (Sandbox Code Playgroud)

但现在我仍然坚持如何以正确的方式分配用户ID.我希望在后台设置此字段.任何提示?

django django-generic-views

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

在django中使用分页时如何返回最后一页?

在一个简单的论坛中,我使用本机 django分页我希望用户在他们发布后被定向到线程中的最后一页。

这是视图

@login_required
def topic_reply(request, topic_id):
    tform = PostForm()
    topic = Topic.objects.get(pk=topic_id)
    args = {}
    posts = Post.objects.filter(topic= topic)
    posts =  Paginator(posts,10)


    if request.method == 'POST':
        post = PostForm(request.POST)


        if post.is_valid():
            p = post.save(commit = False)
            p.topic = topic
            p.title = post.cleaned_data['title']
            p.body = post.cleaned_data['body']
            p.creator = request.user

            p.save()

            return HttpResponseRedirect('/forum/topic/%s/?page=%s'  % (topic.slug, posts.page_range[-1]))

    else:
        args.update(csrf(request))
        args['form'] = tform
        args['topic'] = topic
        return render_to_response('myforum/reply.html', args, 
                                  context_instance=RequestContext(request)) 
Run Code Online (Sandbox Code Playgroud)

其中产生:

'Page' object has no attribute 'page_range'
Run Code Online (Sandbox Code Playgroud)

我尝试了其他技巧,例如:

posts = list(Post.objects.filter(topic= …
Run Code Online (Sandbox Code Playgroud)

django django-pagination

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

检查空查询集

我想确认这是检查空查询集的正确方法,如果这是我遇到 UNIQUE 约束错误的原因。

syn_check= Synonym.objects.filter(MD.objects.get(**filter_dict), synonym_type=Stype.objects.filter(description=values.capitalize().strip()), synonym_name=key)
if not syn_check:
    print 'unavailable synonym', key, values
    syn = Synonym()
    syn.synonym_type=Stype.objects.filter(description=values.capitalize().strip()
    syn.synonym_name = key.strip()
    syn.save()
Run Code Online (Sandbox Code Playgroud)

我在做什么奇怪的事情吗?我也用过if not syn_check.count(),遇到同样的问题。

这是回溯:

    Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/home/project/.virtualenvs/project/local/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/home/project/PycharmProjects/project/project/management/commands/back_populate_data.py", line 53, in handle
    loaded_syn …
Run Code Online (Sandbox Code Playgroud)

django

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

如何使用 get_object_or_404 和 order_by('?') 来获取随机图像

我想从模型中获取随机对象,但如果数据库中没有数据,我想返回 404 页。

这行代码对我很有效:

    dummy_image=DummyImage.objects.order_by('?').first().image_url.url
Run Code Online (Sandbox Code Playgroud)

但我想使用get_object_or_404快捷方式。

所以我试过这个:

dummy_image = get_object_or_404(DummyImage).order('?').first().image_url.url
Run Code Online (Sandbox Code Playgroud)

但它不起作用并导致问题。它说它返回了两个以上的对象。

我该如何解决问题?

python django

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

如何将链接放入Django错误消息

我想使用类似这样的Django错误消息插入项目内部页面的链接

 messages.error(request, 'Please click <a href="{% url 'myproject:settings' %} >here </a>')
Run Code Online (Sandbox Code Playgroud)

django django-templates django-models django-forms django-views

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

__init__() 获得了意外的关键字参数“instance”,其中包含 inlineformset_factory 的自定义表单集

我收到这个错误

\n\n
__init__() got an unexpected keyword argument 'instance'\n
Run Code Online (Sandbox Code Playgroud)\n\n

每当我尝试发送带有为 inlineformset_factory 指定的 formset 参数的表单时。\n有什么想法为什么会发生这种情况吗?

\n\n

这是我的代码。抱歉,没有评论,我正在重写它,试图了解 django 的工作原理

\n\n

形式:

\n\n
class PurchaseForm(forms.ModelForm):\n    class Meta:\n        model = Purchase\n        fields = ['product', 'price', 'consumer']\n        widgets = {\n            'product': forms.Select(attrs = {\n                'class': 'form-control input-sm',\n            }),\n            'consumer': forms.Select(attrs = {\n                'class': 'form-control input-sm',\n            }),\n            'price': forms.NumberInput(attrs = {\n                'class': 'form-control input-sm',\n                'placeholder': '\xd0\xa6\xd0\xb5\xd0\xbd\xd0\xb0',\n            }),\n        }\n    discount = forms.DecimalField(\n        min_value      = 0,\n        decimal_places = 2,\n        # required       = False,\n        widget         = forms.NumberInput(\n …
Run Code Online (Sandbox Code Playgroud)

python django django-forms python-3.x

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

Django redirect_authenticated_user:真不起作用

我正在Django 1.11中编写应用程序。

myapp/urls.py 图案看起来像

from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth.views import LoginView

urlpatterns = [
    url(r'^login/$', LoginView.as_view(), {'redirect_authenticated_user': True}),
    url('^', include('django.contrib.auth.urls')),
    url('^', include('pages.urls')),
    url(r'^pages/', include('pages.urls')),
    url(r'^search/', include('search.urls')),
    url(r'^admin/', admin.site.urls),
]
Run Code Online (Sandbox Code Playgroud)

我想在尝试访问/login页面时重定向登录用户。为此,我已经按照此处的文档中的设置redirect_authenticated_user进行了设置True

但是,/login成功登录后访问时,它不会重定向。

python django django-authentication

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

Heroku 应用程序成功部署,但在加载站点时收到应用程序错误

据我所知,我的日志没有指出任何错误,但是在加载站点时我收到以下错误:

An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail

您可以在下面找到日志。我在这里错过了什么吗?

-----> Python app detected
-----> Uninstalling stale dependencies
       Uninstalling Django-2.1.5:
         Successfully uninstalled Django-2.1.5
       Uninstalling Pillow-5.4.1:
         Successfully uninstalled Pillow-5.4.1
-----> Installing requirements with pip
       Collecting dj-database-url==0.5.0 (from -r /tmp/build_99fe21a8dcc00005ce600053adc20260/requirements.txt (line 1))
         Downloading https://files.pythonhosted.org/packages/d4/a6/4b8578c1848690d0c307c7c0596af2077536c9ef2a04d42b00fabaa7e49d/dj_database_url-0.5.0-py2.py3-none-any.whl
       Collecting Django==2.1.5 (from -r /tmp/build_99fe21a8dcc00005ce600053adc20260/requirements.txt (line 2))
         Downloading …
Run Code Online (Sandbox Code Playgroud)

python django heroku

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

django 2.2.5 url 路径中的 URL 正则表达式

我想在 url 中的单个视图中支持上述视图...在我的搜索中,我遇到了这篇文章,该文章不再受支持,并且我找到的所有教程都已过时,其中演示了如何完成任务Django 1.8.3。

在“products/views.py”中,我创建了产品和详细信息的视图。ProductListView 将显示所有产品,而 ProductDetailView 将显示单个产品详细信息(标题、描述、价格等)。

产品/views.py

class ProductListView(ListView):
    queryset = Product.objects.all()
    template_name = "products/list.html"


class ProductDetailView(DetailView):
    queryset = Product.objects.all()
    template_name = "products/detail.html"
Run Code Online (Sandbox Code Playgroud)

products/urls.py 包含 ProductListView 和 ProductDetailView 视图的路径。ProductListView 似乎是正确的。ProductDetailView 不正确!我收到以下警告:

警告: ?: (2_0.W001) 您的 URL 模式 '^products/(?P\d+)/$' [name='details'] 的路由包含 '(?P<',以 '^' 开头,或以“$”结尾。这可能是迁移到 django.urls.path() 时的疏忽。

ecommerce.py/urls.py 是我包含产品和详细信息网址的地方

电子商务/urls.py:

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include

from .views import home, about, contact

urlpatterns = [
    path('admin/', admin.site.urls), …
Run Code Online (Sandbox Code Playgroud)

python django django-urls django-views

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