Home > Mobile >  Crispy form not rendering on ModelForm
Crispy form not rendering on ModelForm

Time:09-26

I am trying to render a ModelForm with crispy form but is not working,I have tried both tags: ( {{ form|crispy }} and {% crispy form %} ) Why doesn't work?

models.py

class ProfileInfo(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE, unique=True)
    cover_image = models.ImageField(null=True, blank=True,upload_to='cover/')
    profile_image = models.ImageField(null=True, blank=True,upload_to='avatar/')

    def __str__(self):
        return self.user.username.title()

forms.py

class UploadCoverForm(forms.ModelForm):

    class Meta:
        model = ProfileInfo
        fields = ['cover_image']

    def __init__(self, *args, **kwargs):
        super(UploadCoverForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)

views.py

@login_required
def upload_cover(request):
    user = ProfileInfo.objects.get(user = request.user)

    if request.method == "POST":
        form = UploadCoverForm(request.POST, request.FILES, instance=user)

        if form.is_valid():
            user = form.save(False)

            cover = form.cleaned_data.get("cover_image")
            if cover:
                image = Image.open(cover)
                image_data = BytesIO()
                image.save(fp=image_data, format=image.format)
                image_file = ImageFile(image_data)
                user.cover_image.save('{}.cover.{}'.format(user,image.format), image_file)
            user.save()
            return redirect("user:Profile", request.user.username)
    else:
        form = UploadCoverForm(instance=user)

    return render(request, "uploads/upload_cover.html",{"form": form})

I have included the link for bootstrap in "base_uploads.html"

upload_cover.html

{% extends "uploads/base_uploads.html" %}
{% load crispy_forms_tags %}

{% block title %} Upload Cover {% endblock %}

{% block content %}

<form method="POST" enctype="multipart/form-data" action="{% url 'user:upload_cover' %}">
    {% csrf_token %}
  {{ form|crispy }}
<button type="submit" class="btn btn-primary btn-md">Upload</button>
</form>

{% endblock %}

settings.py

INSTALLED_APPS = [
    'revealy_admin.apps.RevealyAdminConfig',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'crispy_forms',
    'channels',
    'users',
    'chats',
]

CRISPY_TEMPLATE_PACK = 'bootstrap4'

Thanks

CodePudding user response:

Since you are rendering only one field, you can use this instead:

{{ form.field_name|as_crispy_field }}
  • Related