我正在创建新的Contact实例,在contact = contact_form.save(commit=False)
cleaned_data['avatar']
后我看到了默认的头像路径,但在表单中我设置了另一张图片。为什么会这样?
联系模式:
class Contact(models.Model):
first_name = models.CharField(max_length=60)
last_name = models.CharField(max_length=60)
note = models.TextField(max_length=280, blank=True)
avatar = models.ImageField(upload_to=generate_upload_to_path, default='/contacts/default_icon.png', blank=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None)
联系ModelForm:
class ContactForm(forms.ModelForm):
prefix = 'contact'
class Meta:
model = Contact
exclude = ('user',)
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.fields['last_name'].widget.attrs['placeholder'] = 'Last name'
self.fields['first_name'].widget.attrs['placeholder'] = 'First name'
self.fields['avatar'].widget.attrs['placeholder'] = 'Avatar'
views.py
def index(request):
if request.user.is_authenticated:
if request.method == 'POST':
contact_form = ContactForm(request.POST)
phone_number_form = PhoneNumberForm(request.POST)
email_form = EmailForm(request.POST)
if contact_form.is_valid() and phone_number_form.is_valid() and email_form.is_valid():
contact = contact_form.save(commit=False)
contact.user = User.objects.get(pk=request.user.pk)
contact.save()
phone_number = phone_number_form.save(commit=False)
phone_number.contact = contact
phone_number.save()
email = email_form.save(commit=False)
email.contact = contact
email.save()
return redirect('contacts:index')