devilsgrin
devilsgrin

Reputation: 43

Django Saving files in database with username

I am getting multiple file entries from the user. And I save all of these in the database in one go.

But I don't want these files to get mixed up when multiple users use the system. Therefore, when I save each file, I want the username that uploaded that file to be saved in the database.

Models.py

class users(models.Model):
    person_name = models.CharField(max_length=50, null=False, blank=True, verbose_name="name")
    person_surname = models.CharField(max_length=50, null=False, blank=True, verbose_name="surname")
    email = models.CharField(max_length=100, null=False, blank=True, verbose_name='email')
    user_name = models.CharField(max_length=30, null=False, blank=True, verbose_name="username")
    user_password = models.CharField(max_length=35, null=False, blank=True, verbose_name="password")


class files(models.Model):
    owner= models.OneToOneField(User, unique=True, related_name="owner", on_delete=models.CASCADE)

    description = models.CharField(max_length=255, blank=True)

    excelFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,)

    wordFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,)
    
    txtEmailFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,)
     
    txtContentFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,)

    attachmentFile = models.FileField(upload_to='upload/%Y/%m/%d',null=False, blank=True,)

forms.py

class DocumentForm(forms.ModelForm):
    class Meta:
        model = files
        fields = ('description', 'excelFile', 'wordFile', 'txtEmailFile', 'txtContentFile', 'attachmentFile')

views.py ( only one func ):

@login_required(login_url="login")
def sendmail(request):

    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)

        if form.is_valid():
            form.save()
            return redirect('sendmail')

        else:
            form = DocumentForm()

    return render(request, 'sendmail.html')

I am not adding the html file here because I received multiple file entries from the user and the html file is mixed.

Database ( MySql Workbench ): enter image description here

How can I do it ?

Upvotes: 0

Views: 1300

Answers (1)

JLeno46
JLeno46

Reputation: 1269

Try this:

if request.method == 'POST':        
    form = DocumentForm(request.POST, request.FILES)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.owner = request.user
        instance.save()
        return redirect('sendmail')

You can save an instance without commit modify one or more fields, and then save and commit.

Upvotes: 2

Related Questions