I
I
ILoveYAnny2016-01-26 07:34:13
Django
ILoveYAnny, 2016-01-26 07:34:13

How to use fields from different models in ModelForm?

Good afternoon or morning everyone. Guys, the question is stupid, but I'm just learning, and I found solutions in the docks.
The bottom line is, there are 2 models, they have their own fields. One model stores the Title and Description, the other Image. Duck Vod, I need a form where I can create a new item by filling in all these fields and uploading an image.
I am making a ModelForm

class SlideForm(forms.ModelForm):

  class Meta:
            model = Slide
            fields = ('title', 'center', 'align_title_in_image', 'slug')

Everything works fine, but I need to add a field to load an image from another model, the first thing that came to mind
class SlideForm(forms.ModelForm):
  class Meta:
            model = Slide
            fields = ('title', 'center', 'align_title_in_image', 'slug')

class ImageSlideForm(forms.ModelForm):
  class Meta:
            model = SlideImage
            fields = ('image',)

But how to properly describe them in a view? Here is such an approach, it displays only the first class, and there is no class for images
def add_slide(request):
        form = SlideForm(), ImageSlideForm()	
        return render_to_response("add_slide.html",{'form': form},context_instance=RequestContext(request))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2016-01-26
@ILoveYAnny

def add_slide(request):
        slide_form = SlideForm()
        image_slide_form = ImageSlideForm()	
        return render(request, "add_slide.html", 
                   {'slide_form': slide_form, 
                    'image_slide_form': image_slide_form})

https://docs.djangoproject.com/en/1.9/topics/forms...
<form>
{% csrf_token %}
{{ slide_form.as_p }}
{{ image_slide_form.as_p }}
<button type="submit">submit</button>
</form>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question