change django upload folder based on queryset - python

Gday, I'm working on a section of my data management project where users will be able to upload premade data for it to be parsed and inputted into the database. I am currently stuck on uploading files. The upload field will be on the main page for the specific dataset, which is navigated to by using the dataset id. What I would like is for any files uploaded in on that page to be saved in a directory such as "/projectroot/uploads/dataset_name". is this possible?

I think you are looking for something like this.
def my_memory_file_name(instance, filename):
return '/'.join(['my_memory', instance.user.username, filename])
class MyMemory(models.Model):
title = models.CharField(max_length=150, null=True, blank=True)
situation = models.TextField(help_text="Explain the situation of screenshot in few words")
date = models.DateField(null=True, blank=True, help_text="Date is not a required field")
screenshot = models.FileField(upload_to=my_memory_file_name)

Related

Different upload and download urls for Django Models's Image Field

I need a way to have different upload and download URLs for ImageField. I want to upload the image to AWS S3 and while accessing the image I want the image to route through CDN (in my case Fastly).
def get_avatar_upload_path(identity, filename):
file_ext = filename.split('.')[-1]
file_name = f'{uuid.uuid4()}.{file_ext}'
return f'{settings.AWS_MEDIA_PREFIX}{identity.uuid}/{file_name}'
class Identity(identity_revision_base):
"""
Identity model. Ties a user to a chat identity.
"""
badges = models.ManyToManyField(Badge, blank=True)
key = models.UUIDField(_("key"), unique=True, default=uuid.uuid4)
uuid = models.UUIDField(_("UUID"), unique=True, default=uuid.uuid4)
avatar = models.ImageField(upload_to=get_avatar_upload_path, blank=True)
user = models.ForeignKey(
to=settings.AUTH_USER_MODEL,
blank=True,
null=True,
on_delete=models.SET_NULL,
related_name="+",
)
Just like I am specifying upload path in ImageField, I would like a way to do something similar for accessing Image. It also seems that I cannot modify avatar.url once it is created. Is there any way around?
If there is any way, I can override the Model's behaviour to modify the url while accessing.
Did you check django-storages? It takes care of uploading to object store and returns CDN URLs for downloading. Fastly is S3 compatible so it should work.
In general you can also also use model methods with property decorator for getting a custom calculated value from model instances.

Django: Letting user download PDF file from database

How can I allow users to download PDF files from database? The PDF file is stored as a longblob in the MySQL database.
What I have so far:
views.py:
reports = Report.objects.all()
However doing so throws the following expcetion: <method 'fetch_row' of '_mysql_connector.MySQL' objects> returned a result with an error set
models.py:
class Report(models.Model):
studentid = models.IntegerField(db_column='studentId') # Field name made lowercase.
studentname = models.TextField(db_column='studentName') # Field name made lowercase.
year = models.CharField(max_length=4)
term = models.CharField(max_length=6)
report = models.TextField() #PDF should get stored here.
What can I do to allow user to see the files to download? I've been looking for ways to solve this problem however can't quite seem to figure it out. Any help is appreciated!
Thank you

Python - Django Share files between two authenticated users

I'm working on a project using Python(3.7) and Django(2.5) in which I'm building an application something like a freelancing site, but I'm stuck at one point while implementing the delivery submission part.
A user will create a service to sell and then a buyer will order his service, after that the seller has to be done the agreed job and need to submit the work to the buyer as a delivery.
The delivery will be in the form of a file, can be a text file, image file, audio, video or a code file, the problem is that I don't know how I can implement this thing in Django, so a user can send a file to another user in a private manner, so only both of these users will be able to access that file.
Here's what I have so far, for order between buyer and seller:
class Order(models.Model):
status_choices = (
('Active', 'Active'),
('Completed', 'Completed'),
('Late', 'Late'),
('Short', 'Short'),
('Canceled', 'Canceled'),
('Submitted', 'Submitted')
)
gig = models.ForeignKey('Gig', on_delete=models.CASCADE)
seller = models.ForeignKey(User, on_delete=models.CASCADE, related_name='selling')
buyer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='buying')
created_at = models.DateTimeField(auto_now=timezone.now())
charge_id = models.CharField(max_length=234)
days = models.IntegerField(blank=False)
status = models.CharField(max_length=255, choices=status_choices)
def __str__(self):
return f'{self.buyer} order from {self.seller}'
Any idea to implement the file sharing as delivery between two authenticated users?
Thanks in advance!
There is a lot of ways you could implement this.
You can simply add a field for users who access to file and let them download the file whenever they asked for download if they are authenticated and they are allowed to download that specific file.
With your model you can do something like this:
Giving gig field is your file you can create a slug or basically any link for a file and when user clicked on it you can get all the orders for that user, then check for the files that the access has been granted with these orders and if the file that users requests to download is one of them, simply let him download it.
You can let a user download a file using X-Sendfile which helps you check if users are allowed to download file or not.
Example here on stackoverflow
A sample code:
def download_file_view(request, file_id):
if not request.user:
# Redirect user or ...
if not request.user.is_authenticated:
# Redirect user or ...
# Check if this user has any orders with that file linked to it:
if Order.objects.filter(buyer=request.user, gig__pk=file_id).exists():
# User has bought this file already and the download should be allowed.
You can check for expiration date and all sorts of things there.

Save OneToManyRelationship based on url input in Django

I have two database which are OneToManyRelationship as shown below.
I am preparing interface for Data to be uploaded.
I want to specify the project attribute in Data model by inputting the url of the Project path like http://project/13.
Does anyone know how I can construct the relationship from url input of parent data?
Models.py
class Project(models.Model):
project = models.CharField(max_length=50, blank=True)
version = models.IntegerField(default=0)
class Data(models.Model):
project=models.ForeignKey(project)
csv=models.FileField(upload_to=dir_path)
If url in Project model sits in project field then you can do something like
# since project attribute is not unique, several ones can match so we pick first
project_object = Project.objects.filter(project=url).first()
if not project_object:
# error cant find it
Data.objects.create(
project=project_object,
csv=...,
)

How to upload images of 10k movies in one go in Django?

I am creating the website which contains 10k movies and it has an attribute called movies_logo which stores the logo of the respected movie .So is there any way so that I can upload all the logo of the respected movies in one go because uploading logo of each movie will take lot of time.This is my models.py.
from django.contrib.auth.models import Permission, User
from django.db import models
from decimal import Decimal
class Picture(models.Model):
user = models.ForeignKey(User, default=1)
picture_id = models.IntegerField(default=0)
picture_title = models.CharField(max_length=500)
genres = models.CharField(max_length=1000)
ratings = models.DecimalField(max_digits=10,decimal_places=1)
picture_logo = models.ImageField()
def __str__(self):
return self.picture_title
If you don't the save location for the images, then upload a single picture and see where it gets stored and with what name. If you don't like the naming, you can change it. Once that is figured out, you can simply go to your mysql command-line, and set the image field in the database to the file name and structure you have decided and then upload / move the images to the correct location. If you want, you can use a for loop to set the image field instead of writing SQL.

Categories