blank

#blank#

已有0人关注此标签

内容分类

python小能手

ImportError:无法导入名称'Message' - django-messages

我分叉了https://github.com/arneb/django-messages/并把它放在我的仓库中:https://github.com/mike-johnson-jr/django-messages/ 当我使用该包时,我在标题中收到错误。完全追溯: Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "/home/michael/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/michael/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/michael/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/michael/.local/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/michael/.local/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in _call_with_frames_removed File "/home/michael/.local/lib/python3.6/site-packages/django_messages/models.py", line 48, in class Message(models.Model): File "/home/michael/.local/lib/python3.6/site-packages/django_messages/models.py", line 87, in Message get_absolute_url = reverse(get_absolute_url) File "/home/michael/.local/lib/python3.6/site-packages/django/urls/base.py", line 90, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/home/michael/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 562, in _reverse_with_prefix self._populate() File "/home/michael/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 413, in _populate for url_pattern in reversed(self.url_patterns): File "/home/michael/.local/lib/python3.6/site-packages/django/utils/functional.py", line 37, in get res = instance.__dict__[self.name] = self.func(instance) File "/home/michael/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/michael/.local/lib/python3.6/site-packages/django/utils/functional.py", line 37, in get res = instance.__dict__[self.name] = self.func(instance) File "/home/michael/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in _call_with_frames_removed File "/home/michael/projects/datafix/datafix/urls.py", line 65, in path('messages/', include('django_messages.urls')), File "/home/michael/.local/lib/python3.6/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in _call_with_frames_removed File "/home/michael/.local/lib/python3.6/site-packages/django_messages/urls.py", line 4, in from django_messages.views import * File "/home/michael/.local/lib/python3.6/site-packages/django_messages/views.py", line 11, in from django_messages.models import Message ImportError: cannot import name 'Message'这里是我的django_messages.models代码: @python_2_unicode_compatibleclass Message(models.Model): """ A private message from user to user """ subject = models.CharField(_("Subject"), max_length=140) body = models.TextField(_("Body")) sender = models.ForeignKey(AUTH_USER_MODEL, related_name='sent_messages', verbose_name=_( "Sender"), on_delete=models.SET_NULL) recipient = models.ForeignKey(AUTH_USER_MODEL, related_name='received_messages', null=True, blank=True, verbose_name=_("Recipient"), on_delete=models.SET_NULL) parent_msg = models.ForeignKey('self', related_name='next_messages', null=True, blank=True, verbose_name=_("Parent message"), on_delete=models.SET_NULL) sent_at = models.DateTimeField(_("sent at"), null=True, blank=True) read_at = models.DateTimeField(_("read at"), null=True, blank=True) replied_at = models.DateTimeField(_("replied at"), null=True, blank=True) sender_deleted_at = models.DateTimeField( _("Sender deleted at"), null=True, blank=True) recipient_deleted_at = models.DateTimeField( _("Recipient deleted at"), null=True, blank=True) objects = MessageManager()

python小能手

使用带有2个主键模型基于view UpdateView的类

我正在构建一个带有两个主键的应用程序(它是一个遗留数据库)。 基本上我想要做的是单击表元素并根据模型上的主键重定向到另一个页面。 我没有找到任何关于如何使用Django基于类的视图执行此操作 这是我的代码: models.py class RmDadoscarteira(models.Model): dtcalculo = models.DateField(db_column='dtCalculo', primary_key=True) # Field name made lowercase. cdcarteira = models.CharField(db_column='cdCarteira', max_length=50) # Field name made lowercase. nmcarteira = models.CharField(db_column='nmCarteira', max_length=255, blank=True, null=True) # Field name made lowercase. pl = models.FloatField(db_column='PL', blank=True, null=True) # Field name made lowercase. retornocota1d = models.FloatField(db_column='RetornoCota1d', blank=True, null=True) # Field name made lowercase. var = models.FloatField(db_column='Var', blank=True, null=True) # Field name made lowercase. var_lim = models.FloatField(db_column='VaR_Lim', blank=True, null=True) # Field name made lowercase. var_variacao1d = models.FloatField(db_column='VaR_Variacao1d', blank=True, null=True) # Field name made lowercase. var_variacao63d = models.FloatField(db_column='VaR_Variacao63d', blank=True, null=True) # Field name made lowercase. var_consumolimite = models.FloatField(db_column='VaR_ConsumoLimite', blank=True, null=True) # Field name made lowercase. stress = models.FloatField(db_column='Stress', blank=True, null=True) # Field name made lowercase. stress_lim = models.FloatField(db_column='Stress_Lim', blank=True, null=True) # Field name made lowercase. stress_variacao1d = models.FloatField(db_column='Stress_Variacao1d', blank=True, null=True) # Field name made lowercase. stress_variacao63d = models.FloatField(db_column='Stress_Variacao63d', blank=True, null=True) # Field name made lowercase. stress_consumolimite = models.FloatField(db_column='Stress_ConsumoLimite', blank=True, null=True) # Field name made lowercase. grupo = models.CharField(db_column='Grupo', max_length=20, blank=True, null=True) # Field name made lowercase. var_pl = models.FloatField(db_column='VaR_PL', blank=True, null=True) # Field name made lowercase. stress_pl = models.FloatField(db_column='Stress_PL', blank=True, null=True) # Field name made lowercase. objetos = models.Manager() class Meta: managed = False db_table = 'RM_DadosCarteira' unique_together = (('dtcalculo', 'cdcarteira'),) views.py from django.shortcuts import render, HttpResponsefrom .models import *import jsonimport pandas as pdfrom django.views.generic.base import TemplateViewfrom django.urls import reverse_lazyfrom django.views.generic.edit import UpdateView # View do relatorio Flagship Solutions #def FlagshipSolutions(request): # render(request, 'dash_solutions_completo.html') class VisualizaFundoSolutions(UpdateView): template_name = "prototipo_fundo.html" model = RmDadoscarteira context_object_name = 'fundos_metricas' fields = 'all' success_url = reverse_lazy("portal_riscos:dash_solutions") def FlagshipSolutions(request): # Queryset Tabela Diaria query_carteira = RmDadoscarteira.objetos.filter(grupo='Abertos') # Data Mais recente dt_recente = str(query_carteira.latest('dtcalculo').dtcalculo) # Filtrando queryset para data mais recente query_carteira = query_carteira.filter(dtcalculo=dt_recente) # Preparando os dados para o grafico de utilizacao de var e stress util_var = [round(obj['var_consumolimite'] * 100,2) for obj in query_carteira.values()] util_stress = [round(obj['stress_consumolimite'] * 100,2) for obj in query_carteira.values()] # Queryset Historico Graficos ### Definir um filtro de data query_hist = RmHistoricometricas.objetos.filter(grupo='Abertos').filter(dtcalculo__gte='2018-07-11') ### Queryset temporario ate dados de retorno e var estarem iguais query_data = RmHistoricometricas.objetos.filter(grupo='Abertos').filter(dtcalculo__gte='2018-07-11').filter(info='% VaR') ## Data Frames de Saida # Data Frame Historico df_hist = pd.DataFrame(list(query_hist.values())) # Criando uma chave de concateno df_hist['concat'] = df_hist['dtcalculo'].astype(str) + df_hist['cdcarteira'] df_hist['valor'] = round(df_hist['valor'] * 100, 2) # Data Frame VaR PL Historico df_hist_var = df_hist[df_hist['info']=='% VaR'] # Data Frame Stress PL Historico df_hist_stress = df_hist[df_hist['info']=='% Stress'] # Data Frame Consumo VaR df_hist_var_cons = df_hist[df_hist['info']=='% Utilização Limite VaR'] # Data Frame Consumo Stress df_hist_stress_cons = df_hist[df_hist['info']=='% Utilização Limite Stress'] # Data Frame de Retorno df_hist_ret = df_hist[df_hist['info']=='Retorno'] # Obtendo todas as datas (removendo duplicados) #datas = df_hist.dtcalculo.drop_duplicates(keep='first').reset_index(drop=True) datas = pd.DataFrame(list(query_data.values())) datas = datas.dtcalculo.drop_duplicates(keep='first').reset_index(drop=True) # Obtendo o nome de todos os fundos (removendo duplicados) fundos = list(df_hist.cdcarteira.drop_duplicates(keep='first').reset_index(drop=True)) # Criando um data frame unico com todas as informacoes a serem utilizadas df_hist_saida = pd.DataFrame(columns=['dtcalculo', 'cdcarteira']) # Criando um data frame com o numero de linhas igual a fundos * datas for fundo in fundos: # Data Frame temporario df_temp = pd.DataFrame(columns=['dtcalculo', 'cdcarteira']) # Copiando as datas df_temp['dtcalculo'] = datas # Inserindo o nome do fundo df_temp['cdcarteira'] = [fundo] * len(datas) # Inserindo dados do temp no data frame de saida df_hist_saida = df_hist_saida.append(df_temp) # Resetando index e criando uma chave de concateno para o dataframe de saida df_hist_saida = df_hist_saida.reset_index(drop=True) df_hist_saida['concat'] = df_hist_saida['dtcalculo'].astype(str) + df_hist_saida['cdcarteira'] # Criando coluna de var pl df_hist_saida = df_hist_saida.merge(df_hist_var[['concat', 'valor']], on='concat', how='left') df_hist_saida = df_hist_saida.rename(columns={'valor': 'var_pl'}) # Criando coluna de var pl df_hist_saida = df_hist_saida.merge(df_hist_stress[['concat', 'valor']], on='concat', how='left') df_hist_saida = df_hist_saida.rename(columns={'valor': 'stress_pl'}) # Criando coluna de consumo var df_hist_saida = df_hist_saida.merge(df_hist_var_cons[['concat', 'valor']], on='concat', how='left') df_hist_saida = df_hist_saida.rename(columns={'valor': 'var_cons'}) # Criando coluna de consumo stress df_hist_saida = df_hist_saida.merge(df_hist_stress_cons[['concat', 'valor']], on='concat', how='left') df_hist_saida = df_hist_saida.rename(columns={'valor': 'stress_cons'}) # Criando coluna de retorno df_hist_saida = df_hist_saida.merge(df_hist_stress_cons[['concat', 'valor']], on='concat', how='left') df_hist_saida = df_hist_saida.rename(columns={'valor': 'retorno'}) # Removendo a coluna concatenado df_hist_saida = df_hist_saida.drop('concat', axis=1) # Substituindo NaN por none df_hist_saida = df_hist_saida.fillna('None') # Criando dicionarios de saida dict_var_pl_hist = dict() dict_stress_pl_hist = dict() dict_var_cons_hist = dict() dict_stress_cons_hist = dict() for fundo in fundos: dict_var_pl_hist[fundo] = list(df_hist_saida[df_hist_saida['cdcarteira'] == fundo].var_pl) dict_stress_pl_hist[fundo] = list(df_hist_saida[df_hist_saida['cdcarteira'] == fundo].stress_pl) dict_var_cons_hist[fundo] = list(df_hist_saida[df_hist_saida['cdcarteira'] == fundo].var_cons) dict_stress_cons_hist[fundo] = list(df_hist_saida[df_hist_saida['cdcarteira'] == fundo].stress_cons) # Lista contendo todas as datas utilizadas lista_datas = list(datas.astype(str)) # Alertas alerta_1 = [70] * len(datas) alerta_2 = [85] * len(datas) alerta_3 = [100] * len(datas) # Flagship context ={'query_carteira': query_carteira, 'fundos': json.dumps(fundos), 'util_var': json.dumps(util_var), 'util_stress': json.dumps(util_stress,), 'dict_var_pl_hist': json.dumps(dict_var_pl_hist, default=dict), 'dict_stress_pl_hist': json.dumps(dict_stress_pl_hist, default=dict), 'dict_var_cons_hist': json.dumps(dict_var_cons_hist, default=dict), 'dict_stress_cons_hist': json.dumps(dict_stress_cons_hist, default=dict), 'datas_hist': json.dumps(lista_datas, default=str), 'alerta_1': json.dumps(alerta_1), 'alerta_2': json.dumps(alerta_2), 'alerta_3': json.dumps(alerta_3), } return render(request, 'dash_solutions_completo.html', context) urls.py # Importamos a função index() definida no arquivo views.py from portal_riscos.views import *from django.urls import pathfrom django.contrib.auth.views import LoginView app_name = 'portal_riscos' # urlpatterns contém a lista de roteamento URLs urlpatterns = [ # Dashboard Solutions path('', FlagshipSolutions, name='dash_solutions'), path('solutions_fundos/<pk>/<cdcarteira>', VisualizaFundoSolutions.as_view(), name='solutions_fundos') ] 我要点击并重定向的表格的一部分 class="btn btn-light btn-sm">Atualizar</a> 那是我得到的错误: Environment: Request Method: GETRequest URL: Django Version: 2.1.2Python Version: 3.6.1Installed Applications:['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'portal_riscos', 'widget_tweaks', 'django.contrib.humanize']Installed Middleware:['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:UsersTBMEPYGAppDataLocalContinuumAnaconda3libsite-packagesdjangocorehandlersexception.py" in inner response = get_response(request)File "C:UsersTBMEPYGAppDataLocalContinuumAnaconda3libsite-packagesdjangocorehandlersbase.py" in _get_response response = self.process_exception_by_middleware(e, request)File "C:UsersTBMEPYGAppDataLocalContinuumAnaconda3libsite-packagesdjangocorehandlersbase.py" in _get_response response = wrapped_callback(request, callback_args, *callback_kwargs)File "C:UsersTBMEPYGAppDataLocalContinuumAnaconda3libsite-packagesdjangoviewsgenericbase.py" in view return self.dispatch(request, args, *kwargs)File "C:UsersTBMEPYGAppDataLocalContinuumAnaconda3libsite-packagesdjangoviewsgenericbase.py" in dispatch return handler(request, args, *kwargs)File "C:UsersTBMEPYGAppDataLocalContinuumAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get self.object = self.get_object()File "C:UsersTBMEPYGAppDataLocalContinuumAnaconda3libsite-packagesdjangoviewsgenericdetail.py" in get_object obj = queryset.get()File "C:UsersTBMEPYGAppDataLocalContinuumAnaconda3libsite-packagesdjangodbmodelsquery.py" in get (self.model._meta.object_name, num)Exception Type: MultipleObjectsReturned at /solutions_fundos/2019-01-14/FICFI52865Exception Value: get() returned more than one RmDadoscarteira -- it returned 21!

