当我注册新用户时,网站会自动创建一个配置文件,并使用default.jpg图片。突然它停止工作了。该错误表明我的“图片”字段存在问题。这是我得到的错误:
IntegrityError at /accounts/register/
null value in column "image" violates not-null constraint
DETAIL: Failing row contains (20, pbkdf2_sha256$150000$72dkND5yT5M0$+/chH/5Vu76KM7oNMjU694EWFZ/p+B..., null, f, kazanda, f, 2019-04-21 17:41:29.969889+00, Andreas, Swarchft, Germany, Frankfurt, andreas_sw@gmail.com, t, null).
这是我的模特。py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics', null=True)
def __str__(self):
return self.user.username
def save(self, force_insert=False, force_update=False, using=None):
super().save()
img = Image.open(self.image.path)
if img.height > 250 or img.width > 250:
output_size = (250, 250)
img.thumbnail(output_size)
img.save(self.image.path)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = Profile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
我的views.py
class UserRegistrationView(SuccessMessageMixin, CreateView):
form_class = UserCreationModelForm
model = User
success_url = reverse_lazy('login')
success_message = "Account for %(first_name)s was created successfully. You will get email notification when admin will activate your account!"
template_name = 'users/registration.html'
def get_success_message(self, cleaned_data):
return self.success_message % dict(cleaned_data)
@login_required
def profile(request):
if request.method == 'POST':
uform = UserUpdateForm(request.POST, instance=request.user)
pform = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
posts = Post.objects.filter(author=request.user)
if uform.is_valid() and pform.is_valid():
uform.save()
pform.save()
messages.success(request, 'Your account has been updated!')
return redirect('users:cabinet')
else:
uform = UserUpdateForm(instance=request.user)
pform = ProfileUpdateForm(instance=request.user.profile)
posts = Post.objects.filter(author=request.user)
context = {
'uform': uform,
'pform': pform,
'posts': posts
}
return render(request, 'users/user_detail.html', context)
@login_required
def cabinet(request):
profile = Profile.objects.all()
context = {
'profile': profile
}
return render(request, 'users/user_detail.html', context)
我的registration.html
这是用于创建用户的表单:
{% extends 'shared/base.html' %}
{% load staticfiles %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section mt-5 pl-5 p-4">
<form method="post">
{% csrf_token %}
<fieldset class="form-group pr-4">
<legend class="mb-4">Join Today</legend>
<div class="form-row">
<div class="form-group col-md-3 mb-0">
{{ form.first_name|as_crispy_field }}
</div>
<div class="form-group col-md-3 mb-0">
{{ form.last_name|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6 mb-0">
{{ form.username|as_crispy_field }}
<div class="form-row">
<div class="form-group col-md-6 mb-0">
{{ form.country|as_crispy_field }}
</div>
<div class="form-group col-md-6 mb-0">
{{ form.city|as_crispy_field }}
</div>
<div class="form-row">
<div class="form-group col-md-12 mb-0">
{{ form.email|as_crispy_field }}
</div>
<div class="form-row">
<div class="form-group col-md-6 mb-0">
{{ form.password1|as_crispy_field }}
</div>
<div class="form-group col-md-6 mb-0">
{{ form.password2|as_crispy_field }}
</div>
<!-- <div class="form-check">
{{ form.access_challenge }}
<label class="form-check-label" for="Checkbox"> Access Challenge Country</label>
</div> -->
</fieldset>
<div class="form-group">
<button style="border-radius: 0; width: 200px; padding-left: 4px;" class="btn btn-info btn-block" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a>
</small>
</div>
</div>
{% endblock %}
这是我的post_form.html
{% extends 'shared/base.html' %}
{% load staticfiles %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section mt-5 pl-5 p-4">
<form method="post" id="personForm" data-cities-url="{% url 'users:ajax_load_cities' %}" novalidate>
{% csrf_token %}
<fieldset class="form-group">
<legend class="mb-4">Church Info</legend>
<div class="form-row">
<div class="form-group col-md-3 small">
{{ form.area|as_crispy_field }}
</div>
<div class="form-group col-md-3 small">
{{ form.country|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3 small">
{{ form.name|as_crispy_field }}
</div>
<div class="form-group col-md-3 small">
{{ form.city|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3 small">
{{ form.email|as_crispy_field }}
</div>
<div class="form-group col-md-3 small">
{{ form.website|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3 small">
{{ form.address|as_crispy_field }}
</div>
<div class="form-group col-md-3 small">
{{ form.phone|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3 small">
{{ date_posted }}
</div>
<div class="form-group col-md-3 small">
{{ author }}
</div>
</div>
<div class="form-group">
<button style="border-radius: 0; width: 200px; padding-left: 4px;" class="btn btn-info btn-block" type="submit">Submit</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a>
</small>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$("#id_area").change(function () {
var url = $("#personForm").attr("data-cities-url");
var areaId = $(this).val();
$.ajax({
url: url,
data: {
'area': areaId
},
success: function (data) {
$("#id_country").html(data);
}
});
});
</script>
{% endblock %}
这是我的forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth import get_user_model
from .models import Profile, Post, User, Country
class UserCreationModelForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'country', 'city', 'email', 'password1', 'password2']
class UserUpdateForm(forms.ModelForm):
username = forms.CharField()
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'country', 'city', 'email']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('name', 'area', 'country', 'city', 'address', 'email', 'phone', 'website')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['country'].queryset = Country.objects.none()
if 'area' in self.data:
try:
area_id = int(self.data.get('area'))
self.fields['country'].queryset = Country.objects.filter(area_id=area_id).order_by('name')
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['country'].queryset = self.instance.area.country_set.order_by('name')