Get field value and save to models

Hello everybody hope everybody is doing well.

My question is how do I get a field value (that is not a part of my models) and save that value to a models field?

Below you can see I get the document text but now I want to store it in my models (BEFORE creation) in my model field doc_text.

def create(request):
    if request.method == 'POST':

        form = forms.CreateBlog(request.POST)

        if form.is_valid(): 
            file = request.FILES["doc_text"]
            doc_text_str = DocText(file) # HOW DO I ASSIGN THIS VALUE TO MY MODELS (doc_text)

            instance = form.save(commit=False)
            instance.author = request.user
            instance.save()
            return redirect('workspace:list')
    else:     
        form = forms.CreateBlog()
    return render(request, 'workspace/blog_create.html', {'form':form})
class Blog(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE, default="Anonymous")
    doc_text = models.TextField(blank=True)

You input/answer would be greatly appreciated! Thanks!

Is your “CreateBlog” form a model form for Blog?

If so, notice how in your if block you’re assigning a value to the author member variable of Blog to request.user. It’s exactly the same thing for the doc_text variable.

Also note that depending upon what the DocText object does, you might want to call that in your if block as well. It wouldn’t appear to be worthwhile to call that if you don’t otherwise have a valid form.

Ah yes it was there I copied and pasted my own code improperly. Thanks. It is now updated :slight_smile: I have also included it now in the if statement. How do I set that value to the doc_text in the models and save it?

What does this specific line of code do?
(Yes, this is a hint.)

Yes that worked! Thanks again @KenWhitesell :+1: