Search code examples
pythondjangoforeign-keys

Connect uploaded file to a post in Django


I am trying to connect an uploaded document with the related post in Django. The idea is that when a user creates a post (I called it seed in my code), he can upload a document with it if he wants to. I tried using the joint method to do so, but it is not working (either telling me it expects an "str" and not an "int" or telling me the ForeignKey condition is not working). Is there any way to then connect those two classes, and successfully upload a file? Thank you for any help!!

Here is what I tried:

views.py

"""

def seed_create(request):
    if request.method == "POST":
        seed_form = SeedForm(request.POST)
        docu_form = DocumentForm(request.POST, request.FILES)
        if seed_form.is_valid() and docu_form.is_valid():
            seed_form.instance.user = request.user
            docu_form.save()
            seed_form.save()
            messages.success(request, 'Your seed was successfully created!')
            return redirect('seed:view_seed')
        else:
            messages.error(request, 'Please correct the error below.')
    
    else:
        seed_form = SeedForm(request.POST)
        docu_form = DocumentForm(request.POST, request.FILES)
    return render(request, "seed/create.html", context={"seed_form": seed_form, "docu_form": docu_form})

    

"""

models.py

"""

def gallery_folder(instance, file):
    return '/'.join(['documents', instance.seed_related_id, file])

class Document(models.Model):
    seed_related = models.ForeignKey(Seed,on_delete=models.CASCADE,default=1)
    description = models.CharField(max_length=255, blank=True)
    file = models.FileField(default="No file",upload_to=gallery_folder)
    uploaded_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

"""

forms.py

"""

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ('description', 'file')

"""


Solution

  • You need to link the seed_related to the Seed you construct through the form:

    def seed_create(request):
        if request.method == 'POST':
            seed_form = SeedForm(request.POST, request.FILES)
            docu_form = DocumentForm(request.POST, request.FILES)
            if seed_form.is_valid() and docu_form.is_valid():
                seed_form.instance.user = request.user
                seed = seed_form.save()
                docu_form.instance.seed_related = seed
                docu_form.save()
                messages.success(request, 'Your seed was successfully created!')
                return redirect('seed:view_seed')
            else:
                messages.error(request, 'Please correct the error below.')
        
        else:
            seed_form = SeedForm()
            docu_form = DocumentForm()
        return render(
            request,
            'seed/create.html',
            context={'seed_form': seed_form, 'docu_form': docu_form}
        )