I have short model definition
class File(models.Model):
id = models.IntegerField(primary_key=True);
file = models.FileField(upload_to='%id')
title = models.CharField(max_length=128)
upload_date = models.DateTimeField(auto_now_add=True, blank=True);
as u see (or not) I would like this model to handle upload so file name would be the same as row id. Is it possible to do it this way somehow?
sure you can
def update_filename(instance, filename):
filename_ = instance.id
file_extension = filename.split('.')[-1]
return '%s.%s' % (filename_, file_extension)
class File(models.Model):
id = models.IntegerField(primary_key=True)
file = models.FileField(upload_to=update_filename)
title = models.CharField(max_length=128)
upload_date = models.DateTimeField(auto_now_add=True, blank=True)
and I would change the class name to something else, so it does not shadow the built in File.
Related
I have a model Currency defines below:
class Currency(models.Model):
"""
Currency Model
Defines the attribute of Currency
"""
class Meta:
verbose_name = "Currency"
verbose_name_plural = "Currencies"
ordering = ['Currency_Name']
def __str__(self):
return self.Currency_Name
Currency_Date = models.DateTimeField(auto_now_add=True)
Currency_Date_Update = models.DateTimeField(auto_now=True)
Currency_Name = models.CharField(max_length=3, unique=True)
Is_Secondary_Ccy = models.CharField(max_length=1, choices=Y_N_BOOLEAN)
Primary_Currency = models.ForeignKey('self', on_delete=models.DO_NOTHING, null=True) # to refer to itself
Primary_Factor = models.IntegerField(default=1)
Currency_Name_Reuters = models.CharField(max_length=3)
The model is linked to itself by the column "Primary_Currency"
In my admin (image below) I can see the linked, but if i open the dropdown, the label is not user friendly "Currency object (0) etc..."
Can I have the value "Currency_Name" of the "Primary_Currency" ?
thanks for your help :)
Use __str__() method of model class,
class Currency(models.Model):
...
# your code
def __str__(self):
try:
return self.Primary_Currency.Currency_Name
except AttributeError:
return self.Currency_Name
I'm going to build up an assets management system. Every property has an unique property-code combine with department-code and type-code.
from django.db import models
class Department(models.Model):
# department_code like rm01
department_code = models.CharField(max_length=4, unique=True)
name = models.CharField(max_length=100)
class Type(models.Model):
# type_code like fe03
type_code = models.CharField(max_length=4, unique=True)
name = models.CharField(max_length=100)
class Property(models.Model):
# property_code like rm01fe037767
property_code = models.CharField(max_length=12, unique=True)
name = models.CharField(max_length=100)
department = models.ForeignKey(Department)
type = models.ForeignKey(Type)
How to do that? OR is there another way to achieve the aim?
Yes but not automatically.
In the normal case: when you want to add new Propery ~> User should pick other 2 model right?
dep_id = ?
type_id= ?
p = Property (id = dep_id+type_id, name = "blabla"...)
p.save()
And you should define the PK (default is int field, auto incre ~> to charfield) and input it by yourself
And normally: we don't do that...
We use: ForeignKey like:
class Item(models.Model):
people = models.ForeignKey(People)
name = models.CharField(max_length=40)
value = models.IntegerField(default=0)
def __str__(self):
return self.name
I want to know, is it my code ok?
What i want: create form with feature uploading multiple files.
Can someone say about many-to-many? Is it ok?
I want to upload many files. How it can be?
from __future__ import unicode_literals
import uuid
from django.db import models
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return os.path.join('file_uploads/%Y/%m', filename)
# Create your models here.
class Order(models.Model):
name = models.CharField(max_length=255)
email = models.CharField(max_length=255)
phone = models.CharField(max_length=255, blank=True)
reference = models.CharField(max_length=255)
files = models.ManyToManyField(File)
deadline = models.DateTimeField(auto_now_add=False, auto_now=False)
class File(models.Model):
name = models.CharField(max_length=255)
file = models.FileField(upload_to=get_file_path)
Updated: I get error when i'm trying to makemigrations command:
File "/home/dima/web/files_2016_04/fileupl/flpp/models.py", line 11, in <module>
class Order(models.Model):
File "/home/dima/web/files_2016_04/fileupl/flpp/models.py", line 16, in Order
files = models.ManyToManyField(File)
NameError: name 'File' is not defined
But it defined. Whats wrong?
Updated: i solve this problem moving File class before Order class
UPD Thanks, i solved problem with ForeignKey('File') with quotes
You just need to declare File class upper than Order class
# Create your models here.
class File(models.Model):
name = models.CharField(max_length=255)
file = models.FileField(upload_to=get_file_path)
class Order(models.Model):
name = models.CharField(max_length=255)
email = models.CharField(max_length=255)
phone = models.CharField(max_length=255, blank=True)
reference = models.CharField(max_length=255)
files = models.ManyToManyField(File)
deadline = models.DateTimeField(auto_now_add=False, auto_now=False)
If you want to keep the current structure, you'll need to put it in quotes:
files = models.ManyToManyField('File')
I have a simple form which is used for submitting files which worked fine. I've since moved the file out from a field into its own table, now I'm really struggling as I need to add the file to the extra table and save the correct foreignkey in the form table. I've tried various snippets in save(), grabbing the file in the view and adding the file as an extra field but nothing is quite working.
The fairly obvious error is:
"Cannot assign InMemoryUploadedFile: Resource.file must be a File
instance"
class File(models.Model):
filename = models.CharField('Filename', max_length=200)
file = models.FileField()
mimetype = models.CharField('Mimetype', max_length=200)
pub_date = models.DateTimeField('date published', auto_now_add=True, blank=True)
def __str__(self):
return self.filename
class Resource(models.Model):
list_display = ('title', 'approved')
def __str__(self):
return str(self.title)
title = models.CharField('Title', max_length=200)
description = models.TextField('Description', null=True)
file = models.ForeignKey(File)
... cut for brevity
class ResourceForm(forms.ModelForm):
class Meta:
model = Resource
the problem is that you assign a file into a foreign key field. You need to instantiate the File object first and then set in to Resource object.
file = File(filename="test", file=temp_data, mimetype='pdf')
file.save()
resource.file = file
resource.save()
I've added a MultivaluedField to my index (haystack), I need to search for a ManyToMany related field, but it doesn't work.
The engine is WHOOSH.
This how my index looks like:
class PostIndex(SearchIndex):
text = CharField(document=True, use_template=True)
author = CharField(model_attr='author')
body = CharField(model_attr='body')
pub_date = DateTimeField(model_attr='publish')
regions = MultiValueField()
def prepare_regions(self, obj):
return [region.name for region in obj.regions.all()]
And this how my model looks like:
class Post(models.Model):
title = models.CharField(_('title'), max_length=200)
author = models.ForeignKey(User, blank=True, null=True)
body = models.TextField(_('body'), )
allow_comments = models.BooleanField(_('allow comments'), default=True)
publish = models.DateTimeField(_('publish'), default=datetime.datetime.now)
categories = models.ManyToManyField(Category, blank=True)
tags = TagField()
objects = PublicManager()
regions = models.ManyToManyField(Region, blank=True)
If I use SearchQuerySet().filter(region__in=words_list) it works. The problem is that I don't know when the user is searching for a region or another field, so I have to use SearchQuerySet().filter(content__icontains=words_list). And in this way nothing is found.
Thanks
Thanks!!
Try :
class PostIndex(SearchIndex):
text = CharField(document=True, use_template=True)
author = CharField(model_attr='author')
body = CharField(model_attr='body')
pub_date = DateTimeField(model_attr='publish')
regions = CharField(model_attr='regions')
You only add region id to the index for Region.
Try
def prepare_regions(self, obj):
return [region.pk for region in obj.regions.all()]