0
class IndexView(generic.ListView):
    template_name = "posts/index.html"

    def get_queryset(self):
        return Inspectionfile.objects.all()

class DetailView(generic.DetailView):
    model = Inspectionfile
    template_name = "posts/detail.html"


class createposts(CreateView):
    model = posts
    fields = ['title','comments']

via the createposts and using forms I can populate the title and comments but they are not being linked with any Inspectionfile(the foreign key). I want the users to be linked without them having to choose. The following is my model. So I want to link every post to a particular inspectionfile.

class Inspectionfile(models.Model):
    document_upload = models.FileField()
    document_type = models.CharField(max_length=10)
    document_title = models.CharField(max_length=250)
    document_check = models.CharField(max_length=250)

    def __str__(self):
        return (self.document_title + self.document_type)


class posts(models.Model):
    inspectionfile = models.ForeignKey(Inspectionfile, on_delete=models.CASCADE, default=1)
    title = models.CharField(max_length=120)
    comments = models.TextField()
    flag = models.BooleanField(default=False)

    def get_absolute_url(self):
        return reverse('posts_form', kwargs={'pk': self.pk})

    def __str__(self):
        return self.title 

form is a simple template:

<form class = "form_horizontal" action = "" method = "post">
    {% csrf_token %}
    {{form.as_p}}
    <button type="submit">Submit</button>
</form>
jape
  • 2,861
  • 2
  • 26
  • 58

1 Answers1

1

Well I think you need to override post method in your createposts view:

def post(self, request, *args, **kwargs):
    current_inspectionfile = Inspectionfile.objects.get(pk= 
                      #enter id of current file. If id is 
                      #parameter in url then use self.kwargs['file_id'], 
                      #where file_id is name of parameter in url
                      )
    new_post = posts.objects.create(inspectionfile=current_inspectionfile, 
                      #and arguments from the form
                      )
    return new_post

And Off-topic: class names in python are usually called in CamelCase in the singular. So class Post(models.Model) and class CreatePost(CreateView):

Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48
  • Thanks that makes sense. But when you say form arguments , you see I don't have an actual form.py , is there a way to pull the post attributes from template. – Ishan Subedi Nov 15 '16 at 00:16
  • @IshanSubedi check [this](http://stackoverflow.com/questions/11336548/django-taking-values-from-post-request). And by 'form' I mean form in your template. – Yevhen Kuzmovych Nov 15 '16 at 00:19
  • do you know why I keep getting: 'posts' object has no attribute 'get' error. The url.py seems to be fine. Is it because ,since we are creating a new object new_post and it does not know what to do with it? – Ishan Subedi Nov 15 '16 at 01:52