Home > Mobile >  Django Files doesn't save
Django Files doesn't save

Time:05-24

I want to do a django project where you upload an image and this image is displayed on another page. I can edit it only with admin panel.

Here is the code:

Views.py

def home(request):
    all1 = New.objects.filter(username='mynameis12').all()
    if not request.user.is_authenticated:
        return redirect('/login/')
    return render(request, 'home.html',{'alls':all1})

Models.py

class New(models.Model):
    username = models.CharField(max_length=200)
    image = models.ImageField(upload_to='media')

Forms.py


class New1(ModelForm):
    username = forms.CharField(max_length=200)
    image = forms.ImageField(required=False)
    class Meta:
        model = New
        fields = ['username','image']

Settings.py

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
LOGIN_URL = '/b/'
LOGIN_REDIRECT_URL = '/b/'
LOGOUT_REDIRECT_URL = '/'

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

The image is showed but it doesn't be saved.

What should I do?

Thanks.

CodePudding user response:

You need to import your form in views and you need to save the form inside your view:

from forms import New1

def home(request):
    if not request.user.is_authenticated:
        return redirect('/login/')
    all1 = New.objects.filter(username='mynameis12').all()
    form = New1()
    if request.method == "POST":
        form = New1(request.POST)
        form.save()
    return render(request, 'home.html',{'alls':all1,'form':form})

in your HTML:

<form>
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>

follow this link for tutorial: https://tutorial.djangogirls.org/en/django_forms/

CodePudding user response:

If you want to upload the pictures in the home page you have to pass a form into it

views.py

from django.contrib.auth.decorators import login_required

# if you just want to display the images in the home page
from .models import New
@login_required(login_url="login") # this does the same thing as the if statement but better
def home(request):
    all1 = New.objects.filter(username='mynameis12')# no need for the '.all()'
    return render(request, "home.html", {"all1": all1 })

if you are only editing the admin panel then there is no need to use the form, but if you still want to here it is.

views.py

from django.contrib.auth.decorators import login_required
from .forms import NewForm
@login_required(login_url="login") # this does the same thing as the if statement but better
def home(request):
    form = NewForm()
    if request.method == "POST":
        form = NewForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            ...
    return render(request, "home.html", {"form": form})

forms.py

class NewForm(ModelForm):
    class Meta:
        model = New
        fields = ['username','image']

    def __init__(self, *args, **kwargs):
        super(NewForm, self).__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs.update({'class': "input"})

there is no need to redefine the fields here if you are not changing anything from the models.py definition of the model.

  • Related