django upload file with custom name and directory name - django

i want to setup my django models for upload file with custom path and filename, my curent models :
def update_filename(instance, filename):
path = "accounts/"
format = instance.id + "/" + filename
return os.path.join(path, format)
class AccountsModel(models.Model):
ChannelName = models.CharField(max_length=100, unique=False)
AuthUri = models.CharField(max_length=250, unique=True)
ClientSecret = models.CharField(max_length=250, unique=True)
ClientID = models.CharField(max_length=250, unique=True)
ClientSecrets = models.FileField(upload_to="accounts/", default='', null=True, blank=False)
RequestToken = models.FileField(upload_to="accounts/", default='', null=True, blank=False)
Note = models.CharField(max_length=250, unique=False)
counter = models.IntegerField(default=0)
author = models.ForeignKey(User, null=True, blank=True, on_delete=models.PROTECT)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
when i try to upload file, i want to be like this :
/accounts/22/clientsecret.json
/accounts/22/token.json
my curent configuration return this error :
UNIQUE constraint failed: myupload_accountsmodel.ClientID
how i can do this ? Where i wrong ?
full project : https://github.com/scaltro/youtubeapp/blob/master/myupload/models.py

Related

django RelatedObjectDoesNotExist error while creating

models:
class FullNameMixin(models.Model):
name_id = models.BigAutoField(primary_key = True, unique=False, default=None, blank=True)
first_name = models.CharField(max_length=255, default=None, null=True)
last_name = models.CharField(max_length=255, default=None, null=True)
class Meta:
abstract = True
class Meta:
db_table = 'fullname'
class User(FullNameMixin):
id = models.BigAutoField(primary_key = True)
username = models.CharField(max_length=255, unique=True)
email = models.CharField(max_length=255, unique=True)
token = models.CharField(max_length=255, unique=True, null=True, blank=True)
password = models.CharField(max_length=255)
role = models.IntegerField(default=1)
verified = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True, null=True, blank=True)
def __str__(self):
return self.username
class Meta:
db_table = 'cga_user'
class Profile(FullNameMixin):
id = models.BigAutoField(primary_key = True)
birthday = models.DateTimeField(null=True, blank=True)
country = models.CharField(max_length=255, null=True, blank=True)
state = models.CharField(max_length=255, null=True, blank=True)
postcode = models.CharField(max_length=255, null=True, blank=True)
phone = models.CharField(max_length=255, null=True, blank=True)
profession_headline = models.CharField(max_length=255, null=True, blank=True)
image = models.ImageField(upload_to=get_upload_path, null=True, blank=True)
profile_banner = models.ImageField(upload_to=get_upload_path_banner, null=True, blank=True)
cga_user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE, related_name="profile")
gender = models.CharField(
max_length=255, blank=True, default="", choices=USER_GENDER_CHOICES
)
created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True, null=True, blank=True)
class Meta:
db_table = 'profile'
When i am creating Profile from django admin panel getting below error.
e
filename = self.upload_to(instance, filename)
File "/Users/soubhagyapradhan/Desktop/upwork/africa/backend/api/model_utils/utils.py", line 7, in get_upload_path
instance.user,
File "/Users/soubhagyapradhan/Desktop/upwork/africa/backend/env/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 421, in __get__
raise self.RelatedObjectDoesNotExist(
api.models.FullNameMixin.user.RelatedObjectDoesNotExist: Profile has no user.
[24/Jul/2021 13:49:51] "POST /admin/api/profile/add/ HTTP/1.1" 500 199997
please take a look how can i fix this.
Note: User model creation working but, profile not working
I checked in drf and django admin panel .
both place not working.
The problem here is that you are declaring a User model which is in fact just a model. That's not how it works.
The User is a special type of model and if you want to change it you have to extend the AbstractUser class.
Alternatively you can connect to it via one-to-one classes in the classic user-profiles approach.
But here you are creating a user model that (besides using the reserved word 'User') has none of the requirements necessary to be treated as a user who can be authenticated and that can instantiate sessions.
> Example of a simple user-profiles architecture
> Working with User objects - Django Docs (i particularly recommend this one)
I would recommend you to read-up on django user authentication.

How to set queryset or limit or filter in ManytoManyField

Hello all here I am new in Django till now I worked with simple models and generic views.
Now I have two models, Server and InventaryGroups, where InventoryGroups is group of Servers.
class Server(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=20, null=True)
hostname = models.CharField(max_length=50, null=True, blank=True)
ip = models.GenericIPAddressField()
ip2 = models.GenericIPAddressField(null=True, blank=True)
user_name = models.CharField(max_length=20, null=True)
password = models.CharField(max_length=200, null=True, blank=True)
ssh_key = models.FileField(null=True, blank=True)
status = models.CharField(max_length=10, null=True, blank=True)
last_login_time = models.DateTimeField(null=True, blank=True)
last_login_from = models.GenericIPAddressField(null=True, blank=True)
def __str__(self):
return str(self.user) + " - " + self.name
class InventoryGroups(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=20, null=True)
host = models.ManyToManyField(Server)
description = models.CharField(max_length=100, null=True, blank=True)
def get_hosts(self):
if self.host:
hostlist = []
for name in self.host.all():
hostlist.append(name)
return hostlist
def __str__(self):
return str(self.user) + " - " + self.name
What I am trying to do is limit my Server (server list) according to User. Like this:
You can see all servers in hostlist.
But I want to show only those Severs which are added by authenticated users or users selected in InventoryGroups.user

Make a query to django models

How is "translation" for following query to django queryset?
SELECT guid FROM feedme_feeditem
WHERE feed_id IN
(SELECT id FROM feedme_feed WHERE country_id IN
(SELECT id FROM feedme_country WHERE name='NL'))
models.py
class Country(models.Model):
name = models.CharField(max_length=250, blank=True)
class Category(models.Model):
name = models.CharField(max_length=250, blank=True)
slug = models.SlugField(blank=True, null=True, editable=False)
user = models.ForeignKey(User, blank=True, null=True)
country = models.ForeignKey(Country, blank=True, null=True)
class Feed(models.Model):
link = models.CharField(blank=True, max_length=450)
url = models.CharField(blank=True, max_length=450)
title = models.CharField(blank=True, null=True, max_length=250)
category = models.ForeignKey(Category, blank=True, null=True)
user = models.ForeignKey(User, blank=True, null=True)
last_update = models.DateField(blank=True, null=True, editable=False)
country = models.ForeignKey(Country, blank=True, null=True)
class FeedItem(models.Model):
title = models.CharField(max_length=350, blank=True)
link = models.URLField(blank=True)
content = models.TextField(blank=True)
feed = models.ForeignKey(Feed, blank=True, null=True)
read = models.BooleanField(default=False)
guid = models.CharField(max_length=255)
pub_date = models.DateTimeField()
To make more simple I already tried add country = models.ForeignKey(Country, blank=True, null=True) to FeedItem class but does't work how i expected.
guids = FeedItem.objects.filter(feed__country__name = 'NL')

function in models is unrecognizable

I trying extend existed models so I added 'thumbnails' in to it. Unfortunately function related to this is not recognized and django console gives me:
thumbnail = models.ImageField(upload_to=_get_upload_image, blank=True, null=True)
NameError: name '_get_upload_image' is not defined
Could someone help me with this issue?
Django 1.6.5 models.py (short version)
class Feed(models.Model):
link = models.CharField(blank=True, max_length=450)
url = models.CharField(blank=True, max_length=450)
title = models.CharField(blank=True, null=True, max_length=250)
category = models.ForeignKey(Category, blank=True, null=True)
user = models.ForeignKey(User, blank=True, null=True)
last_update = models.DateField(blank=True, null=True, editable=False)
country = models.ForeignKey(Country, blank=True, null=True)
thumbnail = models.ImageField(upload_to=_get_upload_image, blank=True, null=True)
class Meta:
unique_together = (
("url", "user"),
)
def _get_upload_image(instance, filename):
return "images/%s_%S" % (str(time()).replace('.','_'), filename)
I solved this through placing function on top of class
class Feed(models.Model):
def _get_upload_image(instance, filename):
return "images/%s_%S" % (str(time()).replace('.','_'), filename)
link = models.CharField(blank=True, max_length=450)
url = models.CharField(blank=True, max_length=450)
title = models.CharField(blank=True, null=True, max_length=250)
category = models.ForeignKey(Category, blank=True, null=True)
user = models.ForeignKey(User, blank=True, null=True)
last_update = models.DateField(blank=True, null=True, editable=False)
country = models.ForeignKey(Country, blank=True, null=True)
thumbnail = models.ImageField(upload_to=_get_upload_image, blank=True, null=True)

initial data in model field

I have a simple model:
class MediaLink(models.Model):
title = models.CharField(max_length=200)
subtitle = models.TextField(max_length=2000, unique=False, blank=True)
byline = models.CharField(max_length=200, unique=False, blank=True)
url = models.URLField(unique=False)
source = models.CharField(max_length=30, unique=False)
source_url = models.CharField(max_length=30, unique=False, blank=True, null=True, choices=SURL_CHOICES)
mediatype = models.CharField(max_length=30, choices=MEDIATYPE_CHOICES)
topic = models.CharField(max_length=30, choices=TOPIC_CHOICES)
sourceinfo = models.ForeignKey(SourceInfo, blank=True, null=True)
date_added = models.DateField(auto_now_add=True)
def __unicode__(self):
return u'%s' % self.title
class Meta:
abstract = True
class Admin:
pass
I'd like to set the "subtitle" field so that in each object, its initial data is "<h3></h3>". I'm using markdown and having the tags set initially saves me from having to create them in the admin for each record.
You could just set the default on the field:
subtitle = models.TextField(max_length=2000, unique=False, blank=True, default='<h3></h3>')
Or if you're using a ModelForm you can set it in the initial kwarg.