我一直在通过Mark Pilgrim的Dive Into Python教自己Python .我完全推荐它,就像其他Stack Overflow用户一样.
然而,Dive Into Python的最后一次更新是在五年前.我期待将新Dive读入Python 3当我切换到3.x时,但是现在,使用django意味着我将坚持2.x.
我很想知道我错过了什么Python的新功能,如果我使用Dive Into Python作为我学习语言的主要资源.我遇到的几个例子是
还有什么我错过了吗?
编辑:正如Bastien在他的回答中指出的那样,我可以阅读Python页面中的新内容,但有时在Stack Overflow上发现一个有用的技巧很有趣,而不是在官方文档中通过完整,全面的答案.
我正在使用列表列表来存储python中的矩阵.我尝试按如下方式初始化2x3 Zero矩阵.
mat=[[0]*2]*3
Run Code Online (Sandbox Code Playgroud)
但是,当我更改矩阵中某个项的值时,它会更改每一行中该条目的值,因为每行的id mat是相同的.例如,在分配之后
mat[0][0]=1
Run Code Online (Sandbox Code Playgroud)
mat是[[1, 0], [1, 0], [1, 0]].
我知道我可以使用循环创建Zero矩阵,如下所示,
mat=[[0]*2]
for i in range(1,3):
mat.append([0]*2)
Run Code Online (Sandbox Code Playgroud)
但有人能告诉我更多的pythonic方式吗?
我正在使用django 1.9,我目前正在编码 - 在Windows命令提示符 - python manage.py makemigrations和错误:
AttributeError:'str'对象没有属性'regex'
我试过编码:
url(r'^$', 'firstsite.module.views.start', name="home"),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}, name='login'),
url(r'^signup/$', 'exam.views.signup', name='signup'),
url(r'^signup/submit/$', 'exam.views.signup_submit', name='signup_submit')
Run Code Online (Sandbox Code Playgroud)
在urls.py中,错误不断出现.
这是我第一次在django编码,所以我的专业知识非常有限.先感谢您.
这是整个urls.py:
from django.conf.urls import patterns, include, url
import django
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'firstsite.views.home', name='home'),
# url(r'^firstsite/', include('firstsite.foo.urls')),
# Uncomment the admin/doc line below to …Run Code Online (Sandbox Code Playgroud) 我ListView在基于类的视图中使用,我想知道是否有办法通过对模板进行排序来显示模板上的模型对象集.这是我到目前为止:
我的观点:
class Reviews(ListView):
model = ProductReview
paginate_by = 50
template_name = 'review_system/reviews.html'
Run Code Online (Sandbox Code Playgroud)
该模型ProductReview有一个date_created字段.我想按降序排列日期.我怎样才能做到这一点?
Python打印没有使用__repr__,__unicode__或__str__打印时我的unicode子类.关于我做错了什么的线索?
这是我的代码:
使用Python 2.5.2(r252:60911,2009年10月13日,14:11:59)
>>> class MyUni(unicode):
... def __repr__(self):
... return "__repr__"
... def __unicode__(self):
... return unicode("__unicode__")
... def __str__(self):
... return str("__str__")
...
>>> s = MyUni("HI")
>>> s
'__repr__'
>>> print s
'HI'
Run Code Online (Sandbox Code Playgroud)
我不确定这是否是上述的准确近似值,只是为了比较:
>>> class MyUni(object):
... def __new__(cls, s):
... return super(MyUni, cls).__new__(cls)
... def __repr__(self):
... return "__repr__"
... def __unicode__(self):
... return unicode("__unicode__")
... def __str__(self):
... return str("__str__")
...
>>> s = MyUni("HI")
>>> s …Run Code Online (Sandbox Code Playgroud) 目前我使用这些模式登录和注销
urlpatterns += patterns("",
(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),
(r'^logout/$', 'django.contrib.auth.views.logout', {'template_name': 'logout.html'})
)
Run Code Online (Sandbox Code Playgroud)
尽管我的settings.py中有LOGIN_REDIRECT_URL ='/ profile /',但是当我已经登录时,如果我想访问/ login /,Django不会将我发送到/ profile/...
我可以以某种方式重定向auth系统的URL模式吗?我不愿意为此编写自定义视图.
昨天我错误地卸载了python 3.7版本。然后我再次安装python(这次是3.8版本)并再次设置我的环境。但是我无法启动具有 Postgres 连接的 Django 项目。实际上我无法在我的环境中安装“ psycopg2 ”。我搜索了几个小时并实施了我从网上获得的所有解决方案,但它不起作用。让我告诉你我到目前为止做了什么。
C:\Program Files\PostgreSQL\12\bin\在我的 PATH 中添加了。然后出现了一个新问题,其中包含一个包含 2 个重要错误的巨大错误报告。
错误:psycopg2 的构建轮失败
......................................
为 psycopg2 运行 setup.py install ... 错误
我尝试升级轮子,但它说,
要求已经是最新的
http://initd.org/psycopg/docs/install.html#install-from-source 我从这个站点了解到psycopg2需要python2版本。所以我也安装了python 2.7。
pip install psycopg2-binary但这对我不起作用。请帮我摆脱这个。我坚持了几个小时。
我所有的django模型都有unicode函数,目前这些函数往往是这样编写的:
def __unicode__(self):
return u'Unit: %s -- %s * %f' % (self.name, self.base.name, self.mul)
Run Code Online (Sandbox Code Playgroud)
但是,Code Like a Pythonista,在http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#string-formatting指出这self.__dict__是一本字典,因此上面的内容可以简化为:
def __unicode__(self):
return u'Unit: %(name)s -- %(base.name)s * %(mul)f' % self.__dict__
Run Code Online (Sandbox Code Playgroud)
这是有效的,除了"base.name",因为python尝试查找self.__dict__['base.name']哪个失败,而self.base.name工作.
即使您需要遵循外键关系,是否有一种优雅的方式来完成这项工作?
使用django generic CreateView我可以创建一个新的用户帐户,但是如何在注册后使用这种技术自动登录该用户?
urls.py
...
url( r'^signup/$', SignUpView.as_view(), name = 'user_signup' ),
...
Run Code Online (Sandbox Code Playgroud)
views.py
class SignUpView ( CreateView ) :
form_class = AccountCreationForm
template_name = 'accounts/signup.html'
success_url = reverse_lazy( 'home' )
Run Code Online (Sandbox Code Playgroud)
forms.py
class AccountCreationForm ( forms.ModelForm ) :
def __init__( self, *args, **kwargs ) :
super( AccountCreationForm, self ).__init__( *args, **kwargs )
for field in self.fields :
self.fields[field].widget.attrs['class'] = 'form-control'
password1 = forms.CharField( label = 'Password', widget = forms.PasswordInput )
password2 = forms.CharField( label = 'Password confirmation', widget = forms.PasswordInput …Run Code Online (Sandbox Code Playgroud) # pip3.4 install mysql-python
Downloading/unpacking mysql-python
Downloading MySQL-python-1.2.5.zip (108kB): 108kB downloaded
Running setup.py (path:/tmp/pip_build_root/mysql-python/setup.py) egg_info for package mysql-python
Traceback (most recent call last):
File "<string>", line 17, in <module>
File "/tmp/pip_build_root/mysql-python/setup.py", line 13, in <module>
from setup_posix import get_config
File "/tmp/pip_build_root/mysql-python/setup_posix.py", line 2, in <module>
from ConfigParser import SafeConfigParser
ImportError: No module named 'ConfigParser'
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 17, in <module>
File "/tmp/pip_build_root/mysql-python/setup.py", line 13, in <module>
from setup_posix …Run Code Online (Sandbox Code Playgroud) python ×8
django ×6
class ×1
django-1.9 ×1
foreign-keys ×1
list ×1
matrix ×1
mysql ×1
postgresql ×1
psycopg2 ×1
python-3.8 ×1
python-3.x ×1
subclass ×1
unicode ×1
windows ×1