在此Web应用程序中,我有一个问题模型和一个问题图模型。每当用户上传图像时,都应该将其保存在media / question_image文件夹中。 如果我是从管理面板上传的,就可以正常工作,但是当我从网页上传图片时,它并没有被保存。事实是,发帖请求正常,我没有收到任何错误。图像未保存在所需位置。 这是我所有的代码: model.py
class QuestionDiagram(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='questionDiagrams')
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
question_diagram = models.ImageField(upload_to='question_diagram/')
question_diagram_text = models.CharField(max_length = 48)
date = models.DateTimeField(auto_now_add=True, blank=True, null=True)
forms.py
class QuestionDiagramForm(forms.ModelForm):
question_diagram = forms.CharField(widget = forms.FileInput(attrs={'class':'questionDiagram-questionDiagram'}))
question_diagram_text = forms.CharField(widget = forms.Textarea(attrs={'class':'questionDiagram-questionDiagramText', 'placeholder':'Describe', 'maxlength':'48'}))
class Meta:
model = QuestionDiagram
fields = ['question_diagram', 'question_diagram_text']
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
在项目urls.py中(添加了mediaroot和mediaurl) ......
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
class QuestionDiagramView(View):
form_class = QuestionDiagramForm
template_name = 'mechinpy/question_diagram.html'
def get(self, request, slug):
form = self.form_class(None)
return render(request, self.template_name, {'form':form})
def post(self, request, slug):
question = get_object_or_404(Question, slug=slug)
form = self.form_class(request.POST, request.FILES)
if form.is_valid():
questiondiagram = form.save(commit=False)
questiondiagram.user = self.request.user
questiondiagram.question = question
questiondiagram.save()
return redirect('mechinpy:detail', question.slug)
else:
return render(request, self.template_name, {'form':form})
html
<form class="form-block" method="POST" action="" enctype="multipart/form-data">
{% csrf_token %}
<!-- Question Diagram Error -->
<span class="show-error">{{form.non_field_errors}}</span>
{% for fields in form %}
<span class="show-error"> {{fields.errors}} </span>
<!-- Question Diagram Fields -->
<div class="show-field"> {{fields}} </div>
{% endfor %}
<!-- Question Diagram Submit Button -->
<div class="submit-content">
<button class="submit-button" type="submit"> Submit </button>
</div>
urls.py
path('m/question/<slug:slug>/diagram/add/', views.QuestionDiagramView.as_view(), name='question_diagram'),
答案 0 :(得分:2)
这里:
class QuestionDiagramForm(forms.ModelForm):
question_diagram = forms.CharField(...)
您需要ImageField
,而不是CharField
。 FWIW,您应该只保留默认字段you don't need to override them just to add css classes。