python小能手

列“user_id”中的空值违反了非空约束Django形式

尝试为用户个人资料页面实现文件上载。我收到以下错误: 列“user_id”中的空值违反非空约束DETAIL:失败行包含(35,profile / {now:%Y /%m / YmdHMSext_xg2iZ6M,null,null)。 我已经读过它可能与User_ID有关,我试过传递form.user = request.user,但是没有用。还有两个空值,而不仅仅是一个空值。 Models.py class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_('Name of User'), blank=True, max_length=255) #accepted_terms_of_service = models.Booleanfield() def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username}) Profile Imagedef upload_to(instance, filename): now = timezone_now() base, ext = os.path.splitext(filename) ext = ext.lower() return "profile/{now:%Y/%m/%Y%m%d%H%M%S}{ext}" class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete='CASCADE', related_name='user_profile') school = models.CharField(max_length=30, null=True, blank=True) image = models.ImageField(_("Picture"), upload_to=upload_to, null=True, blank=True) def __str__(self): return self.user.username views.py @login_requireddef add_image(request): form = ProfileImageForm() #form.user = request.user if request.method == "POST": form = ProfileImageForm(data=request.POST, files=request.FILES) if form.is_valid(): form.save() return redirect('userPage') else: return render(request, "users/user_image_form.html", {"form": form }) forms.py class ProfileImageForm(forms.ModelForm): class Meta: model = Profile fields = ["image"]

