我正在建立一个新闻网站.虽然我试图得到具有相同标签的相关新闻列表.错误说:精确查找的QuerySet值必须限制为使用slicing-Django的一个结果.
我有两个模型新闻和标签,标签是新闻的多对多外键.
新闻模式:
class News(models.Model):
tag = models.ManyToManyField(Tag, blank=True, verbose_name='tag')
Run Code Online (Sandbox Code Playgroud)
标签型号:
class Tag(models.Model):
name = models.CharField(max_length=40)
Run Code Online (Sandbox Code Playgroud)
视图:
def newsDetailView(request, news_pk):
news = get_object_or_404(News, id=news_pk)
tags = news.tag.annotate(news_count=Count('news'))
relative_news = News.objects.filter(tag=tags)
return render(request, "news_detail.html", {
'news': news,
'tags': tags,
'relative_news': relative_news
})
Run Code Online (Sandbox Code Playgroud)
有朋友可以帮忙吗?非常感谢你!
我有一个功能:
import time
def all_40k():
for _ in range(400000):
print('validate')
print('parsing')
print('inserting')
if __name__ == '__main__':
start_time = time.time()
all_40k()
print(f'used time:{time.time()-start_time}')
Run Code Online (Sandbox Code Playgroud)
输出是:
used time:9.545064210891724
Run Code Online (Sandbox Code Playgroud)
因为这个相同的函数重复了 40k 次,所以我希望有 4 个并行函数同时运行,每个函数运行 10k,理想情况下这会快 4 倍。
所以我首先尝试了多线程:
import threading
import time
def first_10k():
for _ in range(100000):
print('validate')
print('parsing')
print('inserting')
def second_10k():
for _ in range(100000):
print('validate')
print('parsing')
print('inserting')
def third_10k():
for _ in range(100000):
print('validate')
print('parsing')
print('inserting')
def forth_10k():
for _ in range(100000):
print('validate')
print('parsing')
print('inserting')
thread1 = threading.Thread(target=first_10k)
thread2 = threading.Thread(target=second_10k) …Run Code Online (Sandbox Code Playgroud) python multithreading python-multithreading python-asyncio python-multiprocessing
我有一个 df:
dfs = """
contract Valindex0 RB Valindex1
2 A00118 51 0 50
3 A00118 42 1 47
4 A00118 44 1 47
"""
df = pd.read_csv(StringIO(dfs.strip()), sep='\s+')
Run Code Online (Sandbox Code Playgroud)
df:
contract Valindex0 RB Valindex1
2 A00118 51 0 50
3 A00118 42 1 47
4 A00118 44 1 47
Run Code Online (Sandbox Code Playgroud)
我想为每一行 df['Valindex'] 添加一个新列,
此列值是
df['Valindex0']
Run Code Online (Sandbox Code Playgroud)
或者
df['Valindex1']
Run Code Online (Sandbox Code Playgroud)
这取决于 df['RB']:
if df['RB']==0:
df['Valindex'] = df['Valindex0']
elif df['RB']==1:
df['Valindex'] = df['Valindex1']
Run Code Online (Sandbox Code Playgroud)
现在我正在使用 apply lambda,但它很慢:
df['Valindex'] = df.apply(
lambda df: df["Valindex" + str(df["RB"])], axis=1) …Run Code Online (Sandbox Code Playgroud) 我可以在一个函数中为两个不同的输入进行双向绑定吗?
为了绑定:
<Input placeholder='title...' onChange={this.handelChangetitle.bind(this)} />
<textarea className='textarea' onChange={this.handelChangecontent.bind(this)}>d</textarea>
Run Code Online (Sandbox Code Playgroud)
到:<p>Blog title:{this.state.title}</p>
<p>Blog content:{this.state.content}</p>
我需要两个非常相似的功能:
handelChangetitle(event){this.setState({title:event.target.value})}
handelChangecontent(event){this.setState({content:event.target.value})}
Run Code Online (Sandbox Code Playgroud)
有什么方法可以保存一些代码,只使用一个函数但同时绑定“标题”和“内容”?
我正在编写一个新闻网站,在详细新闻页面中,有一个评论喷泉,如果人们想发表评论,他们需要先登录。我想让他们登录成功后,页面可以返回到之前的新闻页面。
这是我的views.py:
def newsDetailView(request, news_pk):
news = News.objects.get(id=news_pk)
title = news.title
author = news.author_name
add_time = news.add_time
content = news.content
category = news.category
tags = news.tag.annotate(news_count=Count('news'))
all_comments = NewsComments.objects.filter(news=news)
comment_form = CommentForm(request.POST or None)
if request.method == 'POST' and comment_form.is_valid():
comments = comment_form.cleaned_data.get("comment")
comment = NewsComments(user=request.user, comments=comments, news=news)
comment.save()
return render(request, "news_detail.html", {
'title': title,
'author': author,
'add_time': add_time,
'content': content,
'tags': tags,
'category': category,
'all_comments': all_comments,
'comment_form': comment_form
})
Run Code Online (Sandbox Code Playgroud)
这是我的 news_detail.html:
{% if user.is_authenticated %}
<form method="POST" action="">{% csrf_token …Run Code Online (Sandbox Code Playgroud) django django-templates django-models django-forms django-views
我有 5 个模板:index.html、detail.html、tag.html、login.html、register.html和base.html
所有 5 个模板都将扩展base.html。
index.html、detail.html、tags.html具有相同的<section>...</section>html 代码部分,来自后端的数据相同。我想将此部分添加到base.html 中,这样就不需要在 3 个不同的模板中重复 3 次.
但问题是,login.html 和 register.html确实需要这个部分。
我知道无论是 React.js 还是 Vue.js,使用组件来解决它会很容易。
有什么好方法可以在 Django 中解决这个问题?
当我使用 Keras 时。我收到一个有线错误:
ValueError:模型无法编译,因为它没有优化损失。
这是我的代码:
model = Sequential()
model.add(LSTM(
input_shape=(None, 1),
units=50,
return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(
200,
return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(units=1))
model.add(Activation('linear'))
model.compile(lose='mse', optimizer='rmsprop')
# Step 3. Train model
model.fit(X_Training, Y_Training,
batch_size=512,
nb_epoch=5,
validation_split=0.05)
Run Code Online (Sandbox Code Playgroud) 当我在 Mac 上的 PyCharm 中运行以下代码时?
import numpy as np
import pandas as pd
from subprocess import check_output
print(check_output(["ls", "../input"]).decode("utf8"))
import time
import copy
import numpy as np
import pandas as pd
import chainer
import chainer.functions as F
import chainer.links as L
from plotly import tools
from plotly.graph_objs import *
from plotly.offline import init_notebook_mode, iplot, iplot_mpl
init_notebook_mode()
data = pd.read_csv('../input/Data/Stocks/goog.us.txt')
data['Date'] = pd.to_datetime(data['Date'])
data = data.set_index('Date')
print(data.index.min(), data.index.max())
data.head()
Run Code Online (Sandbox Code Playgroud)
有一些错误:
UserWarning: Accelerate has been detected as a NumPy backend library.
vecLib, …Run Code Online (Sandbox Code Playgroud) 当我尝试启动工作程序时,出现一个问题:
ImportError:没有名为“ project”的模块
追溯(最近一次通话):
File "/usr/local/bin/celery", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python3.5/dist-packages/celery/__main__.py", line 16, in main
_main()
File "/usr/local/lib/python3.5/dist-packages/celery/bin/celery.py", line 322, in main
cmd.execute_from_commandline(argv)
File "/usr/local/lib/python3.5/dist-packages/celery/bin/celery.py", line 496, in execute_from_commandline
super(CeleryCommand, self).execute_from_commandline(argv)))
File "/usr/local/lib/python3.5/dist-packages/celery/bin/base.py", line 273, in execute_from_commandline
argv = self.setup_app_from_commandline(argv)
File "/usr/local/lib/python3.5/dist-packages/celery/bin/base.py", line 479, in setup_app_from_commandline
self.app = self.find_app(app)
File "/usr/local/lib/python3.5/dist-packages/celery/bin/base.py", line 501, in find_app
return find_app(app, symbol_by_name=self.symbol_by_name)
File "/usr/local/lib/python3.5/dist-packages/celery/app/utils.py", line 359, in find_app
sym = symbol_by_name(app, imp=imp)
File "/usr/local/lib/python3.5/dist-packages/celery/bin/base.py", line 504, in symbol_by_name
return imports.symbol_by_name(name, imp=imp)
File …Run Code Online (Sandbox Code Playgroud) 我正在使用 Selenium Python 来定位标签元素。我想使用::before来定位它,因为这是一个弹出窗口。
<div class="crow" grp="0" grpname="Pizza Size">
::before
<label class="label0" cid="1">
<input type="radio" name="0" coname="M" sname="" price="9.99" value="392">M<b class="ip">9.99</b>
</label>
<label class="label0" cid="1"><input type="radio" name="0" coname="L" sname="" price="11.99" value="393">L<b class="ip">11.99</b>
</label><div style="clear:both">
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我不知道如何使用::before来定位它,有朋友可以帮忙吗?
python selenium css-selectors pseudo-element selenium-webdriver
我有这样的Python逻辑:
file = 'POMNI2022.csv'
pomni=False
if 'POMNI' in file:
pomni=True
else:
pass
Run Code Online (Sandbox Code Playgroud)
有什么办法可以让我在这里只使用 1 行代码来实现 if else 逻辑吗?
python ×9
django ×4
django-views ×3
celery ×1
celery-task ×1
chainer ×1
dataframe ×1
django-forms ×1
ipython ×1
keras ×1
numpy ×1
pandas ×1
pycharm ×1
reactjs ×1
selenium ×1