夏末的微笑

文章 评论 浏览 27

夏末的微笑 2025-02-20 22:30:25

更容易的解决方案是用阵列构造它(原始)。

template<int n>
struct array_container{
    int array[n];
    
    array_container(std::array<int, n> arrayIn)
    {
        std::copy(arrayIn.begin(), arrayIn.end(), array); 
    }
};

否则,您可能会弄乱variadic模板和参数解开包装。

The easier solution would be to construct it with an array(in place).

template<int n>
struct array_container{
    int array[n];
    
    array_container(std::array<int, n> arrayIn)
    {
        std::copy(arrayIn.begin(), arrayIn.end(), array); 
    }
};

Otherwise you can mess with variadic templates and parameter unpacking.

将新的构造函数添加到专用模板类

夏末的微笑 2025-02-20 20:13:57

查看 docs 您可以尝试使用> code>> code>> session.bulk_insert_mappings()

buffer = [
    {
        'data': "First test"
    },
    {
        'data': "Second test"
    }
]


with Session() as session:
    session.bulk_insert_mappings(Test, buffer)

Looking at the docs you could try to use session.bulk_insert_mappings().

buffer = [
    {
        'data': "First test"
    },
    {
        'data': "Second test"
    }
]


with Session() as session:
    session.bulk_insert_mappings(Test, buffer)

sqlalchemy批量插入语句在Postgres数据库中抛出attributeError

夏末的微笑 2025-02-20 17:38:58

指定相互依存的链接库的顺序是错误的。

如果库相互依赖,则链接的库的顺序确实很重要。通常,如果库a取决于库b,则liba 必须libb 在链接标志中。

例如:

// B.h
#ifndef B_H
#define B_H

struct B {
    B(int);
    int x;
};

#endif

// B.cpp
#include "B.h"
B::B(int xx) : x(xx) {}

// A.h
#include "B.h"

struct A {
    A(int x);
    B b;
};

// A.cpp
#include "A.h"

A::A(int x) : b(x) {}

// main.cpp
#include "A.h"

int main() {
    A a(5);
    return 0;
};

创建库:

$ g++ -c A.cpp
$ g++ -c B.cpp
$ ar rvs libA.a A.o 
ar: creating libA.a
a - A.o
$ ar rvs libB.a B.o 
ar: creating libB.a
a - B.o

编译:

$ g++ main.cpp -L. -lB -lA
./libA.a(A.o): In function `A::A(int)':
A.cpp:(.text+0x1c): undefined reference to `B::B(int)'
collect2: error: ld returned 1 exit status
$ g++ main.cpp -L. -lA -lB
$ ./a.out

为了重复重复,顺序很重要!

The order in which interdependent linked libraries are specified is wrong.

The order in which libraries are linked DOES matter if the libraries depend on each other. In general, if library A depends on library B, then libA MUST appear before libB in the linker flags.

For example:

// B.h
#ifndef B_H
#define B_H

struct B {
    B(int);
    int x;
};

#endif

// B.cpp
#include "B.h"
B::B(int xx) : x(xx) {}

// A.h
#include "B.h"

struct A {
    A(int x);
    B b;
};

// A.cpp
#include "A.h"

A::A(int x) : b(x) {}

// main.cpp
#include "A.h"

int main() {
    A a(5);
    return 0;
};

Create the libraries:

$ g++ -c A.cpp
$ g++ -c B.cpp
$ ar rvs libA.a A.o 
ar: creating libA.a
a - A.o
$ ar rvs libB.a B.o 
ar: creating libB.a
a - B.o

Compile:

$ g++ main.cpp -L. -lB -lA
./libA.a(A.o): In function `A::A(int)':
A.cpp:(.text+0x1c): undefined reference to `B::B(int)'
collect2: error: ld returned 1 exit status
$ g++ main.cpp -L. -lA -lB
$ ./a.out

So to repeat again, the order DOES matter!

什么是未定义的参考/未解决的外部符号错误,我该如何修复?