中间件小哥

性能测试 PTS 有奖分享,新年大礼包等你拿!

写在活动规则前面的话 阿里云性能测试 PTS,一款超好用的压测工具。 无论是自研还是适配开源的功能,PTS 都可以轻松模拟大量用户访问业务的场景,任务随时发起,免去搭建和维护成本。更是紧密结合阿里云监控类产品提供一站式监控、定位等附加价值,高效检验和管理业务性能。 2019年1月,PTS 正式发布了集成JMeter的功能,支持JMeter脚本导入转化为原生PTS压测场景,便于将存量测试用例迁移到控制能力更强的PTS引擎上。 关于性能测试 PTS,了解更多戳这里 > https://www.aliyun.com/product/pts?source_type=activity201901 那么,在系统或软件的开发生命周期中,你通常是什么时候才会做性能测试呢? 听到最多的答案就是新业务上线前,或者大促之前需要压一压、测一测,修复性能瓶颈,保障系统在大促来临之际能够稳定运行,抗住大流量。 另外一种情况是我们需要压出基线,基线就是,比如我的系统通常能支持 2000 QPS,每次系统更新上线会做一次常规压测,看系统性能是否能维持在基线上。当然,系统能够支持 2000 QPS,也是需要通过压测才能知道的。 现在,立刻,马上来体验一把 PTS,秀出你的压测才华和实践分享吧! 活动时间 活动参与时间:2019年1月17日-2019年3月15日奖品发放时间:2019年3月20日前公布结果,3月25日前发放完成 我猜你,一定最先想知道有哪些丰富的奖品~~ 奖项1:【PTS 最佳分享】 极客分享奖 ¥800 x 1  淘宝心选铝镁合金仿碳纤维皮纹旅行箱 先锋分享奖 ¥499 x 4  JBL入耳式耳机 优秀分享奖 ¥ 220 x 6 星巴克 16oz小猪欢腾不锈钢保温杯 天猫精选款 踊跃分享奖 ¥98 x 15 百草味年货大礼包   奖项2:【PTS 定义有奖】 在话题下留言,用一句优美/极客/别具匠心...的话,定义性能测试PTS,选出9个准确且最具创意的定义,送¥30元淘宝心选毛巾一条(限6条)或云栖社区定制奖品一个(云栖定制电脑包、无线鼠标、移动电源-随机发放)**。友情提示:准确+别具匠心,更容易拿奖哦~(喜欢什么奖品,可顺便留言哦~) 如何挑选【PTS 最佳分享】,如何保证活动的公正性? 我们邀请了来自阿里云中间件技术部的技术和产品专家们,组成评委组,所有评测报告将匿名提报至评委组,进行严格、客观和公正的评分。 专家团 高可用团队技术总监 游骥中间件产品总监 丹臣PTS产品专家 燕顺PTS技术专家 隐寒PTS产品经理 牛兔 评分标准 必须以 PTS 压测为主体的使用评测内容; 逻辑思路清晰,内容结构完整; 对产品提出了改进建议、可操作性强 观点充分,论据充足,有独特见解,具有创新性 图文并茂 作品必须为原创,且未在任何平台发布过;一经发现抄袭或已在其他平台发布过,则将取消参与资格。 挑战赛中,你要做什么? 1、在此登记参与活动 > https://page.aliyun.com/form/act1965942747/index.htm(只有完成登记才可以参与活动评奖,前100名可以获得¥10 产品代金券,免费参与活动)(代金券将分三个批次定向发放至阿里云账户中,发放完成后于钉钉群内公布)2、2019年1月17日-2019年3月15日 体验 PTS,并且在聚能聊话题留言区内分享你的体验和实践操作。3、2019年3月20日在钉钉群内或聚能聊话题中,查看获奖名单 关于分享内容,你可以分享哪些内容? 1、在话题中晒出你的使用过程、压测报告、使用感想、使用场景、发现的瓶颈等。2、您可以使用截图,帮您记录整个操作过程。3、最好,你可以尽量还原在实际使用中的场景。4、当然,你也可以加入,对比其他的相关产品,PTS好在哪里,不好在哪里,以及你的使用体感。 什么样的分享有可能获奖?请参考留言区的官方分享示例 你必须知道的活动规则 1、本次活动的主体是阿里云中间件技术部,分享获奖名单以官方公布为准;2、分享内容严禁抄袭,一旦发现将取消参与资格;3、本次分享活动所有投稿作品的著作权依然归作者所有,但阿里云中间件技术部拥有该作品的使用权。(投稿作品会在脱敏后使用)4、本次在留言区内参与定义PTS活动的著作权依然归作者所有,但阿里云中间件技术部拥有该定义的使用权。5、若投稿质量不高,奖项可空缺;空缺奖项将叠加至下一轮活动。 还有不清楚的?立即钉钉扫码入群提问 活动答疑、获奖名单公布、及时沟通

瓜田夜行人

wordpress登录后转至wp-admin为空白页

wordpress网站应该是被黑了,首先恶意注入代码,被我debug清理掉了,但是现在登录后却无法操作wp-admin界面,为空白页。还发现了两篇垃圾博客文章。 我测试过wp-admin白屏的常见解决方案(例如themes或plugins不兼容造成),但这一次都不是。