Django upload multiple files many to many - django

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')

Related

How to populate a django manytomany database from excel file

I'm trying to transfer data from a excel file into a manytomany table in my sqlite3 database.
model.py
from django.db import models
class Major(models.Model):
name = models.CharField(max_length=30, db_index=True)
class School(models.Model):
name = models.CharField(max_length=50, db_index=True)
majors = models.ManyToManyField(Major)
class professor(models.Model):
ProfessorIDS = models.IntegerField()
ProfessorName = models.CharField(max_length=100)
ProfessorRating = models.DecimalField(decimal_places=2,max_digits=4)
NumberofRatings = models.CharField(max_length=50)
#delete major from the model
school = models.ForeignKey(School , on_delete=models.CASCADE)
major = models.ForeignKey(Major , on_delete=models.CASCADE)
def __str__(self):
return self.ProfessorName
Populating Script
# populate.py, school_major_link
import os
import django
from django_xlspopulator.populator import Populator
os.environ.setdefault('DJANGO_SETTINGS_MODULE','blog_project.settings')
django.setup()
from locate.models import Major
pop = Populator('C:/Users/David/Desktop/db_setup/School_Majors.xlsx', school_majors)
pop.populate()
Error message when attempting to run script
Traceback (most recent call last):
File "populate_school_major.py", line 9, in <module>
pop = Populator('C:/Users/David/Desktop/db_setup/School_Majors.xlsx', school_majors)
NameError: name 'school_majors' is not defined
But it makes sense since this script looks for the class name in the models section verses the name of the table, so I'm not too sure how I would be able to populate the correct table, Note that I already have a table named majors which is already populated using this script, but since django makes manytomany relationships via a variable verses a seperate class i'm stuck.
I tried using the populating script above, but noticed that this wouldn't work since it's locating the class, verses what the database table is saved as. (In sqlite3, the tables name for the majors manytomanyfield is called school_majors).
If anyone has any recommendations on how I can populate the db that would be great.
Picture below of the database table name.
Excel file below
When you define a ManyToManyField in Django, it creates a model behind-the-scenes to store the mapping.
You can access this model using the through attribute of the ManyToManyField. In your case, this would be:
locate.models.School.majors.through
Your current script is failing because school_majors is not a defined name at all - try replacing it with a reference to the model you wish to populate:
pop = Populator('C:/Users/David/Desktop/db_setup/School_Majors.xlsx', locate.models.School.majors.through)
pop.populate()
If this does not work, you might wish to consider defining an explicit through model on the ManyToManyField (as explained in the Django docs) and then specify that in your Populator instantiation.
Good luck!
As lukewarm stated, setting the through allowed me to create a class, which I was able to reference with my script which strictly would be able to populate by locating a class in the model.py
from django.db import models
class Major(models.Model):
name = models.CharField(max_length=30, db_index=True)
class School(models.Model):
name = models.CharField(max_length=50, db_index=True)
school_Major_merge = models.ManyToManyField(Major, through='School_Major')
class School_Major(models.Model):
major = models.ForeignKey(Major, on_delete=models.CASCADE)
school = models.ForeignKey(School, on_delete=models.CASCADE)
class professor(models.Model):
ProfessorIDS = models.IntegerField()
ProfessorName = models.CharField(max_length=100)
ProfessorRating = models.DecimalField(decimal_places=2,max_digits=4)
NumberofRatings = models.CharField(max_length=50)
#delete major from the model
school = models.ForeignKey(School , on_delete=models.CASCADE)
major = models.ForeignKey(Major , on_delete=models.CASCADE)
def __str__(self):
return self.ProfessorName

uploading file as id using models ind django

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.

Django saving file to different model

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()

Cannot run django server after integrating database