夏末的微笑 2025-02-20 08:47:28

检查文档在这里db.Collection('wortnaments')。document()正在返回对文档的引用。在您的代码中,您没有明确定义文档ID,因此正在自动化。然后,使用对文档的引用,您正在创建与该特定文档关联的新子集合。您可以阅读有关引用和子汇编的更多信息在这里

Check the docs here. db.collection('tournaments').document() is returning a reference to the document. In your code, you are not defining the document id explicitly, so it is being autogenerated. Then, using that reference to the document, you are creating a new subcollection associated with that specific document. You can read more about references and subcollections here.

如何将元素添加到集合中,然后在本文档中创建子集合?

夏末的微笑 2025-02-20 08:09:30

加载文档后,在所有扩展的节点上触发conscl()折叠它们:

$(document).ready(function(){
  $('#tree').find('.sim-icon-d').each(function(){
      $(this).click()
  })
});

After the document is loaded, trigger a click() on all expanded nodes to collapse them:

$(document).ready(function(){
  $('#tree').find('.sim-icon-d').each(function(){
      $(this).click()
  })
});

是否可以通过编程方式折叠所有Sim-Tree节点?

夏末的微笑 2025-02-20 06:12:59

函数上

with your_table as (
select 'ℂ

Use NORMALIZE function as in below example

with your_table as (
  select 'ℂ????????????????????????????????' col union all
  select 'Cartagena'
)
select *, normalize(col, NFKC) normalized_col
from your_table     

with output

enter image description here

如何更改BigQuery数据中的字体[数据清洁]

夏末的微笑 2025-02-18 01:35:35

这应该是

import React from "react";

export default function About() { let myStyle = { color:'white', backgroundColor:'black' } 
return ( <> <div>
<h1 className='my-3'>about me</h1>
<div className="accordion accordion-flush" id="accordionFlushExample">
<div className="accordion-item">
<h2 className="accordion-header" id="flush-headingOne">
<button style={myStyle} className="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseOne" aria-expanded="false" aria-controls="flush-collapseOne">
Accordion Item #1
</button>
</h2>
<div stle={myStyle} id="flush-collapseOne" className="accordion-collapse collapse" aria-labelledby="flush-headingOne" data-bs-parent="#accordionFlushExample">
<div className="accordion-body">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> className. This is the first item's accordion body.</div>
</div>
</div>
<div className="accordion-item">
<h2 className="accordion-header" id="flush-headingTwo">
<button style={myStyle} className="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseTwo" aria-expanded="false" aria-controls="flush-collapseTwo">
Accordion Item #2
</button>
</h2>
<div style={myStyle} id="flush-collapseTwo" className="accordion-collapse collapse" aria-labelledby="flush-headingTwo" data-bs-parent="#accordionFlushExample">
<div className="accordion-body">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> className. This is the second item's accordion body. Let's imagine this being filled with some actual content.</div>
</div>
</div>
<div className="accordion-item">
<h2 className="accordion-header" id="flush-headingThree">
<button style={myStyle} className="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseThree" aria-expanded="false" aria-controls="flush-collapseThree">
Accordion Item #3
</button>
</h2>
<div style={myStyle} id="flush-collapseThree" className="accordion-collapse collapse" aria-labelledby="flush-headingThree" data-bs-parent="#accordionFlushExample">
<div className="accordion-body">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> className. This is the third item's accordion body. Nothing more exciting happening here in terms of content, but just filling up the space to make it look, at least at first glance, a bit more representative of how this would look in a real-world application.</div>
</div>
</div>
</div>
</div>
<div className='container'> 
<button type="button" className="btn btn-primary my-3" >Primary</button>
</div>
</>
)}

您以错误的方式初始化的神秘性的,而

let myStyle = { color:'white', backgroundColor:'black' }

在DIV内部的样式参考时,

let myStyle { color:'white', backgroundColor:'balck' }

对于几个divs来说也是错误的,但它应该是样式的,但

也有一个div丢失,但可能是由于复制粘贴而引起的错误

阅读&amp;用初始化的var编写程序:)

