I have an Artwork and ArtworkPhoto models in Django.
ArtworkPhoto has an FK to the Artwork and stores some additional data on the photo.
class ArtworkPhoto(models.Model):
title = models.CharField(max_length=200, verbose_name='Omschrijving', blank=True)
photo = FileBrowseField("Image", max_length=200, directory="artwork/",
extensions=[".jpg", ".png"], blank=False, null=False)
artwork = models.ForeignKey(Artwork, null=False, verbose_name='kunstwerk')
Every Artwork has X photos, all working fine.
Now I want to provide authenticated visitors with an upload form to add an artwork and photo's.
How can I save a posted file to the ArtworkPhotoModel? It's a Grapelli FileBrowser > Filebrowsefield ...
Thanks, i'm a bit stuck here. ...
Related
I have created a model as below.
class UserPost(models.Model):
author = models.ForeignKey(User, related_name='userpost', null=True, on_delete=models.CASCADE)
post_date = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=150, blank=False)
post_body = models.TextField(blank=True, null=True, default='text')
image = models.ImageField(upload_to='post_pics', blank=True)
likes = models.ManyToManyField(User, blank=True, related_name='post_likes')
I am not populating likes field anywhere, my admin screenshot is below.Why my likes field is getting populated with all the users created?
admin screenshot
admin.py
from django.contrib import admin
from feed.models import UserPost
# Register your models here.
admin.site.register(UserPost)
Edit 1:
Adding a screenshot for Rishabh's answer.
trying to add user from left as suggested by him
You are using ManyToManyField of Django which will show you all records of User table left side and you can add them by double clicking on them or by clicking '+' sign, so your likes field is not prepopulated at all it is just showing User table data.
I have a Post model which has a ImageField.
class Post(models.Model):
headline = models.CharField(max_length=255)
lead = models.TextField(blank=True, null=True)
body = models.TextField(blank=True, null=True)
image = models.ImageField(upload_to="posts", blank=True, null=True, max_length=255)
In my ModelForm, the file input for the image works perfectly, but I was wondering how to let the user choose between uploading a new image, or selecting one from all the images that have been previously uploaded to the site.
Any pointers?
In order to do that define another model Image and then create a foreign key from Post to Image. When creating a new post, you can either select an existing image or upload a new one and then select it.
I have a model to upload pictures:
class Snap(models.Model):
image = models.ImageField(upload_to=get_upload_file_name)
caption = models.CharField(max_length=150, blank=True, null=True)
pubdate = models.DateTimeField(default=timezone.now)
In the admin it contains all the Snap's field (i.e. one field to upload an image ,its caption and the pubdate) which is as expected. How do I add multiple record of Snap's in one go. I hope I was clear, if not please ask. Your help and guidance will be very much appreciated. Thank you.
admin.py:
class SnapAdmin(admin.ModelAdmin):
class Meta:
model = Snap
admin.site.register(Snap, SnapAdmin)
I have a fairly simple Django set up for a forum, and one of the most basic models is this, for each thread:
class Post(models.Model):
created = models.DateTimeField(auto_now_add=True)
last_reply = models.DateTimeField(auto_now_add=True, blank=True, null=True)
username = models.ForeignKey(User, related_name="forumuser")
fixed = models.BooleanField(_("Sticky"), default=False)
closed = models.BooleanField(default=False)
markdown_enabled = models.BooleanField(default=False)
reply_count = models.IntegerField(default=0)
title = models.CharField(_("Title Post"), max_length=255)
content = models.TextField(_("Content"), blank=False)
rating = models.IntegerField(default=0)
followers = models.IntegerField(default=0)
ip_address = models.CharField(max_length=255)
def __unicode__(self):
return self.title
def get_absolute_url(self):
return "/post/%s/" % self.id
Then we have some replies:
class PostReply(models.Model):
user = models.ForeignKey(User, related_name='replyuser')
post = models.ForeignKey(Post, related_name='replypost')
created = models.DateTimeField(auto_now_add=True)
content = models.TextField()
ip_address = models.CharField(max_length=255)
quoted_post = models.ForeignKey('self', related_name='quotedreply', blank=True, null=True)
rating = models.IntegerField(default=0)
reply_order = models.IntegerField(default=1)
Now, currently there just over 1600 users, 6000 Posts, and 330,000 PostReply objects in the db for this setup. When I run this SQL query:
SELECT * FROM `forum_post` LIMIT 10000
I see that Query took 0.0241 sec which is fine. When I browse to the Django admin section of my site, pulling up an individual Post is rapid, as is the paginated list of Posts.
However, if I try and pull up an individual PostReply, it takes around 2-3 minutes to load.
Obviously each PostReply admin page will have a dropdown list of all the Posts in it, but can anyone tell me why this or anything else would cause such a dramatically slow query? It's worth noting that the forum itself is pretty fast.
Also, if it is something to do with that dropdown list, has anyone got any suggestions for making that more usable?
Try to add all foreign keys in raw_id_fields in admin
class PostReplyAdmin(ModelAdmin):
raw_id_fields = ['user', 'post', 'quoted_post']
This will decrease page's load time in change view. The problem is that django loads ForeignModel.objects.all() for each foreign key's dropdowns.
Another way is to add foreign keys in autocomplete_fields (docs) in admin
class PostReplyAdmin(ModelAdmin):
autocomplete_fields = ['user', 'post', 'quoted_post']
As pointed by #Andrey Nelubin the problem for me was indeed in the page loading all related models for each foreign key's dropdown. However, with autocomplete_fields selects are turned into autocomplete inputs (see figure below), which load options asynchronously.
class Product(models.Model):
...
image = models.ImageField(upload_to=generate_filename, blank=True)
When I use ImageField(blank=True) and do not select image into admin form, an exception occurs.
In django code you can see this:
class FieldFile(File):
....
def _require_file(self):
if not self:
raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
def _get_file(self):
self._require_file()
...
Django trac has ticket #13327 about this problem, but seems it can't be fixed soon. How to make these field optional?
blank=True should work. If this attribute, which is False by default, is set to True then it will allow entry of an empty value.
I have the following class in my article app:
class Photo(models.Model):
imagename = models.TextField()
articleimage = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True)
I make use of the above class in another class by using the ManyToManyField relationship:
class Article(models.Model):
pub_date = models.DateTimeField(default=timezone.now)
slug = models.SlugField(max_length=130)
title = models.TextField()
photo = models.ManyToManyField(
Photo, related_name='photos', blank=True)
author = models.ForeignKey(User)
body = models.TextField()
categories = models.ManyToManyField(
Category, related_name='articles', null=True)
I want to make images in my articles optional, so blank=True in
photo = models.ManyToManyField(Photo, related_name='photos', blank=True)
is necessary. This allows me to create an article without any images if I want to.
Are you using class Product in any relationship? If so, make sure to set blank=True in the relationship you are using.
Set null=True (see documentation)
class Product(models.Model):
...
image = models.ImageField(upload_to=generate_filename, blank=True, null=True)
If 'optional' means that you want to be able to disregard the image field altogether. Then blank=True, so do the trick. However, if you are still getting the same error, then this means that you are using it's url either in the template somewhere or you are trying to open the path of the image in models.py or views.py ( may be to resize the image or some other backend preprocessing).
That is why it is always suggested to use try - catch block while handling files.