[Answered ]-User form foreignkeyfield form not valid

1👍

I think your problem come from the form instance which is instance=request.user, actually the instance is supposed to be the MemeImg object instance and not the user, that’s making it not to save the image. So i have deleted the instance and also i don’t know what you are using those extra context variable for ‘url’: func[0],’name’: func[1], ‘date’: func[2] ?, so i deleted them too keep things simple. Now i think you should be able to save without any Issues.

@login_required(login_url='/login')
def post(request):
    if request.method == 'POST':
        form = PostImg(request.POST, request.FILES)
        if form.is_valid():
            print('success')
            data = form.save(commit=False)
            data.op = request.user
            form.save()
            return HttpResponseRedirect('https://youtu.be/dQw4w9WgXcQ')
        else:
            print("fail")
            form = PostImg(request.POST)
    ctx = {
        'form': form,
    }
    return render(request, 'Post.html', ctx)

Also your form had in it {{ form.Post_Img }} which i don’t no what you are looking to accomplish with that variables?, the right way is doing {{ form.as_p }} or simply just calling the form like this {{ form }} so i have made the correction in you HTML
too.

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <div class="container">
        {{ form.Title|materializecss }}
        <div class="file-field input-field">
            <div class="btn">
                <span>File</span>
                <input type="file">
            </div>
            <div class="file-path-wrapper">
                {{ form }}
                <input class="file-path validate" type="text">
            </div>
        </div>
        <button class="btn waves-effect waves-light" type="submit" name="action">Submit
            <i class="material-icons right">send</i>
        </button>
    </div>
</form>
👤Godda

Leave a comment