This should work

import React from "react";

export default function About() { let myStyle = { color:'white', backgroundColor:'black' } 
return ( <> <div>
<h1 className='my-3'>about me</h1>
<div className="accordion accordion-flush" id="accordionFlushExample">
<div className="accordion-item">
<h2 className="accordion-header" id="flush-headingOne">
<button style={myStyle} className="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseOne" aria-expanded="false" aria-controls="flush-collapseOne">
Accordion Item #1
</button>
</h2>
<div stle={myStyle} id="flush-collapseOne" className="accordion-collapse collapse" aria-labelledby="flush-headingOne" data-bs-parent="#accordionFlushExample">
<div className="accordion-body">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> className. This is the first item's accordion body.</div>
</div>
</div>
<div className="accordion-item">
<h2 className="accordion-header" id="flush-headingTwo">
<button style={myStyle} className="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseTwo" aria-expanded="false" aria-controls="flush-collapseTwo">
Accordion Item #2
</button>
</h2>
<div style={myStyle} id="flush-collapseTwo" className="accordion-collapse collapse" aria-labelledby="flush-headingTwo" data-bs-parent="#accordionFlushExample">
<div className="accordion-body">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> className. This is the second item's accordion body. Let's imagine this being filled with some actual content.</div>
</div>
</div>
<div className="accordion-item">
<h2 className="accordion-header" id="flush-headingThree">
<button style={myStyle} className="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseThree" aria-expanded="false" aria-controls="flush-collapseThree">
Accordion Item #3
</button>
</h2>
<div style={myStyle} id="flush-collapseThree" className="accordion-collapse collapse" aria-labelledby="flush-headingThree" data-bs-parent="#accordionFlushExample">
<div className="accordion-body">Placeholder content for this accordion, which is intended to demonstrate the <code>.accordion-flush</code> className. This is the third item's accordion body. Nothing more exciting happening here in terms of content, but just filling up the space to make it look, at least at first glance, a bit more representative of how this would look in a real-world application.</div>
</div>
</div>
</div>
</div>
<div className='container'> 
<button type="button" className="btn btn-primary my-3" >Primary</button>
</div>
</>
)}

You've initialised myStyle in a wrong manner it is

let myStyle = { color:'white', backgroundColor:'black' }

while it was

let myStyle { color:'white', backgroundColor:'balck' }

Style reference inside div was also wrong for several divs where it is stle but it should be Style

There is also a div missing but it might be due to copy pasting error

READ & WRITE PROGRAMS WITH INITIALISED VARS IN MIND :)

为什么要创建一个样式对象以给组件的样式显示ReaCJS中的随机错误?

夏末的微笑 2025-02-18 01:16:19

尝试此代码以查看是否可以提供帮助 - 它简化了读取和处理,并使其更可读(用于维护和调试)。

有时,我们想打动人们并制作单线或紧凑的代码,从而牺牲可读性。我不建议这样做。

import itertools as it

K, M = map(int, input(), split())   

# reading the K lines and appending lists to LL
LL = []

for i in range(K):
    ll = list(map(int, input().strip().split()))
    LL.append(ll[1:])    # skip the first num

MAX = -1

# looping thr Cartesian Product of LL lists and get the max now
for i in it.product(*LL):
    MAX = max(sum(map(lambda x: x**2, i)) % M, MAX)

print(MAX)     

Try this code to see if it can help - it simplify the reading and processing and make it more readable (for maintain and debug).

Sometimes, we want to impress people and make one-liner or compact code, thus sacrifice the readability. I don't recommend that.

import itertools as it

K, M = map(int, input(), split())   

# reading the K lines and appending lists to LL
LL = []

for i in range(K):
    ll = list(map(int, input().strip().split()))
    LL.append(ll[1:])    # skip the first num

MAX = -1

