在Django中使用表单上传图片

huangapple go评论67阅读模式
英文:

Uploading images using forms in Django

问题

I need help. Learning Django at the moment. Doing a simple (for now) project which is basically a site about film photocameras: it contains information, relations between cameras and films... You get the idea.

我需要帮助。目前正在学习Django。正在做一个简单(目前为止)的项目,基本上是一个关于胶片相机的网站:它包含信息,相机和胶卷之间的关系... 你明白了。

I have created two forms to create a new entry for camera and for film. Here is the models to start with:

我已经创建了两个表单,用于创建相机和胶卷的新条目。以下是开始使用的模型:

And here is the forms to full this models using browser:

这是用浏览器填充这些模型的表单:

Views for processing the data (for camera entry):

用于处理数据的视图(用于相机条目):

So, the problem is that when I use this forms via browser and append my image to the form and then press save, it doesn't save anything. But appending an image using Admin Panel works fine. Here is my template for adding the camera entry:

所以,问题是当我通过浏览器使用这些表单并将我的图像附加到表单,然后按保存时,它不保存任何内容。但是在管理面板中附加图像可以正常工作。这是我用于添加相机条目的模板:

And here is how it looks in browser:

这是在浏览器中的样子:

When I press add: it creates new entry, but without an image attached.

当我按“添加”时:它创建了新的条目,但没有附加图像。

I know, that I can upload images using separate form and writing a separate view for this, but I would like to see it works in one form. Is it possible?

我知道,我可以使用单独的表单上传图像并为此编写单独的视图,但我想看到它是否可以在一个表单中工作。这是可能的吗?

英文:

I need help. Learning Django at the moment. Doing a simple (for now) project which is basically a site about film photocameras: it contains information, relations between cameras and films... You get the idea.

I have created two forms to create a new entry for camera and for film. Here is the models to start with:


class Camera(models.Model):
	ref_to_topic=models.ForeignKey(Topic, on_delete=models.CASCADE)
	ref_to_brand=models.ForeignKey(Brand, on_delete=models.CASCADE)
	camera_name=models.CharField(max_length=255)
	camera_info=models.TextField(null=True, blank=True)
	camera_image=models.ImageField(upload_to='site_media/camera_images/', null=True, blank=True)
	when_appeared_date=models.DateField(null=True, blank=True)
	when_appeared_year=models.IntegerField(null=True, blank=True)
	when_disappeared=models.DateField(null=True, blank=True)
	when_disappeared_year=models.IntegerField(null=True, blank=True)
	when_added=models.DateTimeField(auto_now_add=True)
	when_updated=models.DateTimeField(auto_now=True)
	owner = models.ForeignKey(User, on_delete=models.CASCADE, default=1)

	class Meta():
		verbose_name_plural='cameras'

	def __str__(self):
		return f"{self.camera_name} - {self.camera_info[:25]}"


class Film(models.Model):
	ref_to_topic=models.ForeignKey(Topic, on_delete=models.CASCADE)
	ref_to_brand=models.ForeignKey(Brand, on_delete=models.CASCADE)
	film_name=models.CharField(max_length=255)
	film_info=models.TextField(null=True, blank=True)
	film_image=models.ImageField(upload_to='site_media/film_images/', null=True, blank=True)
	when_added=models.DateTimeField(auto_now_add=True)
	when_updated=models.DateTimeField(auto_now=True)
	owner = models.ForeignKey(User, on_delete=models.CASCADE, default=1)

	class Meta():
		verbose_name_plural='films'

	def __str__(self):
		return f"{self.film_name} - {self.film_info[:25]}"

And here is the forms to full this models using browser:


class CameraForm(forms.ModelForm):
	class Meta:
		model = Camera
		fields = ['camera_name', 'camera_info', 'when_appeared_date', 'when_appeared_year', 'when_disappeared', 'when_disappeared_year', 'ref_to_topic', 'ref_to_brand', 'owner', 'camera_image']
		labels = {
			'camera_name': 'Camera',
			'camera_info': 'Info',
			'when_appeared_date': 'Started on the market (exact date, can be null)',
			'when_appeared_year': 'Strarted on the market (exact year, can be null)',
			'when_disappeared': 'When the sales stopped (exact date, can be null)',
			'when_disappeared_year': 'When the sales stopped (exact year, can be null)',
			'ref_to_topic': 'refered to topic',
			'ref_to_brand': 'refered to brand',
			'owner': 'Owner',
			'camera_image': 'Image'
		}
		widgets = {
			'camera_info': forms.Textarea(attrs={'cols': 80})
		}

class FilmForm(forms.ModelForm):
	class Meta:
		model = Film
		fields = ['film_name', 'film_info', 'ref_to_topic', 'ref_to_brand', 'owner', 'film_image']
		labels = {
			'film_name': 'Film',
			'film_info': 'Info',
			'ref_to_topic': 'refered to topic',
			'ref_to_brand': 'refered to brand',
			'owner': 'Owner',
			'film_image': 'Image'
		}
		widgets = {
			'film_info': forms.Textarea(attrs={'cols': 80})
		}

Views for processing the data (for camera entry):

@login_required
def add_new_camera(request):
	if request.method != 'POST':
		form = CameraForm()
	else:
		form = CameraForm(data=request.POST)
		if form.is_valid():
			form.save()
			return redirect ('content_app:cameras')

	context = {
		'form': form,
	}
	return render (request, 'content_app/add_new_camera.html', context)

So, the problem is that when I use this forms via browser and append my image to the form and then press save, it doesn't save anything. But appending an image using Admin Panel works fine. Here is my template for adding the camera entry:


<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>add new camera</title>
</head>
<body>
{% extends 'content_app/base.html' %}

{% block content %}
<p>New camera:</p>
<form action="{% url 'content_app:add_new_camera' %}" method="post" enctype="multipart/form-data">
	{% csrf_token %}
	{{form.as_p}}
	<button name="submit">add</button>
</form>
{% endblock content %}	
</body>
</html>

And here is how it looks in browser:

在Django中使用表单上传图片

When I press add: it creates new entry, but without an image attached.

I know, that I can upload images using seperate form and writing a seperate view for this, but I would like to see it works in one form. Is it possible?

答案1

得分: 1

你需要同时将 request.FILES 传递给表单。

尝试

CameraForm(request.POST, request.FILES)

文档 中有更多详细信息。

英文:

You need to pass the request.FILES to the form as well.

Try

CameraForm(request.POST, request.FILES)

More details in the docs.

huangapple
  • 本文由 发表于 2023年7月23日 17:19:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76747477.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定