I need something like this:
In one form there will be several file upload fields with multi uploads.
I would make it as single field, but I need then to filter it. E.g:
I will need to display on frontend all the file1, not file1 - file2 - file3 combined.
So, I Need model like this (but that works only for a single file upload)
class TestModel(models.Model):
#info 1
exp_date = models.DateField(default=None, blank=True, null=True)
file1 = models.FileField(upload_to="1/", blank=True, null=True)#multi files
#info 2
member_number = models.CharField(max_length=50, default=None)
file2 = models.FileField(upload_to="1/", blank=True, null=True)#multi files
#info 3
member_exp_date = models.CharField(max_length=50, default=None)
file3 = models.FileField(upload_to="1/", blank=True, null=True)#multi files
But it has to have multi file uploads in each "file upload" field, therefore I have to create another model like this for every file field
class FilesOne(models.Model):
file = models.FileField(upload_to="%Y-%m-%d/", blank=True, null=True)
files_key = models.ForeignKey('TestModel', on_delete=models.CASCADE,
default=None, null=True)
class FilesTwo(models.Model):
file = models.FileField(upload_to="%Y-%m-%d/", blank=True, null=True)
files_key = models.ForeignKey('TestModel', on_delete=models.CASCADE,
default=None, null=True)
...
and in views make for loop and run "create-objects" 'file-number' Times for every field like this:
add_files = request.FILES.getlist("file")
for i in add_files :
FilesOne.objects.create(files_key=user.driver, file=i)
So, is there any good solution to make it happen?
Related
I need to upload photos to specific directories.
I have below model code.
#reversion.register()
class Student(BaseModel):
uuid = models.UUIDField(default=uuid.uuid4, verbose_name=_("Unique Identifier"), unique=True)
user = models.OneToOneField(User, on_delete=models.PROTECT, db_index=True, verbose_name=_("User"))
photo = models.ImageField(upload_to="student/", null=True, blank=True, verbose_name=_("Photo"))
std_status = models.IntegerField(choices=STD_STATUS, default=1, verbose_name=_("Stu Sta"))
std_no = models.AutoField(primary_key=True, verbose_name=_("Stu Num"))
name = models.CharField(max_length=100, db_index=True, verbose_name=_("Name"))
surname = models.CharField(max_length=100, db_index=True, verbose_name=_("Surname"))
For the photo line. It uploads photos to student/ directory. But i need to have subdirectories with User name and dates. Like "student/jenifer_argon/2019223/2022/07/01"
I can set "student/" directory but username and std_no and date should be dynamically set. student/user/std_no/date user and std_no should come from above model on creation runtime.
How can i do this?
It is like; everything will be on same form. But std_no and user will be set first than they will be used to set upload diretory definition and image will be uploaded to that directory.
A function can be passed to upload_to that is passed the instance and filename, you can construct your path using these
from datetime import date
def student_photo_path(instance, filename):
today = date.today()
return 'student/{0}/{1}/{2}/{3}/{4}/{5}'.format(
instance.user.username,
instance.std_no,
today.year,
today.month,
today.day,
filename
)
class Student(BaseModel):
...
photo = models.ImageField(upload_to=student_photo_path, null=True, blank=True, verbose_name=_("Photo"))
...
I am reading this article about chunking a large database operation. I am also using django-import-export and django-import-export-celery in my admin site and I would like to integrate chunking into them.
The problem I have is django-import-export already handles the file import, as well as the whole process of importing, in the background.
I tried using django-import-export's bulk imports, but one of the caveats is:
Bulk operations do not work with many-to-many relationships.
so chunking is what we thought was the alternative. Is it possible to perform chunking inside the django-import-export?
UPDATE - ADDED MODEL:
class Profile(models.Model):
firstname = models.CharField(max_length=200)
lastname = models.CharField(max_length=200, blank=True, null=True)
email = models.EmailField(max_length=200)
associated_issuer = models.ManyToManyField('app.Issuer', related_name='add_issuer', blank=True)
associated_profile = models.ManyToManyField('app.Profile', related_name='add_profile', blank=True)
class Issuer(models.Model):
# personal information
name = models.CharField(max_length=200, blank=True, null=True)
contact_email = models.EmailField(max_length=200, blank=True, null=True)
associated_profile = models.ManyToManyField('app.Profile', related_name='add_profile_2', blank=True)
associated_issuer = models.ManyToManyField('app.Issuer', related_name='add_issuer_2', blank=True)
Can someone tell me how to combine two or more attribute values of in another field by using instance?
Models.py:
fn_id = models.ForeignKey(FilemNumber, null=True, blank=True)
ln_id = models.ForeignKey(LineNumber, null=True, blank=True)
pn_id = models.ForeignKey(PhotoNumber, null=True, blank=True)
title = models.CharField(max_length=255,blank=True, null=True)
I want to combine fn_id, ln_id and pn_id and save the combination of the three values into field title.
You can do this:
from django import models
class BaseModel(models.Model):
fn_id = models.ForeignKey(FilemNumber, null=True, blank=True)
ln_id = models.ForeignKey(LineNumber, null=True, blank=True)
pn_id = models.ForeignKey(PhotoNumber, null=True, blank=True)
class YourModel(models.Model):
common = models.OneToOneField(BaseModel)
# I suppose that you want to get title, so let define title method
# if obj is an instance of YourModel, you can access title like this:
# obj.title
#property
def title(self):
return '{}{}{}{}'.format(self.id, self.common.fn_id,
self.common.ln_id, self.common.pn_id)
Lets read this article: https://docs.djangoproject.com/en/1.8/ref/models/fields/#onetoonefield
I am trying to export all my database with a prefetch_related but I only get data from the main model.
My models:
class GvtCompoModel(models.Model):
gvtCompo= models.CharField(max_length=1000, blank=False, null=False)
...
class ActsIdsModel(models.Model):
year = models.IntegerField(max_length=4, blank=False, null=False)
...
class RespProposModel(models.Model):
respPropos=models.CharField(max_length=50, unique=True)
nationResp = models.ForeignKey('NationRespModel', blank=True, null=True, default=None)
nationalPartyResp = models.ForeignKey('NationalPartyRespModel', blank=True, null=True, default=None)
euGroupResp = models.ForeignKey('EUGroupRespModel', blank=True, null=True, default=None)
class ActsInfoModel(models.Model):
#id of the act
actId = models.OneToOneField(ActsIdsModel, primary_key=True)
respProposId1=models.ForeignKey('RespProposModel', related_name='respProposId1', blank=True, null=True, default=None)
respProposId2=models.ForeignKey('RespProposModel', related_name='respProposId2', blank=True, null=True, default=None)
respProposId3=models.ForeignKey('RespProposModel', related_name='respProposId3', blank=True, null=True, default=None)
gvtCompo= models.ManyToManyField(GvtCompoModel)
My view:
dumpDB=ActsInfoModel.objects.all().prefetch_related("actId", "respProposId1", "respProposId2", "respProposId3", "gvtCompo")
for act in dumpDB.values():
for field in act:
print "dumpDB field", field
When I display "field", I see the fields from ActsInfoModel ONLY, the starting model. Is it normal?
You haven't understood the arguments to prefetch_related. It's not a list of fields, but a list of models.
(Note that your field naming convention is also very misleading - respProposId1 and actId are not IDs, but actual instances of the models. Django has created an underlying field in each case by appending _id, so the db columns are respProposId1_id and actId_id. You should just call the fields resp_propos1 and resp_propos2 - also note that normal style is lower_case_with_underscore, not capWords.)
It is normal, that you are seeing fields from ActsInfoModel only. You can access related models via dot notation, like:
acts = ActsInfoModel.objects.all().prefetch_related("actId", "respProposId1", "respProposId2", "respProposId3", "gvtCompo")
for act in acts:
print act.respProposId1.respPropos
Related models are already prefetched, so it won't produce any additional queries. FYI, quote from docs:
Returns a QuerySet that will automatically retrieve, in a single
batch, related objects for each of the specified lookups.
I am currently building a page in django, where there are 4 form fields, 2 text, 2 select fields, and when submitted it takes those fields and searches several models for matchinng items.
the model looks like this:
class Person(models.Model):
user = models.ForeignKey(User, blank=True, null=True, verbose_name="the user associated with this profile")
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
about = models.TextField(max_length=255, blank=True, null=True)
birthdate = models.DateField(blank=True, null=True, verbose_name="Birthdate (yyyy-mm-dd)")
GENDER_CHOICES = (
(u'M', u'Male'),
(u'F', u'Female'),
)
gender = models.CharField(max_length=1, choices = GENDER_CHOICES, default = 'M')
picture = models.ImageField(upload_to='profile', blank=True, null=True)
nationality = CountryField(blank=True, null=True)
location = models.CharField(max_length=255, blank=True, null=True)
command_cert = models.BooleanField(verbose_name="COMMAND certification")
experience = models.ManyToManyField('userProfile.MartialArt', blank=True, null=True)
and I am trying to search the first_name field, the last_name field, the nationality field, and the experience field, but say if the first_name field is blank, I need to pass an empty value so it returns all rows, then filter from there with last name the same way, for some reason it is not working at all for me. this is my sqs:
results = SearchQuerySet().models(Person).filter(first_name=sname, last_name=slastname, nationality=scountry, experience__pk=sexperience)
any ideas?
Without seeing specific errors or a stack trace, it's hard to determine what "is not working at all".
Edit: Looking at your provided view code, I would remove the filter and return all of the objects for your Fighter, Referee, Insider, and Judge models. This is to ensure that the issue here lies in the filter, and not something else.
Then, once I'd verified that objects are being placed into results, I'd put in the filters one at a time to determine what the problematic filter is. Give this a try and reply back with your results.