小编HuL*_*iCa的帖子

如何覆盖 Django Rest Framework 视图集 perform_create() 方法以将默认值设置为字段

我有一个名为的模型Product和两个以不同方式管理同一个模型的视图集。每个人都必须为 field 设置不同的值product_type,该值在序列化程序中设置为 read_only SuplementSerializer

我试图覆盖perform_create()method 并设置 field 的值product_type,但它始终采用默认值。

这是我的模型:

class Product(models.Model):
    ROOM = 'ROOM'
    SUPLEMENT = 'SUPLEMENT'
    PRODUCT_TYPE_CHOICES = (
        (ROOM, _('Room')),
        (SUPLEMENT, _('Suplement'))
    )

    hotel = models.ForeignKey(Hotel, on_delete=models.PROTECT, related_name='products', verbose_name=_('Hotel'))
    name = models.CharField(max_length=100, verbose_name=_('Name'))
    product_type = models.CharField(max_length=9, choices=PRODUCT_TYPE_CHOICES, default=ROOM, verbose_name=_('Product Type'))
    room_type = models.ForeignKey(RoomType, null=True, blank=True, on_delete=models.PROTECT, related_name='products', verbose_name=_('Room Type'))
    plan_type = models.ForeignKey(PlanType, null=True, blank=True, on_delete=models.PROTECT, related_name='products', verbose_name=_('Plan Type'))
    content_type = models.ForeignKey(ContentType, null=True, blank=True, on_delete=models.PROTECT, related_name='rate_base_products', verbose_name=_('Rate Base'))
    object_id …
Run Code Online (Sandbox Code Playgroud)

python django django-rest-framework

5
推荐指数
1
解决办法
7038
查看次数

在Ubuntu 14.04上安装Neo4j失败

我正在尝试按照http://neo4j.com/docs/operations-manual/current/installation/linux/debian/?_ga=2.249168388.2041192375.1507250087-893468657.1507250087中的指定在ubuntu 14.04中安装neo4j

我正在使用的安装说明是

sudo apt-get install neo4j=3.2.3
Run Code Online (Sandbox Code Playgroud)

但这不起作用

Reading package lists... Done
Building dependency tree       
Reading state information... Done
E: Unable to locate package neo4j
Run Code Online (Sandbox Code Playgroud)

我会很感激

neo4j ubuntu-14.04

4
推荐指数
1
解决办法
1037
查看次数

Django自定义身份验证后端不起作用

我希望我的Django项目使用他们的电子邮件而不是用户名来验证用户身份.我遵循了这个建议,但它不起作用.

这是我的 EmailBackend

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend

class EmailBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwars):
        UserModel = get_user_model()
        try:
            user = UserModel.objects.get(email=username)
        except UserModel.DoesNotExist:
            return None
        else:
            if user.check_password(password):
                return user

        return None
Run Code Online (Sandbox Code Playgroud)

我已经添加AUTHENTICATION_BACKENDS = ['GeneralApp.utils.EmailBackend']settings.py中,当它被注释时,我可以使用用户名登录,当我取消注释它时,我再也无法登录了.我已经发现代码GeneralApp.utils.EmailBackend.authenticate()永远不会被执行,但我知道Django可以找到这个类,因为我故意拼错它并且我得到一个错误,当我纠正错字时,没有异常被提出.我也知道默认的身份验证后端是有效覆盖的,因为我不能用用户名登录.我有这个相同的解决方案在另一个项目中完美地工作,所以我无法理解为什么自定义的身份验证代码永远不会执行,当类完全定位AUTHENTICATION_BACKENDS设置为它.

python django

4
推荐指数
2
解决办法
1814
查看次数

Django 错误 __str__ 返回非字符串(类型 __proxy__)

我有使用一些模型GenericForeignKey,当我试图进入他们Django管理util的,我可以看到的记录列表,但是当我点击其中一个,我得到这个错误:__str__ returned non-string (type __proxy__)

这是其中一个模型的代码:

class ReservationComponent(models.Model):
    reservation = models.ForeignKey(Reservation, on_delete=models.PROTECT, related_name='components', verbose_name=_(''))
    day = models.DateField(verbose_name=_('Day'))
    content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    class Meta:
        verbose_name = _("Reservation Component")
        verbose_name_plural = _("Reservations Components")

    def __str__(self):
        return "[{}][{}]{} - [{}]{}".format(self.id, self.reservation, self.day, self.content_type, self.object_id)
Run Code Online (Sandbox Code Playgroud)

这是整个追溯:

Internal Server Error: /es/admin/ReservationsManagerApp/reservationcomponent/14/change/
Traceback (most recent call last):
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 158, in _get_response
    response = self.process_exception_by_middleware(e, …
Run Code Online (Sandbox Code Playgroud)

python django django-models

4
推荐指数
1
解决办法
2132
查看次数

如何使用 Axios 将 CSRF Coo​​kie 从 React 发送到 Django Rest Framework

我想从使用AxiosReact应用程序向Django Rest Framework后端发出POST请求。我设法从后端获取了CSRF 令牌,但我无法通过我的请求发送它,所以我总是收到错误消息:Forbidden (CSRF cookie not set.)

这是我的React应用程序的代码:

handleClick() {
    const axios = require('axios');
    var csrfCookie = Cookies.get('XSRF-TOKEN');
    console.log(csrfCookie)
    axios.post('http://127.0.0.1:8000/es/api-auth/login/',
      {
        next: '/',
        username: 'admin@admin.com',
        password: 'Cancun10!',
      },
      {
        headers: {
          'x-xsrf-token': csrfCookie,  // <------- Is this the right way to send the cookie?
        },
        withCredentials = true,
      }
    )
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    })
  }
