编辑
根据@Jim Fasarakis Hilliard的回答,我知道这不是错误,而是预期的行为。因此,我想补充一个问题-我可以在类型检查器中以某种方式强制使用类似mypys --strict-optional的功能PyCharm吗?
观看了几段有关类型检查的视频后Python 3.5+,Pycharm我认为应该将其标记为错误的返回类型:
from typing import Optional, List
import random
def r() -> Optional[List[int]]:
if random.choice([0, 1]):
return [1, 2, 3]
return None
def f() -> List[int]:
return r()
Run Code Online (Sandbox Code Playgroud)
该f()函数可以返回list的intS或None它明确地规定,但PyCharm并不标志着return r()作为一个错误的返回。
def f() -> List[int]:
return None
Run Code Online (Sandbox Code Playgroud)
例如,如果f()函数如上所示,则PyCharm检测到错误的return类型。
是一个错误还是我应该更改某些设置?我将类型检查的严重性提高到error。
我有一个模特:
class Model(models.Model):
price = models.DecimalField(...)
Run Code Online (Sandbox Code Playgroud)
Model生产数据库中已有对象.现在我添加price_total字段到这个模型不可能null.
class Model(models.Model):
price = models.DecimalField(...)
price_total = models.DecimalField(...)
Run Code Online (Sandbox Code Playgroud)
我想这price_total等于price迁移之后.
就像是:
price_total = models.DecimalField(default=this_object.price,...)
Run Code Online (Sandbox Code Playgroud)
有可能以某种方式做到这一点吗?
我唯一知道的是:
price_total可空的price_total等于price例如通过django shellprice_total不能为空但这种方式有多种缺点,你可以忘记在生产中这样做,它有很多步骤等...
有没有更好的办法?
我需要一个匹配任何数字后跟一个字符串的正则表达式,该字符串由数字,空格,点和逗号后跟"Kč"或"Eur"组成.
问题是我regex有时候找不到所有这些字符串.
((\d[., \d]+)(K?|Eur))
Run Code Online (Sandbox Code Playgroud)
例如:
re.findall("""((\d[., \d]+)(K?|Eur))""","Letenky od 12 932 Kc?",flags=re.IGNORECASE)
Run Code Online (Sandbox Code Playgroud)
什么也不返回 [(12 932 K?,12 932,K?)]
你知道正则表达式有什么问题吗?
我需要在Django管理change页面中保留有关过滤和搜索的信息。
因此,当用户按 过滤时"?away_team__id__exact=267821",我需要将此查询附加到change pageurl。
假设我们通过上面的查询过滤了对象。这是更改列表的网址:
http://127.0.0.1:8000/matches/match/?away_team__id__exact=267821
Run Code Online (Sandbox Code Playgroud)
我想制作change将用户重定向到change当前对象页面并将查询附加到 url 的列,而不是:
http://127.0.0.1:8000/matches/match/2009/change/
Run Code Online (Sandbox Code Playgroud)
网址将是:
http://127.0.0.1:8000/matches/match/2009/change/?away_team__id__exact=267821
Run Code Online (Sandbox Code Playgroud)
问题是我无法在自定义列方法中访问请求。我尝试使用模板语言来做到这一点,但没有成功,我得到:
http://127.0.0.1:8000/matches/match/1996/change/?{{%20request.GET.urlencode%20}}
Run Code Online (Sandbox Code Playgroud)
这是方法:
def change(self,obj):
return mark_safe(f"""<a class="changelink" href="{reverse("admin:matches_match_change",args=(obj.pk,))}"""+"?{{ request.GET.urlencode }}\""+"><span class='icon'>Zmeni?</span></a>")
Run Code Online (Sandbox Code Playgroud)
你知道怎么做吗?
编辑
这是因为我需要在对象页面中创建一个NEXT和PREVIOUS按钮,change以便用户可以直接进入下一个对象。
我有一个UserProfile有许多必填(不是空而是空白)字段的字段,我试图在添加用户时不显示它。
我尝试了多种方法,例如:
def get_formsets_with_inlines(self, request, obj=None):
if not obj:
return []
return super().get_formsets_with_inlines(request, obj)
Run Code Online (Sandbox Code Playgroud)
但保存后User,django会引发错误,指出来自的字段UserProfile不能为空。
你知道如何让它发挥作用吗?
我正在尝试创建一个customCombobox像普通组件一样工作的组件,只需添加v-combobox一个即可 - 用户按下按键后tab,它将自动选择第一个选项(如果有)。
到目前为止我所做的看起来不错,但v-model在这个领域不起作用(总是如此null)。
<template>
<v-combobox ref="combobox" :rules="rules"
@keydown.tab.prevent="selectFirst"
:value="innerValue" :label="label"
:items="items"
>
</v-combobox>
</template>
<script>
module.exports = {
props: ['value', 'label', 'items', 'rules'],
data() {
return {
innerValue:null,
}
},
watch:{
value(_new){
this.innerValue = _new
this.$emit('input',[_new])
this.$emit('change')
}
},
methods: {
selectFirst() {
var combobox = this.$refs.combobox
var filteredItems = combobox.filteredItems
if (filteredItems.length){
this.innerValue = filteredItems[0]
}
}
},
computed: {
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
你知道为什么吗?
我正在尝试提供zip包含Django对象图像的文件。
问题是,即使返回 Zip 文件,它也已损坏。
注意:由于我使用远程存储,因此我无法使用文件的绝对路径。
应在内存中生成 zip 的模型方法
def generate_images_zip(self) -> bytes:
content = BytesIO()
zipObj = ZipFile(content, 'w')
for image_fieldname in self.images_fieldnames():
image = getattr(self, image_fieldname)
if image:
zipObj.writestr(image.name, image.read())
return content.getvalue()
Run Code Online (Sandbox Code Playgroud)
视图集动作
@action(methods=['get'], detail=True, url_path='download-images')
def download_images(self, request, pk=None) -> HttpResponse:
product = self.get_object()
zipfile = product.generate_images_zip()
response = HttpResponse(zipfile, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=images.zip'
return response
Run Code Online (Sandbox Code Playgroud)
当我尝试打开下载的 Zip 文件时,它说它已损坏。
你知道如何让它发挥作用吗?
我正在尝试注册全局过滤器,Vue3但它引发了此错误:
main.js?56d7:13 Uncaught TypeError: Cannot read property 'globalProperties' of undefined
Run Code Online (Sandbox Code Playgroud)
根据Vue3 中的 Use 过滤器,但无法读取 globalProperties它应该可以工作。
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import "./assets/tailwind.css";
import axiosSetUp from "@/auth/axiosSetUp";
import {formatIsoDateTime as utils_formatIsoDateTime} from "@/utils";
axiosSetUp()
const app = createApp(App).use(store).use(router).mount("#app");
app.config.globalProperties.$filters = {
formatIsoDateTime(isoString) {
return utils_formatIsoDateTime(isoString)
}
}
Run Code Online (Sandbox Code Playgroud)
你知道问题出在哪里吗?
编辑:这个问题最初是在使用时发布的,yasg但我切换到了spectacular所以两种解决方案都可以。
我很好奇是否有办法告诉参数yasg或spectacular向django-filter参数添加描述。
我想告诉开发者,parent领域就是一个Country模型pk。
模型
class County(AddressModel):
parent = models.ForeignKey('Country', verbose_name='Krajina', related_name='counties', on_delete=models.PROTECT, help_text='Krajina')
class Meta:
verbose_name = 'Kraj'
verbose_name_plural = 'Kraje'
Run Code Online (Sandbox Code Playgroud)
筛选
class CountyFilter(FilterSet):
class Meta:
model = County
fields = {
'name': ['icontains'],
'parent': ['exact']
}
Run Code Online (Sandbox Code Playgroud)
串行器
class CountySerializer(serializers.ModelSerializer):
class Meta:
model = County
fields = ['id', 'name']
Run Code Online (Sandbox Code Playgroud)
看法
class AddressCountyAutocompleteView(ListAPIView):
serializer_class = CountySerializer
filter_backends = [DjangoFilterBackend]
filterset_class = CountyFilter
queryset = County.objects.all() …Run Code Online (Sandbox Code Playgroud) python django django-rest-framework drf-yasg drf-spectacular
此代码应该将一些文本写入文件。当我尝试将文本写入控制台时,一切正常。但是当我尝试将文本写入文件时,出现 UnicodeEncodeError。我知道,这是一个常见的问题,可以使用正确的解码或编码来解决,但我尝试过它仍然得到相同的 UnicodeEncodeError。我究竟做错了什么?
我附上了一个例子。
print "(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)".decode("utf-8")%(dict.get('name'),dict.get('description'),dict.get('ico'),dict.get('city'),dict.get('ulCislo'),dict.get('psc'),dict.get('weby'),dict.get('telefony'),dict.get('mobily'),dict.get('faxy'),dict.get('emaily'),dict.get('dic'),dict.get('ic_dph'),dict.get('kategorie')[0],dict.get('kategorie')[1],dict.get('kategorie')[2])
Run Code Online (Sandbox Code Playgroud)
(StarBuy sro、Inzertujte 的照片、auto-moto、oble?enie、reality、prácu、zvieratá、starožitnosti、dovolenky、nábytok、všetko pre deti、obuv、stroj....
with open("test.txt","wb") as f:
f.write("(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)".decode("utf-8")%(dict.get('name'),dict.get('description'),dict.get('ico'),dict.get('city'),dict.get('ulCislo'),dict.get('psc'),dict.get('weby'),dict.get('telefony'),dict.get('mobily'),dict.get('faxy'),dict.get('emaily'),dict.get('dic'),dict.get('ic_dph'),dict.get('kategorie')[0],dict.get('kategorie')[1],dict.get('kategorie')[2]))
Run Code Online (Sandbox Code Playgroud)
UnicodeEncodeError: 'ascii' 编解码器无法对位置 50 中的字符 u'\u010d' 进行编码:序号不在范围内 (128)
问题可能出在哪里?
python ×8
django ×5
python-3.x ×3
django-admin ×2
javascript ×2
vue.js ×2
database ×1
django-2.0 ×1
drf-yasg ×1
encoding ×1
pycharm ×1
python-3.5 ×1
regex ×1
typing ×1
unicode ×1
vue-events ×1
vuejs3 ×1
vuetify.js ×1
zip ×1