机器人可以响应消息,但是如何让它以某种频率自己写呢?
Innsmouth fisherman's questions
在写文章时,我可以选择上传图片,但是当我这样做时,settings.py 中没有任何反应
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
详细信息.html
<img src="{% if article.image %}{{ article.image.url }}{% endif %}">
模型.html
class Article(models.Model):
title = models.CharField(max_length=50)
text = models.TextField()
image = models.ImageField(blank=True, upload_to='images/%Y/%m/%d')
file = models.FileField(blank=True)
网址.py
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
表格.py
class ArticleForm(ModelForm):
class Meta:
model = Article
fields = ['title', 'text', 'image','file']
视图.py
def detail(request, pk):
article = get_object_or_404(Article, pk=pk)
return render(request, 'content/detail.html',
{'article': article})
def list(request):
return render(request, 'content/list.html', {
'articles': Article.objects.all()
})
def create_article(request):
if request.method == 'POST':
form = ArticleForm(request.POST)
if form.is_valid():
form.save()
return redirect('list')
else:
form = ArticleForm()
return render(request, 'content/create.html', {'form': form})
创建.html
{% extends "base.html" %}
{% block title %}
create article
{% endblock %}
{% block content %}
<form action="." method="post" enctype="multipart/form-data">
{{ form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Save"></p>
</form>
{% endblock %}
我正在编写一个程序,该程序应根据radioButton
选择的输出响应:
转换器.py
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
import sys
criteries = {'В разработке': 'A1',
'Утверждённые к разработке': 'A2',
'Обоснованные к разработке': 'A3',
'Разработка ожидается/задерживается': 'A4',
'Разработка не выяснена/нецелесообразна': 'A5',}
class Ui_MainWindow(QMainWindow):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.setEnabled(True)
MainWindow.resize(667, 336)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(10, 30, 141, 16))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(180, 30, 221, 16))
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(430, 30, 151, 16))
self.label_3.setObjectName("label_3")
self.line = QtWidgets.QFrame(self.centralwidget)
self.line.setGeometry(QtCore.QRect(70, 50, 3, 61))
self.line.setFrameShape(QtWidgets.QFrame.VLine)
self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line.setObjectName("line")
self.line_2 = QtWidgets.QFrame(self.centralwidget)
self.line_2.setGeometry(QtCore.QRect(280, 50, 3, 61))
self.line_2.setFrameShape(QtWidgets.QFrame.VLine)
self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_2.setObjectName("line_2")
self.line_3 = QtWidgets.QFrame(self.centralwidget)
self.line_3.setGeometry(QtCore.QRect(500, 50, 16, 61))
self.line_3.setFrameShape(QtWidgets.QFrame.VLine)
self.line_3.setProperty("color", QtGui.QColor(0, 0, 0))
self.line_3.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_3.setObjectName("line_3")
self.radioButton = QtWidgets.QRadioButton(self.centralwidget)
self.radioButton.setGeometry(QtCore.QRect(20, 120, 91, 16))
self.radioButton.setChecked(False)
self.radioButton.setObjectName("radioButton")
self.radioButton.text = 'В разработке'
self.radioButton.toggled.connect(self.onClicked)
self.radioButton_2 = QtWidgets.QRadioButton(self.centralwidget)
self.radioButton_2.setGeometry(QtCore.QRect(20, 150, 181, 21))
self.radioButton_2.setObjectName("radioButton_2")
self.radioButton.text = 'Утверждённые к разработке'
self.radioButton_2.toggled.connect(self.onClicked)
self.radioButton_3 = QtWidgets.QRadioButton(self.centralwidget)
self.radioButton_3.setGeometry(QtCore.QRect(20, 180, 201, 21))
self.radioButton_3.setObjectName("radioButton_3")
self.radioButton.text = 'Обоснованные к разработке'
self.radioButton_3.toggled.connect(self.onClicked)
self.radioButton_4 = QtWidgets.QRadioButton(self.centralwidget)
self.radioButton_4.setGeometry(QtCore.QRect(230, 120, 161, 31))
self.radioButton_4.setObjectName("radioButton_4")
self.radioButton.text = 'Разработка ожидается/задерживается'
self.radioButton_4.toggled.connect(self.onClicked)
self.radioButton_5 = QtWidgets.QRadioButton(self.centralwidget)
self.radioButton_5.setGeometry(QtCore.QRect(460, 120, 171, 31))
self.radioButton_5.setObjectName("radioButton_5")
self.radioButton.text = 'Разработка не выяснена/нецелесообразна'
self.radioButton_5.toggled.connect(self.onClicked)
self.response = QtWidgets.QLabel(self.centralwidget)
self.response.setGeometry(QtCore.QRect(70, 260, 221, 41))
self.response.setText("")
self.response.setObjectName("response")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "converter"))
self.label.setText(_translate("MainWindow", "Промышленные проекты"))
self.label_2.setText(_translate("MainWindow", "Потенцильно промышленные проекты"))
self.label_3.setText(_translate("MainWindow", "Некоммерческие проектыl"))
self.radioButton.setText(_translate("MainWindow", "В разработке"))
self.radioButton_2.setText(_translate("MainWindow", "Утверждённые к разработке"))
self.radioButton_3.setText(_translate("MainWindow", "Обоснованные для разработки"))
self.radioButton_4.setText(_translate("MainWindow", "Разработка ожидается/задерживается"))
self.radioButton_5.setText(_translate("MainWindow", "Разработка не выяснена/нецелесообразна"))
def onClicked(self):
radioButton = self.sender()
if radioButton.isChecked():
self.response.setText(criteries.get(radioButton.text))
print(criteries.get(radioButton.text))
else:
print("1")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
当任何按钮被按下,并显示在控制台1
中,None
除了第一个,它给出1
和A5
我正在编写一个程序,它应该根据在 main.html 的多个选择标签中选择的内容输出某种响应
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Converter</title>
<script src="eel.js"></script>
</head>
<body>
<select name="type" id="type">
<option></option>
<option value="pp">Промышленные проекты</option>
<option value="ppp">Потенциально промышленные проекты</option>
<option value="np">Некоммерческие проекты </option>
</select>
<div id="project"></div>
<div id="response"></div>
<script type="text/javascript">
const type = document.getElementById("type");
const project = document.getElementById("project");
const response = document.getElementById("response");
var scnd;
async function changeOption_(){
let request = scnd.value;
let result = await eel.listener(request)();
response.innerHTML = result;
}
function changeOption(){
if (type.value == "pp"){
project.innerHTML = `<select name="scnd" id="scnd">
<option value=\"vr\">В разработке</option>
<option value=\"ukr\">Утверждённые к разработке</option>
<option value=\"okr\">Обоснованные к разработке</option>
</select>`;
scnd = document.getElementById("scnd");
scnd.addEventListener("change", changeOption_);
} else if(type.value == "ppp"){
project.innerHTML = `<select name="scnd" id="scnd">
<option value=\"n\">None</option>
<option value=\"ro\">Разработка ожидается/задерживается</option>
</select>`;
scnd = document.getElementById("scnd");
scnd.addEventListener("change", changeOption_);
}else{
project.innerHTML = `<select name="scnd" id="scnd">
<option value=\"n\">None</option>
<option value=\"rnv\">Разработка не выяснена/нецелесообразна</option>
</select>`;
scnd = document.getElementById("scnd");
scnd.addEventListener("change", changeOption_);
}
}
type.addEventListener("change", changeOption);
</script>
</body>
</html>
主文件
import eel
eel.init("web")
eel.start("main.html", size=(700,700))
criteries = {'vr':'Probable Reserves'}
@eel.expose
def listener(code):
return criteries.get(code)
但是当我输入数据希望获得可能的储备时,我什么也没得到,调试器中没有错误
我正在使用 eel python 库,但到目前为止主要代码是 js + html main.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Converter</title>
<script src="eel.js"></script>
</head>
<body>
<select name="type">
<option></option>
<option value="pp">Промышленные проекты</option>
<option value="ppp">Потенциально промышленные проекты</option>
<option value="np">Некоммерческие проекты </option>
</select>
<div name="project"></div>
<script type="text/javascript">
async function changeOption(){
if (type.options[type.selectedIndex].value == "pp"){
project.insertAdjacentHTML("afterbegin", "<select>
<option value=\"vr\">В разработке</option>
<option value=\"ukr\">Утверждённые к разработке</option>
<option value=\"okr\">Обоснованные к разработке</option>
</select>");
} else if(type.options[type.selectedIndex].value == "ppp"){
project.insertAdjacentHTML("afterbegin", "<select>
<option value=\"n\">None</option>
<option value=\"ro\">Разработка ожидается/задерживается</option>
</select>");
}else{
project.insertAdjacentHTML("afterbegin", "<select>
<option value=\"n\">None</option>
<option value=\"rnv\">Разработка не выяснена/нецелесообразна</option>
</select>");
}
}
type.addEventListener("change", changeOption);
</script>
</body>
</html>
主文件
import eel
eel.init("web")
eel.start("main.html", size=(700,700))
如您所见,脚本应该根据第一次选择中选择的内容创建一个新的选择标签,但这不会发生。
我正在尝试使用高级用户 models.py 更新我的项目中的迁移
class Teacher(AbstractUser):
name = models.CharField(max_length=20, unique=False)
surname = models.CharField(max_length=20)
email = models.EmailField(max_length=255, unique=True)
USERNAME_FIELD = 'email'
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True,
on_delete=models.CASCADE)
subject = models.ForeignKey(Subject, related_name='teacher_subject',
null=True, on_delete=models.CASCADE)
password = models.CharField(max_length=50)
REQUIRED_FIELDS = ['name', 'surname', 'password']
什么可能导致这样的错误?最初,这个问题出在 Teacher.username 上,我在 Google 上搜索到你需要添加 USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'surname', 'password'] 但显然它并没有好转
错误代码:
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "E:\Projects\mindless\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "E:\Projects\mindless\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "E:\Projects\mindless\django\core\management\base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "E:\Projects\mindless\django\core\management\base.py", line 364, in execute
output = self.handle(*args, **options)
File "E:\Projects\mindless\django\core\management\base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "E:\Projects\mindless\django\core\management\commands\migrate.py", line 234, in handle
fake_initial=fake_initial,
File "E:\Projects\mindless\django\db\migrations\executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "E:\Projects\mindless\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "E:\Projects\mindless\django\db\migrations\executor.py", line 245, in apply_migration
state = migration.apply(state, schema_editor)
File "E:\Projects\mindless\django\db\migrations\migration.py", line 124, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "E:\Projects\mindless\django\db\migrations\operations\fields.py", line 249, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "E:\Projects\mindless\django\db\backends\sqlite3\schema.py", line 137, in alter_field
super().alter_field(model, old_field, new_field, strict=strict)
File "E:\Projects\mindless\django\db\backends\base\schema.py", line 535, in alter_field
old_db_params, new_db_params, strict)
File "E:\Projects\mindless\django\db\backends\sqlite3\schema.py", line 359, in _alter_field
self._remake_table(model, alter_field=(old_field, new_field))
File "E:\Projects\mindless\django\db\backends\sqlite3\schema.py", line 286, in _remake_table
self.quote_name(model._meta.db_table),
File "E:\Projects\mindless\django\db\backends\base\schema.py", line 137, in execute
cursor.execute(sql, params)
File "E:\Projects\mindless\django\db\backends\utils.py", line 99, in execute
return super().execute(sql, params)
File "E:\Projects\mindless\django\db\backends\utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "E:\Projects\mindless\django\db\backends\utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "E:\Projects\mindless\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "E:\Projects\mindless\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "E:\Projects\mindless\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "E:\Projects\mindless\django\db\backends\sqlite3\base.py", line 383, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: new__me_teacher.email
使用 manage.py migrate 命令
最新迁移:
# Generated by Django 2.2.4 on 2021-05-24 13:35
from django.db import migrations, models
def forwards_func(apps, schema_editor):
User = apps.get_model("auth", "User")
db_alias = schema_editor.connection.alias
for x in Teachers.objects.filter(email='').count():
x.email = f'fake_email_{x.pk}@fake_email.fake'
class Migration(migrations.Migration):
dependencies = [
('me', '0007_auto_20210519_2106'),
]
operations = [
migrations.AlterField(
model_name='teacher',
name='email',
field=models.EmailField(max_length=255, unique=True),
),
migrations.RunPython(forwards_func),
]
当我尝试创建超级用户
python manage.py createsuperuser
我收到以下错误
django.db.utils.IntegrityError: NOT NULL constraint failed: me_teacher.subject_id
我/模特
from django.conf import settings
from django.contrib.auth.models import User, AbstractUser
from django.db import models
import sys
sys.path.append('../')
from wisdom.models import Subject
class Teacher(AbstractUser):
name = models.CharField(max_length=20)
surname = models.CharField(max_length=20)
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
subject = models.ForeignKey(Subject, related_name='teacher_subject',
on_delete=models.CASCADE)
智慧/模型
from django.db import models
class Subject(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True)
class Meta:
ordering = ['title']
def __str__(self):
return self.title
我的问题是什么?
我尝试通过继承 AbstractUser 来扩展 User 模型:
模型.py
class Teacher(AbstractUser):
name = models.CharField(max_length=20)
surname = models.CharField(max_length=20)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE,
related_name='teacher_subject')
person = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
设置.py
AUTH_USER_MODEL = 'education.Teacher'
表格.py
class TeacherRegistrationForm(UserCreationForm):
class Meta(UserCreationForm):
model = Teacher
fields = ('name','surname','subject')
class TeacherChangeForm(UserChangeForm):
class Meta:
model = Teacher
fields = ('name','surname','subject')
管理员.py
class TeacherUserAdmin(UserAdmin):
add_form = TeacherRegistrationForm
form = TeacherChangeForm
model = Teacher
list_display = ['name','surname','subject']
admin.site.register(Teacher, TeacherUserAdmin)
当我尝试创建迁移时,我得到了错误
courses.Course.owner: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out.
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'.
courses.Course.students: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out.
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'.
courses.File.owner: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out.
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'.
courses.Image.owner: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out.
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'.
courses.Text.owner: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out.
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'.
courses.Video.owner: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out.
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'.
我该怎么办?
有以下结构:
main - submain_1 - file1.py
- submain_2 - file2.py
如何从 file2 中的 file1 导入一个类?已经试过了
from ..submain_1.file1 import class
但我收到一个错误:'ValueError:尝试相对导入超出顶级包'
我需要添加一个指向我的 Django 站点的链接,该链接仅在用户在特定组中时才会出现。我试图写一个解决方案,但它引发了一堆错误
如果允许用户添加课程,则处理 button_for_teacher 模板。并且这个模板本身被插入到base.html中的include标签中
def is_instructor(request, username):
user = User.objects.get(username=username)
if user.has_perm('course.can_add_course'):
return render(request, 'courses/course/button_for_teacher.html')
button_for_teacher.html
{% extends "base.html" %}
{% block title %}
{% endblock %}
{% block content %}
<a href="{% url "manage_course_list" %}">Your courses</a>
{% endblock %}
base.html
{% include "courses/course/button_for_teacher.html" %}
在列表页面上显示每个人的课程列表并且应该有一个链接的视图
class CourseListView(TemplateResponseMixin, View):
model = Course
template_name = 'courses/course/list.html'
def get(self, request, subject=None):
subjects = Subject.objects.annotate(total_courses=Count('courses'))
courses = Course.objects.annotate(total_modules=Count('modules'))
if subject:
subject = get_object_or_404(Subject, slug=subject)
courses = courses.filter(subject=subject)
return self.render_to_response({'subjects':subjects,
'subject':subject,
'courses':courses})