# looping thr Cartesian Product of LL lists and get the max now
for i in it.product(*LL):
    MAX = max(sum(map(lambda x: x**2, i)) % M, MAX)

print(MAX)     

为什么python可以正确求和?

夏末的微笑 2025-02-18 01:00:31

鉴于您的规格我试图重现一个最小的例子。
您可以尝试做类似的事情:

#!/usr/bin/env bash

k="Y"

nr_0=("R" "R" "Y" "Y")
nr_1=("R" "Y" "Y" "Y")
nr_2=("Y" "R" "Y" "Y")
nr_3=("Y" "Y" "R" "Y")
nr_4=("Y" "Y" "Y" "R")
nr_5=("Y" "Y" "Y" "Y") # the winner
nr_6=("Y" "R" "Y" "Y")

for j in {0..6}; do
    tmp_array_name="nr_$j[@]"
    tmp_array=("${!tmp_array_name}")

    if [ "${tmp_array[0]}" == "$k" ] && [ "${tmp_array[1]}" == "$k" ] && [ "${tmp_array[2]}" == "$k" ] && [ "${tmp_array[3]}" == "$k" ]; then
        echo "The winner is $tmp_array_name - ${tmp_array[*]}"
    fi
done

使用此输出:
获胜者是NR_5 [@] -YYY Y

Given your specifications I tried to reproduce a minimal example.
You can try to do something like this:

#!/usr/bin/env bash

k="Y"

nr_0=("R" "R" "Y" "Y")
nr_1=("R" "Y" "Y" "Y")
nr_2=("Y" "R" "Y" "Y")
nr_3=("Y" "Y" "R" "Y")
nr_4=("Y" "Y" "Y" "R")
nr_5=("Y" "Y" "Y" "Y") # the winner
nr_6=("Y" "R" "Y" "Y")

for j in {0..6}; do
    tmp_array_name="nr_$j[@]"
    tmp_array=("${!tmp_array_name}")

    if [ "${tmp_array[0]}" == "$k" ] && [ "${tmp_array[1]}" == "$k" ] && [ "${tmp_array[2]}" == "$k" ] && [ "${tmp_array[3]}" == "$k" ]; then
        echo "The winner is $tmp_array_name - ${tmp_array[*]}"
    fi
done

With this output:
The winner is nr_5[@] - Y Y Y Y

如何在Bash中以其名称中的不同数字引用数组?

夏末的微笑 2025-02-17 20:24:43

x,y,z坐标后的列是占用率。一个是0.74,另一个为0.31。作为具有构象的分子的一部分。如果在所有结构中都找到了它,则值将为1.00

编辑:

我在Python中使用CCTBX。我必须道歉,它实际上是在两天前工作,但是当我去给您写一个例子时,该包并未得到认可。我一直在遇到问题,让它再次工作。我正在使用Windows,而我只是移至Linux解决此问题。 CCTBX有过滤器,您可以在其中分开这些集合。 A,B等是Altloc位置。

基本格式是打开文件。隔离层,提取原子,用搜索创建真相表,然后在真相表上选择。

我没有明确地做到这一点,但是您应该能够在Altloc搜索
参考:

from __future__ import absolute_import, division, print_function`
from iotbx.data_manager import DataManager`
import pandas as pd`
dm = DataManager()                   #   Initialize the DataManager and call it dm
dm.set_overwrite(True)                #   tell the DataManager to overwrite files with the same name
model_filename = "./files/1vir.pdb"    #   Name of model file`
m = dm.get_model(om_model_filename1)  #   Deliver model object with model info
pdb_hierarchy = m.get_hierarchy() # Get hierarchy object
pdb_atoms = pdb_hierarchy.atoms() # get atoms
sites_cart = m.get_sites_cart() # get atom list
sel_cache = pdb_hierarchy.atom_selection_cache()
#this next line may not be exactly right but along these lines, see reference
c_alpha_alpha_protein = sel_cache.selection("altloc A") # extract truth table
protein = sites_cart.select(c_alpha_sel_protein)
protein = sites_cart.select(c_alpha_sel_protein)
protein = pd.DataFrame( [i for i in protein], columns=['x', 'y', 'z'] )