Run Code Online (Sandbox Code Playgroud)

这是我的settings.pyCSRF 配置:

CORS_ALLOW_CREDENTIALS …
Run Code Online (Sandbox Code Playgroud)

csrf django-csrf django-rest-framework reactjs axios

4
推荐指数
2
解决办法
7448
查看次数

制作一个 React Material-UI 组件以贴在屏幕的右下角

我正在制作一个 CRUD 应用程序,我想将“创建”控件显示为一个Fab按钮,该按钮粘在屏幕的右侧,并在屏幕滚动时保持在那里。

最后,我可以让按钮在屏幕滚动时保持静止,但我找不到如何将其位置设置在屏幕右下角的方法。

这是我的组件的代码:

import React, { Component } from 'react';
import Cookies from 'js-cookie';
import axios from 'axios';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import Fab from '@material-ui/core/Fab';
import AddIcon from '@material-ui/icons/Add';
import Icon from '@material-ui/core/Icon';
import Album from './Album.js'

const styles = theme => ({ …
Run Code Online (Sandbox Code Playgroud)

reactjs material-ui

4
推荐指数
2
解决办法
9487
查看次数

无法在 Windows 上运行的 VSC 上调试 R 代码

我已经为在 Windows 上运行的 VSC 安装了以下扩展:R、R 调试器和 R 工具,但是,当我尝试调试某些 R 代码时,我收到以下消息:Please install the R package: "vscDebugger"

我尝试使用安装它install.packages("vscDebugger", repos="http://cran.us.r-project.org"),但失败了。

这是我的launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "R-Debugger",
            "name": "Launch R-Workspace",
            "request": "launch",
            "debugMode": "workspace",
            "workingDirectory": "${workspaceFolder}"
        },
        {
            "type": "R-Debugger",
            "name": "Debug R-File",
            "request": "launch",
            "debugMode": "file",
            "workingDirectory": "${workspaceFolder}",
            "file": "${file}"
        },
        { …
Run Code Online (Sandbox Code Playgroud)

r visual-studio-code

4
推荐指数
1
解决办法
7674
查看次数

如何在 Django Rest Framework ViewSet 中获取额外参数

我必须使用 Django Rest Framework 实现一个端点,它以这种方式接收额外的参数:

GET .../hotels_in_period/?check_in=2018-09-30&check_out=2018-10-10

端点应该接收参数check-incheck-out,但我不知道如何在list视图集的方法中获取它们。我以为它们可以作为 提供request.data,但事实并非如此。

我将不胜感激任何帮助。

python django django-rest-framework

3
推荐指数
1
解决办法
1374
查看次数

python-docx如何合并行单元格

我正在使用python-docx从数据创建 Word 文档。我可以毫无问题地创建所有行和单元格,但在某些情况下,当数据库中的当前记录在字段comment 中有一些内容时,我需要添加一个新行来显示长内容。

我尝试附加一个段落,但结果是注释附加在表格之后,我需要将其添加到当前表格行的下方。

我认为解决方案是附加一个合并所有单元格的表格行,但我找不到这样做的文档。

这是我生成 docx 文件的代码:

class OperationDOCXView(viewsets.ViewSet):
    exclude_from_schema = True

    def list(self, request):
        from ReportsManagerApp.controllers import Operations2Controller

        self.profile_id = request.query_params['profile_id']
        self.operation_date = request.query_params['operation_date']
        self.operation_type = request.query_params['operation_type']
        self.format = request.query_params['doc_format']

        operation_report_controller = Operations2Controller(self.profile_id, self.operation_date, self.operation_type)
        context = operation_report_controller.get_context()

        if self.format == 'json':
            return Response(context)
        else:
            word_doc = self.get_operation_word_file(request, context)

        return Response("{}{}{}".format(request.get_host(), settings.MEDIA_URL, word_doc))

    def get_operation_word_file(self, request, context):
        import unicodedata
        from django.core.files import File
        from django.urls import reverse
        from docx import Document
        from docx.shared …
Run Code Online (Sandbox Code Playgroud)

python python-docx

3
推荐指数
1
解决办法
3548
查看次数

如何在 Django 中使用反向获取完整 url

我想将访问服务的 url 保存在一个变量中,所以我正在使用reversenamefor 中的条目urlpatterns,我得到类似/es/general/provider_types/,但我想获得一个完整的 url,比如https://127.0.0.1:8000/es/general/provider_types/

这就是我使用的方式reverse

{'name': models.ProviderType._meta.verbose_name_plural.title(), 'url': reverse('rest_provider_types_list')}
Run Code Online (Sandbox Code Playgroud)

有什么办法可以做到这一点吗?

python django

2
推荐指数
1
解决办法
1952
查看次数