我是Django的新手。我知道这个问题已经被问过几次了,但是所提供的解决方案都不适合我。我正在创建自定义用户注册表格。表单正确呈现,但是提交后未将数据发布到数据库。它只是刷新并清除输入的数据。在过去的几个小时中,我一直在努力工作,但是我无法指出这段代码中的问题所在。真诚的感谢您的协助。谢谢
我的看法如下
```from django.shortcuts import render, redirect
from users.forms import RegistrationForm
from django.contrib import messages
def register(request):
"""Registration view"""
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
username = form.cleaned_data('username')
messages.success(request, f'Account created for{username}!')
form.save()
return redirect('bookings-home')
else:
print (form.errors)
else:
form = RegistrationForm()
return render(request, 'users/register.html', {'form': form})
```
**My Form is as follows**
```from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class RegistrationForm(UserCreationForm):
"""Handles users registration"""
email = forms.EmailField(required=True)
class Meta:
"""Defines fields needed"""
model = User
fields = (
'username',
'first_name',
'last_name',
'email',
'password1',
'password2'
)
def save(self, commit=True):
"""Save data to the database if safe"""
user = super(RegistrationForm, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
```
**My template code is as follows**
```<form method="POST" action = '.'>
{% csrf_token %}
<div class="form-inner">
<div class="login-with-socials">
<button class="btn btn-facebook btn-block">Register with Facebook</button>
<!-- <button class="btn btn-google btn-block">Register with Google</button> -->
<button class="btn btn-twitter btn-block">Register with Twitter</button>
<!-- <button class="btn btn-pinterest btn-block">Register with Pinterest</button> -->
</div>
<div class="text-seperator">
<span>or</span>
</div>
{% for field in form %}
<div class="form-group">
<input id="login_username" class="form-control" placeholder="{{field.label}}" type="{{ field.field.widget.input_type }}">
</div> {% endfor %}```
**And finally my url is as follows**
```from django.contrib import admin
from django.urls import path, include
from users import views as user_views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', user_views.register, name='register'),
path('', include('hotels.urls')),
]```
答案 0 :(得分:0)
通过实现crisp_forms,我部分能够获得上述问题的解决方案。在第一个实例中,我尝试将CSS与Django字段一起使用。我仍然很想知道为什么上述方法不起作用