这是一个非常简单的Django问题,但我在Django文档中找不到答案,尽管有很多狩猎!
如何检查对象是否已经存在,并且只添加它,如果它不存在?
这是代码 - 如果已经存在,我不想在数据库中添加两次follow_role.我该如何先检查?使用get()可能 - 但是如果get()没有返回任何内容,那么Django会抱怨吗?
current_user = request.user
follow_role = UserToUserRole(from_user=current_user, to_user=user, role='follow')
follow_role.save()
Run Code Online (Sandbox Code Playgroud)
谢谢!
Django新手问题....
我正在尝试编写搜索表单并维护搜索请求和搜索结果之间的输入框状态.
这是我的表格:
class SearchForm(forms.Form):
q = forms.CharField(label='Search: ', max_length=50)
Run Code Online (Sandbox Code Playgroud)
这是我的观点代码:
def search(request, q=""):
if (q != ""):
q = q.strip()
form = SearchForm(initial=q)
#get results here...
return render_to_response('things/search_results.html',
{'things': things, 'form': form, 'query': q})
elif (request.method == 'POST'): # If the form has been submitted
form = SearchForm(request.POST)
if form.is_valid():
q = form.cleaned_data['q']
# Process the data in form.cleaned_data
return HttpResponseRedirect('/things/search/%s/' % q) # Redirect after POST
else:
form = SearchForm()
return render_to_response('things/search.html', {
'form': form,
})
else:
form …Run Code Online (Sandbox Code Playgroud) Windows无法获取我的.hgignore文件.我从命令行运行Mercurial,"hg status"显示被忽略目录中的大量文件.
.hgignore文件看起来像这样(文件的开头或每行的开头都没有空格).我把它放在存储库的根目录中.
\.pyc$
\.pyo$
\.DS_Store
\.Python
\.installed.cfg
^bin$
^build$
^develop-eggs$
^eggs$
^include$
^lib$
^parts$
^pip-log.txt$
^web/localsettings.py$
Run Code Online (Sandbox Code Playgroud)
我试过用ANSI和UTF-8保存文件,但它似乎没有什么区别.
我知道该文件在Linux上运行正常,Windows中的路径有什么不同吗?
我想在Django中创建一个位于URL /搜索的搜索框,并重定向到友好的URL,如/ search/queryterm - 而不是在URL中使用?q = queryterm)
因此,用户键入查询词,将它们带到/ search/queryterm,并显示结果列表.
我可以获得并显示结果OK给定像/ search/queryterm这样的URL.
但我不知道从表单处理URL重定向的最佳方法.这应该是表单中纯HTML的重定向(感觉有点hacky),如果是这样,我该如何实现呢?
或者应该将表单POST发送到/ search /,然后将ResponseRedirect发送到/ search/queryterm页面?这不会慢吗?
谢谢!