# other examples that I know work`
# you can use other search parameters to set to isolate other components like solvents, ligands, etc.
c_alpha_sel_non_protein = sel_cache.selection("hetero") # isolate all non protein atom (ligand, H2O, AcOH...) XXX not case sensitive!
c_alpha_sel_proteinplus_not_ligand = sel_cache.selection("not resname 2ow") # XXX not case sensitive!
c_alpha_sel_ligand = sel_cache.selection("resname 2ow") # extract ligand truth table object

还有其他人做了自己的Python版本。只是浏览尚未使用:

prody如果您届时还没有得到一个示例,我将尝试将其放在一起。

The column after the x,y,z coordinates is the occupancy. One is 0.74 and the other is 0.31. As a fraction of the molecules that have the conformation. If it's found there in all the structures, the value would be 1.00

Edit:

I use cctbx in python. I have to apologize that it was literally working 2 days ago but when I went to write you an example, the package was not recognized. I've been having issue getting it to work again. I'm using windows and my just move to Linux for this issue. cctbx has filters where you can separate those sets. The A,B, etc is the altloc position.

Basic format is open file. Isolate hierarcy, extract atoms, create truth table with search and select on truth table.

I've not done it explicitly, but you should be able to search by altloc
reference: http://cci.lbl.gov/docs/cctbx/doc_models_hierarchy/

from __future__ import absolute_import, division, print_function`
from iotbx.data_manager import DataManager`
import pandas as pd`
dm = DataManager()                   #   Initialize the DataManager and call it dm
dm.set_overwrite(True)                #   tell the DataManager to overwrite files with the same name
model_filename = "./files/1vir.pdb"    #   Name of model file`
m = dm.get_model(om_model_filename1)  #   Deliver model object with model info
pdb_hierarchy = m.get_hierarchy() # Get hierarchy object
pdb_atoms = pdb_hierarchy.atoms() # get atoms
sites_cart = m.get_sites_cart() # get atom list
sel_cache = pdb_hierarchy.atom_selection_cache()
#this next line may not be exactly right but along these lines, see reference
c_alpha_alpha_protein = sel_cache.selection("altloc A") # extract truth table
protein = sites_cart.select(c_alpha_sel_protein)
protein = sites_cart.select(c_alpha_sel_protein)
protein = pd.DataFrame( [i for i in protein], columns=['x', 'y', 'z'] )

# other examples that I know work`
# you can use other search parameters to set to isolate other components like solvents, ligands, etc.
c_alpha_sel_non_protein = sel_cache.selection("hetero") # isolate all non protein atom (ligand, H2O, AcOH...) XXX not case sensitive!
c_alpha_sel_proteinplus_not_ligand = sel_cache.selection("not resname 2ow") # XXX not case sensitive!
c_alpha_sel_ligand = sel_cache.selection("resname 2ow") # extract ligand truth table object

There are others that have done their own python versions. Just browsing have have not used:

selaltloc on Github

prody

If I get my packages up again soon, I'll try to put an example together proper if you've not gotten it by then.

如何在PDB文件中解析替代原子信息?

夏末的微笑 2025-02-17 15:30:49

之所以发生,是因为您的CSS选择器是错误的,它仅适用于桌子而不是项目。另外,您可以删除尝试以外的,如果是“无”,则可以给链接一个默认值。

import scrapy


class ActaSpider(scrapy.Spider):
    name = 'acta_spider'
    start_urls = ['https://www.fcf.cat/acta/2022/futbol-11/cadet-primera-divisio/grup-2/1c/la-salle-bonanova-ce-a/1c/lhospitalet-centre-esports-b']

    def parse(self, response):
        for actaelements in response.css('table.acta-table tbody tr'):
            yield {
                'name': actaelements.css('a::text').get(),
                'link': actaelements.css('a::attr(href)').get(default='Link Error'),
            }

