我在使用Django上传图片时遇到了一些麻烦。
settings.py :
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/uploads/'
models.py :
class Dater(AbstractUser):
AbstractUser.username = models.CharField(max_length=30)
AbstractUser.password = models.CharField(max_length=30)
picture = models.ImageField(upload_to="users_picture", blank=True, null=True)
summary = models.TextField()
....
forms.py :
class UserForm(forms.ModelForm):
username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Enter your username'}))
password = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','type': 'password','placeholder': 'Enter your password'}))
summary = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control col-xs-2'}))
...
class Meta:
model = models.Dater
fields = ['username', 'password', 'summary',
'picture']
我的HTML :
<form id="signupForm" method="post" action="" enctype='multipart/form-data'>
{% csrf_token %}
{% include 'website/form-template.html' %}
<button type="submit" class="btn btn-danger">Submit</button>
</form>
views.py :
class UserFormView(View):
form_class = UserForm
template_name = 'website/signup.html'
# Display the form
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
# Process the form
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
# Cleaning and normalizing data
password = form.cleaned_data['password']
user.set_password(password)
user.latitude = 24.8047 # api call later
user.longitude = 120.9714 # api call later
user.save()
我创建了一个文件夹:“uploads”与文件manage.py
处于同一级别。在这个文件夹里面我还创建了另一个文件夹:“users_picture”我希望我的图片可以上传到,但是当我添加用户时,图像根本就没有上传。