尽管经过了数小时的努力,但我无法引导使用UserCreationForm创建的Django表单。我想将Bootstrap类添加到标签中,但是由于我对基于django类的视图的了解不足,因此无法解决。
urls.py
urlpatterns = [
path('signup/', views.SignUp.as_view(), name='signup'),
path('', include('django.contrib.auth.urls')),
]
views.py
class SignUp(CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('accounts:login')
template_name = 'accounts/signup.html'
forms.py
class CustomUserCreationForm(UserCreationForm):
class Meta:
fields = ('first_name', 'last_name', 'email', 'age', 'height', 'avatar', 'password1', 'password2')
model = get_user_model()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['password2'].label = "Confirm Password"
电流输出 enter image description here
我想要的输出 enter image description here
答案 0 :(得分:0)
或 https://django-bootstrap3.readthedocs.io/en/latest/templatetags.html
以及在模板中渲染字段时,例如 {%bootstrap_field form.myfield form_group_class ='custom-class-name'%}
您可以像这样添加自定义类。它会在您检查时作为HTML中的类显示,以便可以将其用于CSS
答案 1 :(得分:0)
因此,我要发布我自己问题的答案,以便寻找相同内容的人可以在一个地方找到解决方案。我到底在找什么;
forms.py
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <thrust/remove.h>
#include <thrust/merge.h>
#include <cstdlib>
#include <cstdio>
#include <thrust\partition.h>
#include <thrust\execution_policy.h>
#include <time.h>
#include <cmath>
#include <iostream>
using namespace std;
#define BLOCKS 2LL//32768LL*32LL
#define THREADS 16LL
#define ELEMS BLOCKS*THREADS*2
class ComplexNumber
{
public:
double Real;
double Imaginary;
__host__ __device__ ComplexNumber() {
this->Real = 0;
this->Imaginary = 0;
}
__host__ __device__ ComplexNumber(double real) {
this->Real = real;
this->Imaginary = 0;
}
__host__ __device__ ComplexNumber(double real, double imaginary) {
this->Real = real;
this->Imaginary = imaginary;
}
__host__ __device__ ComplexNumber operator *(ComplexNumber &a) {
ComplexNumber result = ComplexNumber((this->Real*a.Real - this->Imaginary*a.Imaginary), (this->Real*a.Imaginary + this->Imaginary*a.Real));
return (result);
}
__host__ __device__ ComplexNumber operator -(ComplexNumber &a) {
ComplexNumber result = ComplexNumber((this->Real - a.Real), (this->Imaginary - a.Imaginary));
return (result);
}
__host__ __device__ ComplexNumber operator +(ComplexNumber &a){
ComplexNumber result = ComplexNumber((this->Real + a.Real), (a.Imaginary + this->Imaginary));
return (result);
}
__host__ __device__ ComplexNumber operator /(ComplexNumber &a) {
ComplexNumber result = ComplexNumber(((this->Real*a.Real + this->Imaginary*a.Imaginary) / (pow(this->Real, 2) + (pow(this->Imaginary, 2)))), ((this->Real*a.Imaginary - this->Imaginary*a.Real) / (pow(this->Real, 2) + pow(this->Imaginary, 2))));
return (result);
}
//void operator =(ComplexNumber &a);
__host__ friend std::ostream& operator<<(std::ostream& os, ComplexNumber &a) {
return os << "(" << a.Real << ", " << a.Imaginary << ")";
}
/*__host__ __device__ bool operator ==(ComplexNumber &a) {
return ((this->Real == a.Real) && (this->Imaginary == a.Imaginary));
}*/
/*void operator +=(ComplexNumber &a);
void operator -=(ComplexNumber &a);*/
__host__ __device__ ~ComplexNumber() {};
__host__ __device__ double Radius()
{
return sqrt(pow(this->Real, 2) + pow(this->Imaginary, 2));
}
};
cudaError_t LaunchFFT(ComplexNumber *a, unsigned int size);
int random(int min, int max) //range : [min, max)
{
static bool first = true;
if (first)
{
srand(time(NULL)); //seeding for the first time only
first = false;
}
return min + rand() % ((max + 1) - min);
}
__global__ void FFTKernel(ComplexNumber *a, unsigned int size)
{
std::size_t i = 2*(blockIdx.x * blockDim.x + threadIdx.x);
ComplexNumber temp = a[i] + a[i + 1];
a[i + 1] = a[i] - a[i + 1];
a[i] = temp;
}
__global__ void FFTMultiply(ComplexNumber *a, int k, unsigned int size)
{
std::size_t i= blockIdx.x * blockDim.x + threadIdx.x;
std::size_t n = (i / 2)&(~(1 << (k - 1)));
ComplexNumber Wnn = ComplexNumber(cos(2 * 3.14152*n / size), -sin(2 * 3.14152*n / size));
a[i] = a[i] * Wnn;
}
__global__ void FFTSwap(ComplexNumber *a, unsigned int size)
{
std::size_t i = blockIdx.x * blockDim.x + threadIdx.x;
std::size_t ixj = i + size / 2;
ComplexNumber temp = a[i];
a[i] = a[ixj];
a[ixj] = temp;
}
void FFT( ComplexNumber *a, unsigned int size)
{
dim3 blockdim(BLOCKS, 1);
dim3 threaddim(THREADS, 1);
int k;
FFTSwap<<<blockdim, threaddim >>>(a, size);
cudaThreadSynchronize();
for (k = 1; (1 << (k - 1)) < ELEMS; k <<= 1) { //split into k partitions
FFTKernel<<<blockdim, threaddim>>> (a, size);
FFTMultiply <<<blockdim, threaddim >> > (a, k, size);
FFTSwap <<<blockdim, threaddim >>> (a, size);
cudaThreadSynchronize();
}
FFTKernel <<<blockdim, threaddim >>> (a, size);
cudaThreadSynchronize();
}
int main()
{
//ComplexNumber *aa = new ComplexNumber[ELEMS];
ComplexNumber *a = new ComplexNumber[ELEMS];
for (std::size_t i = 0; i < ELEMS; i++) {
a[i] = ComplexNumber(random(0, 100), random(0, 100));
cout << a[i];
}
// Add vectors in parallel.
cudaError_t cudaStatus = LaunchFFT(a, ELEMS);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "addWithCuda failed!");
return 1;
}
// cudaDeviceReset must be called before exiting in order for profiling and
// tracing tools such as Nsight and Visual Profiler to show complete traces.
cudaStatus = cudaDeviceReset();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceReset failed!");
return 1;
}
delete[] a;
return 0;
}
// Helper function for using CUDA to add vectors in parallel.
cudaError_t LaunchFFT(ComplexNumber *a, unsigned int size)
{
ComplexNumber *dev_a = 0;
cudaError_t cudaStatus;
// Choose which GPU to run on, change this on a multi-GPU system.
cudaStatus = cudaSetDevice(0);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaSetDevice failed! Do you have a CUDA-capable GPU installed?");
goto Error;
}
// Allocate GPU buffers for three vectors (two input, one output) .
cudaStatus = cudaMalloc((void**)&dev_a, size * sizeof(ComplexNumber));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMalloc failed!");
goto Error;
}
// Copy input vectors from host memory to GPU buffers.
cudaStatus = cudaMemcpy(dev_a, a, size * sizeof(ComplexNumber), cudaMemcpyHostToDevice);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMemcpy failed!");
goto Error;
}
// Launch a kernel on the GPU with one thread for each element.
//clock_t start, stop = 0;
cudaEvent_t startCu, stopCu;
float elapsedTime;
cudaEventCreate(&startCu);
cudaEventCreate(&stopCu);
//start = clock();
cudaEventRecord(startCu, 0);
FFT(dev_a, size);
cudaStatus = cudaGetLastError();
cudaEventRecord(stopCu, 0);
cudaEventSynchronize(stopCu);
//stop = clock();
cudaEventElapsedTime(&elapsedTime, startCu, stopCu);
printf("Elapsed time : %f ms\n", elapsedTime);
//print_elapsed(start, stop);
// Check for any errors launching the kernel
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "addKernel launch failed: %s\n", cudaGetErrorString(cudaStatus));
goto Error;
}
// cudaDeviceSynchronize waits for the kernel to finish, and returns
// any errors encountered during the launch.
cudaStatus = cudaDeviceSynchronize();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching addKernel!\n", cudaStatus);
goto Error;
}
// Copy output vector from GPU buffer to host memory.
cudaStatus = cudaMemcpy(a, dev_a, size * sizeof(int), cudaMemcpyDeviceToHost);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMemcpy failed!");
goto Error;
}
Error:
cudaFree(dev_a);
return cudaStatus;
}
views.py
class CustomUserCreationForm(UserCreationForm):
class Meta:
fields = ('first_name', 'last_name', 'email', 'age', 'height', 'avatar', 'password1', 'password2')
model = get_user_model()
first_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'First Name',
'class': 'form-control',
}))
last_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Last Name',
'class': 'form-control',
}))
email = forms.CharField(widget=forms.EmailInput(attrs={'placeholder': 'Email',
'class': 'form-control mb-4',
}))
age = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder': 'Age',
'class': 'form-control',
}))
height = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder': 'Height(cm)',
'class': 'form-control',
}))
avatar = forms.ImageField(widget=forms.FileInput(attrs={'placeholder': 'Avatar',
'class': 'form-control mb-4',
}))
password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password',
'class': 'form-control mb-4',
}))
password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password',
'class': 'form-control mb-4',
}))
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['password2'].label = "Confirm Password"
accounts / register.html
class SignUp(CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('accounts:login')
template_name = 'accounts/register.html'
您可以像在CustomUserCreationForm类中一样对UserCreationFrom进行子类化,然后您所要做的就是将所需的属性(引导类名,ID等)添加到要修改(美化)的表单字段中。谈到在SignUp视图中编写的“ accounts / register.html”,我明确地告诉django在哪里可以找到模板。在模板中,您可以通过{% extends 'base.html' %}
{% block title %}
SignUp
{% endblock title %}
{% block content %}
<div style="margin: 75px 0px 0px 0px; background: rgb(87,77,255);
background: linear-gradient(276deg, rgba(87,77,255,0.8830882694874825) 24%, rgba(7,96,255,0.5385504543614321) 77%);" class="bg_cover">
<form class="text-center col-md-5" method="POST" enctype="multipart/form-data">
<p class="h4 mb-4">SignUp</p>
{% csrf_token %}
<div class="form-row mb-4">
<div class="col">
{{ form.first_name }}
</div>
<div class="col">
{{ form.last_name }}
</div>
</div>
{{ form.email }}
<div class="form-row mb-4">
<div class="col">
{{ form.age }}
</div>
<div class="col">
{{ form.height }}
</div>
</div>
{{ form.avatar }}
{{ form.password1 }}
{{ form.password2 }}
<button class="btn-block btn btn-primary my-4" type="submit">Sign up</button>
</form>
</div>
{% endblock content %}
渲染整个表单,也可以像在模板中那样渲染单个字段!
希望我的回答可以使您免于头痛不已!