It happens because your css selector is wrong, it's just for the table and not the items. Also you can remove the try except and give the link a default value if it's "None".

import scrapy


class ActaSpider(scrapy.Spider):
    name = 'acta_spider'
    start_urls = ['https://www.fcf.cat/acta/2022/futbol-11/cadet-primera-divisio/grup-2/1c/la-salle-bonanova-ce-a/1c/lhospitalet-centre-esports-b']

    def parse(self, response):
        for actaelements in response.css('table.acta-table tbody tr'):
            yield {
                'name': actaelements.css('a::text').get(),
                'link': actaelements.css('a::attr(href)').get(default='Link Error'),
            }

为什么解析仅在每个表的第一项上发生

夏末的微笑 2025-02-17 13:46:58

稳定的基准确实支持自定义Envs。参见 docs

Stable baselines does support custom envs. See docs.

如何在自定义环境中培训RL代理?

夏末的微笑 2025-02-17 13:38:33

您可以使用.ondismiss()使用类似的方法。
然后,使用ImageConverter将您的ImageSlected转换为base64字符串。

profileView中,

 .sheet(isPresented: $openCameraRoll, onDismiss: didDismiss) {
    ImagePicker(selectedImage: $imageSelected, sourceType: .camera)
 }
 
 func didDismiss() {
     let b64Str = imageManager.imageToBase64(imageSelected)
     print("\n---> b64Str: \(b64Str?.count) \n")
 }

还删除ZSTACK,或通过vstack

edit-1替换它:在这里,一些对我有用的示例代码:

struct ProfileView: View {
    let imageManager = ImageConverter()
    
    @State var changeProfileImage = false
    @State var openCameraRoll = false
    @State var imageSelected = UIImage()
    
    var body: some View {
        VStack {
            Button(action: {
                openCameraRoll = true
            }, label: {
                Image(systemName: "plus")
                //  .profileImageMod()
            })
            if changeProfileImage {
                Image(uiImage: imageSelected)
                    .resizable() // <-- here
                    .frame(width: 222, height: 222)
                    .foregroundColor(.white)
                    .background(Color.gray)
                    .clipShape(Circle())
            } else {
                Image(systemName: "questionmark")
                    .frame(width: 222, height: 222)
                    .foregroundColor(.white)
                    .background(Color.gray)
                    .clipShape(Circle())
            }
        }
        .sheet(isPresented: $openCameraRoll, onDismiss: didDismiss) {
            ImagePicker(selectedImage: $imageSelected, sourceType: .camera)
        }
    }
    
    func didDismiss() {
        changeProfileImage = true
        let b64Str = imageManager.imageToBase64(imageSelected)
        print("\n---> b64Str: \(b64Str?.count) \n")
    }
}

you could use something like this approach, using the .onDismiss()
to then convert your imageSelected to base64 string using your ImageConverter.

In ProfileView,

 .sheet(isPresented: $openCameraRoll, onDismiss: didDismiss) {
    ImagePicker(selectedImage: $imageSelected, sourceType: .camera)
 }
 
 func didDismiss() {
     let b64Str = imageManager.imageToBase64(imageSelected)
     print("\n---> b64Str: \(b64Str?.count) \n")
 }

Also remove the ZStack, or replace it by a VStack

EDIT-1: here some example code that works for me:

struct ProfileView: View {
    let imageManager = ImageConverter()
    
    @State var changeProfileImage = false
    @State var openCameraRoll = false
    @State var imageSelected = UIImage()
    
