简体   繁体   English

我正在尝试在我的 Django 项目上实现图像上传功能,但没有创建文件。 我的代码有什么问题?

[英]I am trying to implement an image upload feature on my Django project but no file is being created. What is wrong with my code?

I have a profile page with a default profile picture and a 'Change' button beside it which will trigger a modal upon being clicked.我有一个带有默认个人资料图片的个人资料页面,旁边有一个“更改”按钮,单击该按钮将触发模式。 In this modal, the image upload button (for choosing the image) will appear along with a submit button.在此模式中,图像上传按钮(用于选择图像)将与提交按钮一起出现。 I have created a separate view for handling the image upload.我创建了一个单独的视图来处理图像上传。 I do not know why a file is not being created after upload.我不知道为什么上传后没有创建文件。 No error message is being given by Django. Django 没有给出错误消息。 I suspect it has something to do with settings.py configuration or the action part of my modal field.我怀疑它与 settings.py 配置或我的模态字段的操作部分有关。

views.py视图.py


from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect

from .forms import KeyForm, Weekly_Item_Form, Daily_Item_Form, ProfileForm
from .models import Key, Weekly_Item, Daily_Item, Profile


def profile_view(request):
    profiles = Profile.objects.all()
    mainprofile = profiles.last()
    if profiles:
        form = ProfileForm()
        context = {
            'page_title':"Profile", 
            'mainprofile':mainprofile,
            'form': form
        }
    else:
        context = {'page_title':"Profile"}
    return render(request, "bujo/profile.html", context)


def update_image(request, pk):
    mainprofile = Profile.objects.get(id=pk)
    form = ProfileForm(instance=mainprofile)
    
    if request.method == 'POST':
        form = ProfileForm(request.POST, request.FILES, instance=mainprofile)
        if form.is_valid():
            form.save()
            return redirect('profile')
    return redirect('profile')

urls.py网址.py


urlpatterns = [
    path('admin/', admin.site.urls),
    path('profile/', app_views.profile_view, name='profile'),
    path('update_image/<str:pk>', app_views.update_image, name='update_image'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py设置.py

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

profile.html配置文件.html

<form method='POST' enctype="multipart/form-data" action="{% url 'update_image' mainprofile.pk %}"> {% csrf_token %}
                 {{ form.image }}
             <input type='submit' class="btn btn-primary"" value='Change profile picture' />
             </form>

forms.py forms.py

from django import forms
from .models import Profile

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['name', 'image', 'nickname', 'bio']

models.py模型.py

class Profile(models.Model):
    name = models.CharField(max_length=50, blank=False)
    image = models.ImageField(null=True, blank=True, upload_to="images/")
    nickname = models.CharField(max_length=20, null=False, blank=True)
    bio = models.CharField(max_length=100, null=False, blank=True)

Your form has fields other than image also.您的表单也有图像以外的字段。 You don't render them in the template but the form class expects them, so when the form is submitted it is considered to be not valid.您不在模板中呈现它们,但表单 class 需要它们,因此当提交表单时,它被认为是无效的。 If you want to update only the image create another form class which has only the image field.如果您只想更新图像,请创建另一个只有图像字段的表格 class。

In your forms.py add another form class:在您的forms.py添加另一个表格 class:

from django import forms
from .models import Profile

class ProfileImageForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['image']

In your views:在您看来:

from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect

from .forms import KeyForm, Weekly_Item_Form, Daily_Item_Form, ProfileForm, ProfileImageForm
from .models import Key, Weekly_Item, Daily_Item, Profile


def profile_view(request):
    profiles = Profile.objects.all()
    mainprofile = profiles.last() # This line feels weird! You always make the form for the last profile only.
    if profiles:
        form = ProfileImageForm()
        context = {
            'page_title':"Profile", 
            'mainprofile':mainprofile,
            'form': form
        }
    else:
        context = {'page_title':"Profile"}
    return render(request, "bujo/profile.html", context)


def update_image(request, pk):
    mainprofile = Profile.objects.get(id=pk)
    form = ProfileImageForm(instance=mainprofile)
    
    if request.method == 'POST':
        form = ProfileImageForm(request.POST, request.FILES, instance=mainprofile)
        if form.is_valid():
            form.save()
            return redirect('profile')
    return redirect('profile')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在尝试在 django 中注册用户,但表单字段没有显示。 我的代码有什么问题? - I am trying to register users in django but the form fields are not showing up. What is wrong with my code? 我在Django中的CSV上传代码有什么问题? - What is wrong with my CSV upload code in Django? 我的绳子有什么问题(将文件上传到 django) - what is wrong with my cord(upload file to django) 我的 Django 网站正在加载我的 static (CSS) 文件,但它们没有显示。 我错过了什么或做错了什么? - My static (CSS) files are loading for my Django website, but they are not being displayed. What am I missing or doing wrong? Django:我的代码有什么问题? - Django:What is wrong with my code? 在这个django视图中,我的函数在做什么错? - What am I doing wrong with my function within this django view? 我的django应用程序的settings.py文件中的此代码有什么问题? - what is wrong with this code in settings.py file of my django application? 是什么导致Django文件上传代码中的内存激增? - What is causing the memory spike in my Django file upload code? 我正在尝试用Django实现博客应用程序。我创建了配置文件pic上传的注册表。但是它没有提交数据? - I am trying to implement blog app with Django.I created registration form with profile pic upload.But its not submitting data? 我正在尝试使用Django实现博客应用。我创建了带有个人资料照片上传的注册表单,但返回IntegrityError - I am trying to implement blog app with Django.I created registration form with profile pic upload.But its returning IntegrityError
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM