1

How can i use my custom form called PayForm inside a template (Post.html) which is the template of a view called Post I tried to point both of the views to the same template but as i was told you can't point two views to the same template so i am currently stuck on this

models.py

from django.db import models
from django.urls import reverse
from PIL import Image

# Create your models here.


class Post(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, unique=True)
    created = models.DateTimeField(auto_now_add=True)
    content = models.TextField(default="---")
    current_price = models.IntegerField(default=0)
    reduction = models.IntegerField(default=0)
    original_price = models.IntegerField(default=0)
    Status = models.CharField(max_length=5, default="✓")
    img = models.CharField(max_length=255)
    sold = models.IntegerField(default=0)
    endday = models.CharField(max_length=30, default="apr 27, 2018 16:09:00")


    class Meta:
        ordering = ['-created']

        def __unicode__(self):
            return u'%s'% self.title

    def get_absolute_url(self):
        return reverse('Products.views.post', args=[self.slug])

    def __str__(self):
        return self.title



class Payment(models.Model):
    Author = models.CharField(max_length=255)
    Product = models.CharField(max_length=255)
    Payment_ID = models.CharField(max_length=255)
    Status = models.CharField(max_length=5, default="X")
    Review_result = models.CharField(max_length=255, default="Not yet reviewed")
    Address = models.CharField(max_length=255, default='')
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created']

        def __unicode__(self):
            return u'%s'% self.Status

    def __str__(self):
        return self.Status

views.py

from django.shortcuts import render, render_to_response , get_object_or_404, redirect
from .models import Post
from django.contrib.auth import authenticate, login, logout
from .forms import RegistrationForm, PayForm


def index(request):
    posts=Post.objects.all()
    return render(request, 'Index.html', {"posts": posts})


def post(request, slug):
    return render(request, 'post.html', {'post': get_object_or_404(Post, slug=slug)})

def new_payment(request):

    template ='payment.html'
    if request.method == 'POST':
        form = PayForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('index')
        else:
            print('form invalid')

    else:
        form = PayForm({'Author':request.user.username})

    context = {
        'form' : form,
    }
    return render(request, template, context)

forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Payment, Post

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)

    class Meta:
        model = User
        fields = (
                'username',
                'first_name',
                'last_name',
                'email',
                'password1',
                'password2',
            )

    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.email = self.cleaned_data['email']

        if commit:
            user.save()

        return user

class PayForm(forms.ModelForm):
    class Meta: 

        model = Payment
        fields = ['Author', 'Product', 'Payment_ID', 'Address']

If someone can help me with this it would be greatly appreciated

RaoufM
  • 525
  • 5
  • 22
  • Possible duplicate of [django submit two different forms with one submit button](https://stackoverflow.com/questions/18489393/django-submit-two-different-forms-with-one-submit-button) – Carl Brubaker May 06 '18 at 02:36
  • That's not what i wanted to do i want to use the payment form inside the post view like to set the curent post's slug as a default value for the product field in payment – RaoufM May 06 '18 at 11:33
  • Are you trying to get two `forms` on the same `view`? – Carl Brubaker May 06 '18 at 16:15
  • no i have one form which is new_payment and i want to display it on the post template – RaoufM May 06 '18 at 16:21

1 Answers1

0

If you have already created new_payment_form.html(or whatever you have called it) you can simply add to the post.html by using the {% include %} tag surrounded with appropriate <form> tags and whatever you need to go with it. The {% include %} essentially copies and pastes all the code from whatever file you have inside the tag. And a general rule, Product means class and product means variable or field.

# new_payment_form.html is the name of your html file. 
# template_path is the directory to your template. 
<form>
    {% include 'template_path/new_payment_form.html' %}
    <button> # submit button
</form>

However, you still need to process it in the view.

def post(request, slug):
    """
    (all the if: else: stuff)
    """
    # Set new_payment product
    new_payment = PayForm(initial={'Product': slug})

    return render(request, 'post.html', {'post': get_object_or_404(Post, slug=slug), 'new_payment': new_payment})

You will probably rewrite your view, and there are some details to figure out, but that should get you headed in the right direction. You might want to change slug to a product id or pk.

Carl Brubaker
  • 1,602
  • 11
  • 26