    var body: some View {
        VStack {
            Button(action: {
                openCameraRoll = true
            }, label: {
                Image(systemName: "plus")
                //  .profileImageMod()
            })
            if changeProfileImage {
                Image(uiImage: imageSelected)
                    .resizable() // <-- here
                    .frame(width: 222, height: 222)
                    .foregroundColor(.white)
                    .background(Color.gray)
                    .clipShape(Circle())
            } else {
                Image(systemName: "questionmark")
                    .frame(width: 222, height: 222)
                    .foregroundColor(.white)
                    .background(Color.gray)
                    .clipShape(Circle())
            }
        }
        .sheet(isPresented: $openCameraRoll, onDismiss: didDismiss) {
            ImagePicker(selectedImage: $imageSelected, sourceType: .camera)
        }
    }
    
    func didDismiss() {
        changeProfileImage = true
        let b64Str = imageManager.imageToBase64(imageSelected)
        print("\n---> b64Str: \(b64Str?.count) \n")
    }
}

从相机或库中拍摄照片后,如何将图像转换为base64

夏末的微笑 2025-02-17 13:37:36

正如@iain Shelvington指出的那样,问题从用用户名设置为uppercase - &gt; 用户名= request.post.get('username')。upper()

user = User.objects.create_user(username=request.POST.get('username').upper(), email=request.POST.get('email').lower(), password=request.POST.get('password'), first_name=request.POST.get('firstname'), last_name=request.POST.get('lastname'))

然后,您将用户名传递给authenticate()没有upper()

user = authenticate(username=request.POST.get('username'), password=request.POST.get('password'))

因此,您可以在创建用户时从用户名中删除upper(),或在authenticate() upper() >。

不过,在附带说明,我看到您有两种称为login()的方法。 django login()和定义的方法login()。这也可能给您带来一些问题。我建议您将定义的login()重命名为:login_view(),因此不会遮盖django login()。例如:

# your defined method here; rename to login_view:
def login_view(request):
     ...
     # so it won't shadow the login method from Django
     login(request, users)
     ...

否则您会收到一个错误:

异常类型:typeerror at/login/except值:login()采用1个位置参数,但给出了2个

您可以看一下此 是否需要更好地了解。

As pointed out by @Iain Shelvington, the issue starts from where a user is being created with the username set to uppercase -> username=request.POST.get('username').upper().

user = User.objects.create_user(username=request.POST.get('username').upper(), email=request.POST.get('email').lower(), password=request.POST.get('password'), first_name=request.POST.get('firstname'), last_name=request.POST.get('lastname'))

Then the way you're passing the username to the authenticate() is without the upper().

user = authenticate(username=request.POST.get('username'), password=request.POST.get('password'))

So you could remove the upper() from the username when creating a user, or add the upper() to the username in the authenticate().

On a side note though, I see where you have two methods called login(). The Django login() and a defined method login(). This might cause a bit of an issue for you as well. I'd suggest that you rename your defined login() to something like: login_view() so it doesn't shadow the Django login(). For example:

# your defined method here; rename to login_view:
def login_view(request):
     ...
     # so it won't shadow the login method from Django
     login(request, users)
     ...

Else you'll get an error like:

Exception Type: TypeError at /login/ Exception Value: login() takes 1 positional argument but 2 were given

You could take a look at this answer to get a better understanding if needs be.

Django身份验证函数即使在“设置”中进行必要的更改。

夏末的微笑 2025-02-17 02:59:23

我发现了。工作查询是,

INSERT INTO community_members (community_id, member_id)
SELECT communities.id, user_follows.follower_id
FROM communities JOIN user_follows
ON communities.owner_id = user_follows.following_id

能够自动为每个社区所有者的用户做到这一点,而不必为每个用户运行查询是很酷的。目前还可以,因为我需要运行的15位用户进行

编辑:已更新以为所有社区所有者运行

I figured it out. The working query is

INSERT INTO community_members (community_id, member_id)
SELECT communities.id, user_follows.follower_id
FROM communities JOIN user_follows
ON communities.owner_id = user_follows.following_id

It would be cool to be able to do this for every user that is a community owner automatically, instead of having to run the query for each one. This is ok for now as there are <15 users I need to run this for

edit: Have updated to run for all community owners

将旧SQL表的数据插入新表中

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文