I am having problems running my server after I try to integrate the database with the application using the "python manage.py inspectdb > /models.py" command.
This is what I have in my models.py file
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# Feel free to rename the models, but don't rename db_table values or field names.
#
# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'
# into your database.
from __future__ import unicode_literals
from django.db import models
class AuthGroup(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=80)
class Meta:
db_table = 'auth_group'
class AuthGroupPermissions(models.Model):
id = models.IntegerField(primary_key=True)
group = models.ForeignKey(AuthGroup)
permission = models.ForeignKey('AuthPermission')
class Meta:
db_table = 'auth_group_permissions'
class AuthPermission(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=50)
content_type = models.ForeignKey('DjangoContentType')
codename = models.CharField(max_length=100)
class Meta:
db_table = 'auth_permission'
class AuthUser(models.Model):
id = models.IntegerField(primary_key=True)
password = models.CharField(max_length=128)
last_login = models.DateTimeField()
is_superuser = models.BooleanField()
username = models.CharField(max_length=30)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.CharField(max_length=75)
is_staff = models.BooleanField()
is_active = models.BooleanField()
date_joined = models.DateTimeField()
class Meta:
db_table = 'auth_user'
class AuthUserGroups(models.Model):
id = models.IntegerField(primary_key=True)
user = models.ForeignKey(AuthUser)
group = models.ForeignKey(AuthGroup)
class Meta:
db_table = 'auth_user_groups'
class AuthUserUserPermissions(models.Model):
id = models.IntegerField(primary_key=True)
user = models.ForeignKey(AuthUser)
permission = models.ForeignKey(AuthPermission)
class Meta:
db_table = 'auth_user_user_permissions'
class DjangoContentType(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100)
app_label = models.CharField(max_length=100)
model = models.CharField(max_length=100)
class Meta:
db_table = 'django_content_type'
class DjangoSession(models.Model):
session_key = models.CharField(max_length=40)
session_data = models.TextField()
expire_date = models.DateTimeField()
class Meta:
db_table = 'django_session'
class DjangoSite(models.Model):
id = models.IntegerField(primary_key=True)
domain = models.CharField(max_length=100)
name = models.CharField(max_length=50)
class Meta:
db_table = 'django_site'
class DjangoUser(models.Model):
firstname = models.CharField(max_length=256)
lastname = models.CharField(max_length=256)
username = models.CharField(primary_key=True, max_length=256)
password = models.CharField(max_length=256)
class Meta:
db_table = 'django_user'
and this is the error message I get
Unhandled exception in thread started by <bound method Command.inner_run of <django.contrib.staticfiles.management.comma
nds.runserver.Command object at 0x0000000002CD1518>>
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\django\core\management\commands\runserver.py", line 92, in inner_run
self.validate(display_num_errors=True)
File "C:\Python33\lib\site-packages\django\core\management\base.py", line 280, in validate
num_errors = get_validation_errors(s, app)
File "C:\Python33\lib\site-packages\django\core\management\validation.py", line 35, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "C:\Python33\lib\site-packages\django\db\models\loading.py", line 166, in get_app_errors
self._populate()
File "C:\Python33\lib\site-packages\django\db\models\loading.py", line 72, in _populate
self.load_app(app_name, True)
File "C:\Python33\lib\site-packages\django\db\models\loading.py", line 96, in load_app
models = import_module('.models', app_name)
File "C:\Python33\lib\site-packages\django\utils\importlib.py", line 35, in import_module
__import__(name)
TypeError: source code string cannot contain null bytes
It seems I have a null variable some place but I don't know where that is coming from. I would appreciate some help.
I just had this problem myself. I finally fixed it:
open the generated model.py file in Notepad++ (or other)
copy/paste the generated code into a new file in IDLE
Save over model.py
I'm not sure why this works, but I got an encoding error trying to open the file directly in IDLE. So I copy/pasted the code, and it fixes everything.
I had the same problem using Sublime 3 as editor. It got solved if I resaved the models.py file in my app folder as 'Save with Encoding :: UTF-8'.

TypeError: Error when calling the metaclass bases sequence item 2: expected string or Unicode, int found

I have the following models.py
from django.db import models
import datetime
class Build(models.Model):
build_name = models.CharField(max_length=60)
description = models.CharField(max_length=140)
parts = models.ManyToManyField('Part')
def __unicode__(self):
return self.build_name
class Part(models.Model):
name = models.CharField(max_length=70)
cost_usd = models.DecimalField(5, 2)
type_of = models.CharField(max_length=5)
supported_builds = models.ManyToManyField(Build)
def __unicode__(self):
return self.name
class OrderBuild(models.Model):
parent = models.ForeignKey(Build)
custom_parts = models.ManyToManyField(Part)
class PriceCache(models.Model):
price = models.DecimalField(4, 2)
time_fetched = models.DateTimeField(default=datetime.datetime.now())
I've tried commenting each of the lines one by one and rerunning, and there is no one line that seems to cause this bug. The only time it synced successfully was when I commented everything out in the model classes.
Does anyone know what is causing this bug, and how I can fix it?
Check the lines
cost_usd = models.DecimalField(5, 2)
# ...
price = models.DecimalField(4, 2)
by modifying them to
cost_usd = models.DecimalField(max_digits=5, decimal_places=2)
# ...
price = models.DecimalField(max_digits=4, decimal_places=2)
The signature of model fields are like
field(verbose_name=None, name=None, ...)
DecimalField(verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs)
Thus your code have verbose_name and name of the fields incorrectly set to integer numbers.