In my project I need to change the location where files are being uploaded. This is done using a FileSystemStorage. The path were the files are uploaded should be easy to configure, for example using the Django Admin.
from django.core.files.storage import FileSystemStorage
from django.db import models
class Setting(models.Model):
entry = models.CharField(primary_key=True, db_column="entry", max_length=50)
value = models.CharField(db_column="value", max_length=250, blank=True, null=True)
def __unicode__(self):
return "%s" %(self.entry)
class Meta:
db_table = 'settings'
verbose_name = 'Setting'
verbose_name_plural = 'Settings'
fs = FileSystemStorage(location=Setting.objects.get(entry__exact='upload_path').value)
def generate_filename(instance, filename):
...
class FileImport(models.Model):
data_file = models.FileField(_('Data file'), upload_to=generate_filename, storage=fs)
I receive this error:
django.db.utils.DatabaseError:
relation "settings" does not exist
LINE 1: ...ELECT "settings"."entry", "settings"."value" FROM "settings"...
for the line where FileSystemStorage is being created. Is there a way of telling Django to create table settings(for Setting objects) first and then fill this table with some fixtures?
That won't solve your problem, since the Settings table still won't be populated. Move it into a class attribute that gets initialized the first time it's instantiated.
Related
I don't have the advertisement module displayed in the django admin panel. Here is the model code
from django.db import models
class Advertisement(models.Model):
title = models.CharField(max_length=1000, db_index=True)
description = models.CharField(max_length=1000, default='', verbose_name='description')
creates_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
price = models.FloatField(default=0, verbose_name="price")
views_count = models.IntegerField(default=1, verbose_name="views count")
status = models.ForeignKey('AdvertisementStatus', default=None, null=True, on_delete=models.CASCADE,
related_name='advertisements')
def __str__(self):
return self.title
class Meta:
db_table = 'advertisements'
ordering = ['title']
class AdvertisementStatus(models.Model):
name = models.CharField(max_length=100)
admin.py /
from django.contrib import admin
from .models import Advertisement
admin.site.register(Advertisement)
I was just taking a free course from YouTube. This was not the case in my other projects. Here I registered the application got the name in INSTALLED_APPS. Then I performed the creation of migrations and the migrations themselves. Then I tried to use the solution to the problem here , nothing helped. I didn't find a solution in Google search either.
127.0.0.1:8000/admin/
console
admins.py
The name of the file is admin.py not admins.py. Yes, that is a bit confusing since most module names in Django are plural. The rationale is probably that you define a (single) admin for the models defined.
Alternatively, you can probably force Django to import this with the AppConfig:
# app_name/apps.py
from django.apps import AppConfig
class AppConfig(AppConfig):
def ready(self):
# if admin definitions are not defined in admin.py
import app_name.admins # noqa
Currently, I want to create a folder whenever I try to add a new tag in Django admin. But I don't know how to realize this function. my model.py code is as below:
class Tags(models.Model):
Tag_name = models.CharField('Tag Name', max_length=10, default='NA')
Description = models.TextField('Tag Description', max_length=100, blank=True)
class Meta:
verbose_name = 'Tags'
verbose_name_plural = verbose_name
def __str__(self):
return self.Tag_name
The function I want is, for example, if I create a tag named "test", the system will automatically create a folder named "test" in a specific place.
You can use signals, in your model.py
from django.db.models.signals import post_save
def callback(*args, **kwargs):
instance = kwargs.get('instance')
# Do after save
post_save.connect(callback, sender=Tags)
I'm writing my news web-site and I already have translit widget imported into my django models.py
and it's looks like
class Article(models.Model):
class Meta():
db_table = "article"
verbose_name = "Новость"
verbose_name_plural = "Новости"
def get_image_path(self, filename):
path = ''.join(["static/article/", translit.slugify(filename)])
return path
article_image1 = models.ImageField(upload_to= get_image_path, null=True, blank=True, verbose_name = "Фотография 1")
In that case all uploaded images are stored in path_to_app/static/article/some_image_name.jpg
But we have a lot of images and storing them in one folder is very problematicaly.
the problem is:
How can I save image to
path_to_app/static/article/todays_year/todays_month/todays_date/some_image_name.jpg
Thank you
Use the datetime.date.strftime() function.
from datetime import date
def get_image_path(self, filename):
path = ''.join([date.today().strftime('static/article/%Y/%m/%d/'),
translit.slugify(filename)])
return path
You can return a string from your upload_to function - in this case get_image_path, with the date-formatters in it, and Django will pass the date information to the string. (https://docs.djangoproject.com/en/1.7/ref/models/fields/#django.db.models.FileField.upload_to)
I'm trying to have this third class noticeTime be constrained to the foreign key email. I am using the same syntax that worked for the 2nd class location, but when I use it on noticeTime it throws an error:
Exception Value: no such column: setupNotifications_noticetime.email_id
Here is the code:
from django.db import models
# Create your models here.
from django.db import models
class email(models.Model):
email = models.CharField(max_length=200)
def __unicode__(self):
return self.email`
class location(models.Model):
email = models.ForeignKey(email)
zip_code = models.CharField(max_length=5)
def __unicode__(self):
return self.zip_code
class noticeTime(models.Model):
email = models.ForeignKey(email)
time = models.CharField(max_length=200)
def __unicode__(self):
return self.time
here is admin.py:
from django.contrib import admin
# Register your models here.
from setupNotifications.models import email
from setupNotifications.models import location
from setupNotifications.models import noticeTime
admin.site.register(email)
admin.site.register(location)
admin.site.register(noticeTime)
I'm using the sqlite database
Perhaps your problem is that you ran syncdb, assuming that it would alter the table to match your model change. Unfortunately, it does not do that. There are some separate tools available, such as South, which can help with database migrations.
When I try to migrate my code I get this error.
Here are my code and classes:
from django.db import models
from core.models import Event
class TicketType(models.Model):
name = models.CharField(max_length=45)
price = models.DecimalField(max_length=2, decimal_places=2, max_digits=2)
type = models.CharField(max_length=45)
amount = models.IntegerField()
event = models.ForeignKey(Event)
class Meta:
app_label = "core"
import datetime
from django.core.serializers import json
from django.db import models
from core.models import User
class Event(models.Model):
page_attribute = models.TextField()
name = models.TextField(max_length=128 , default="New Event")
description = models.TextField(default="")
type = models.TextField(max_length=16)
age_limit = models.IntegerField(default=0)
end_date = models.DateTimeField(default=datetime.datetime.now())
start_date = models.DateTimeField(default=datetime.datetime.now())
is_active = models.BooleanField(default=False)
user = models.ForeignKey(User)
ticket_type=models.ForeignKey('core.models.ticket_type.TicketType')
class Meta:
app_label = "core"
Here is the error I get:
CommandError: One or more models did not validate:
core.event: 'ticket_type' has a relation with model core.models.ticket_type.TicketType,
which has either not been installed or is abstract.
You're unnecessarily confusing yourself by having these in separate files within the same app.
But your issue is caused by the way you're referenced the target model. You don't use the full module path to the model: you just use 'app_name.ModelName'. So in your case it should be:
ticket_type=models.ForeignKey('core.TicketType')
Another issue can be when using multiple models in separate files missing statement like:
class Meta:
app_label = 'core_backend'
You can also get this error if there a bug in your models file that prevents it from loading properly. For example, in models.py
from third_party_module_i_havent_installed import some_method
I hit this error when I didn't put a third-party app in my INSTALLED_APPS setting yet.