I'm working on a project in django, I need to duplicate a picture stored in one model and save it with a different name into another one, I've tried many of the responses I've found but nothing seems to work.
This last try doesn't give me an error but is not duplicating the image, nor storing a copy with the name. I'm running Pillow and Django 3.X
models.py:
class Visualization(models.Model):
kind = models.CharField(max_length=90)
description = models.CharField(max_length=90)
image = models.ImageField(upload_to='visualization', null=True,
blank=True)
class Order(models.Model):
visualization = models.ForeignKey(Visualization,
on_delete=models.CASCADE)
hashed = models.ImageField(upload_to='hashedimages', null=True,
blank=True)
def save(self):
super().save()
self.hashed = self.visualization.image
self.hashed.name = 'randomothername.jpg''
self.hashed.save()
Related
I have a Django project using a MongoDB connected by Djongo. I created a simple model which looks like:
from django.db import models
# Create your models here.
class Property(models.Model):
name = models.CharField(max_length=128, blank=False)
property_type = models.CharField(max_length=24, blank=True)
include_on = models.CharField(max_length=256, blank=True)
format_example = models.TextField(blank=True)
notes = models.TextField(blank=True)
After registering the model by using the line admin.site.register(Property) in the admin.py file I end up seeing my model appear. After adding a test Property I see the line
The property “Property object (61226db9f4f416b206c706e5)” was added successfully.
Which tells me the item was added. It also appears on the admin panel but it looks like:
Property object (None)
If I select the property I get an error that says:
Property with ID “None” doesn’t exist. Perhaps it was deleted?
If I try to delete the property I get a ValueError with error of:
Field 'id' expected a number but got 'None'.
Since I am currently learning Django/MongoDB I actually ran across the ValueError once before. The fix was to delete the entire database and start over. The issue is I don't want to run into this in the future and want to know what I have to do to fix it, or correct what I am doing wrong.
I found my answer. Turns out I need to assign a primary key. I fixed this by changing my model to..
class Property(models.Model):
name = models.CharField(primary_key=True, max_length=128, blank=False)
property_type = models.CharField(max_length=24, blank=True)
include_on = models.CharField(max_length=256, blank=True)
format_example = models.TextField(blank=True)
notes = models.TextField(blank=True)
I created an app with django and python3 containing several tutorials, which in turn contain multiple content entrys that are saved in another table. Each tutorial is represented by an entry in the exercises tutorial model. I want to be able to sort the tutorials and the contents in the django admin panel. It works fine for the inline tutorial contents with SortableInlineAdminMixin class. It also works fine if I create new tutorials from scratch without having any objects saved before (it works local on my pc if I clone this project and set it up from scratch)
My problem now is, that I have the app setup like you see in the code and pictures below on a ubuntu server with apache, but I can't sort the tutorials (the inline contents still work fine). If i drag and drop them to a new position and reload, they don't save at their new position and fall back to their old position.
Tutorial and TutorialContent model:
from django.db import models
from ckeditor_uploader.fields import RichTextUploadingField
# Page for tutorials
class Tutorial(models.Model):
title = models.CharField(max_length=60)
order = models.PositiveIntegerField(default=0, null=False, unique=True)
# Timestamp
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['order']
def __str__(self):
return self.title
# Content for tutorials
class TutorialContent(models.Model):
lesson_page = models.ForeignKey(Tutorial, related_name='tutorial_content', on_delete=models.CASCADE)
content = RichTextUploadingField()
order = models.PositiveIntegerField(default=0, null=False)
# Timestamp
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['order']
def __str__(self):
description = 'Order - ' + str(self.order)
return description
Tutorial and TutorialContent admin:
from django.contrib import admin
from .models import Tutorial, TutorialContent
from adminsortable2.admin import SortableInlineAdminMixin, SortableAdminMixin
class TutorialContentInline(SortableInlineAdminMixin, admin.TabularInline):
model = TutorialContent
class TutorialAdmin(SortableAdminMixin, admin.ModelAdmin):
model = Tutorial
inlines = [TutorialContentInline]
list_display = ['title']
admin.site.register(Tutorial, TutorialAdmin)
Django admin tutorial model panel:
SQLite3 view of the corresponding table:
Maybe a little to late, but:
If there is already some model instance persisted in your db when you add the adminsortable2 field in your model, the ordering will not works, you need to build the order a first time with:
python manage.py reorder your_app.YourModel
Source: https://django-admin-sortable2.readthedocs.io/en/latest/usage.html#initial-data
Hoping this can help.
I am having a bit of trouble with the logic of how this should work so I am hoping it is possible.
I figured out 1 possible solution that is written as an answer below, I will accept it in a few days, but if someone comes up with a better solution, I will negate any answer I post.
Overall I am working on an Apartment Move-Out/Move-In Inspection Application in Django, and in both portions I have universal Locations that must be inspected for each report. I have allowed the InspectionLocations objects to be updated/submitted by clients, which is presenting an issue in how submitted reports should be stored in my Database.
What I want is to use the InspectionLocations table as a blueprint to build an Inspection Report for Move-Ins where the form-fields are generated based on the InspectionLocations objects' location, status, and information attributes/fields.
My issue is right at this point, how do I reference those values as a blueprint to build a report submission when the number of fields in the InspectionLocations can change?
from django.db import models
from apps.units.models import Unit
class Inspections(models.Model):
class Meta:
abstract = True
id = models.AutoField(primary_key=True)
inspection_date = models.DateField()
submitted_by = models.ForeignKey(
'users.CustomUser',
default=None,
null=True,
on_delete=models.SET_NULL,
db_column='submitted_by')
last_update = models.DateTimeField(auto_now=True)
date_added = models.DateTimeField(auto_now_add=True, editable=False)
class MoveInInspections(Inspections):
unit = models.ForeignKey(Unit, on_delete=models.CASCADE, db_column='unit_id')
# should have reference to all InspectionLocation items as reference for submission, how?
class MoveOutInspections(Inspections):
unit = models.ForeignKey(Unit, on_delete=models.CASCADE, db_column='unit_id')
date_notice_given = models.DateField(blank=True, null=True, default=None)
date_vacated = models.DateField(blank=True, null=True, default=None)
# should have reference to all InspectionLocation items as reference for submission, how?
class InspectionLocations(models.Model):
'''
Defualt Inspection Locations are created when a
client is created using code like this:
InspectionLocation.objects.get_or_create(location='Living Room')
InspectionLocation.objects.get_or_create(location='Dining Room')
InspectionLocation.objects.get_or_create(location='Kitchen')
InspectionLocation.objects.get_or_create(location='Bedroom')
InspectionLocation.objects.get_or_create(location='Bathroom')
InspectionLocation.objects.get_or_create(location='Other')
'''
id = models.AutoField(primary_key=True)
location = models.CharField(max_length=50)
status = models.BooleanField(default=None)
information = models.TextField(default=None, blank=True)
I have tried ManyToMany fields and FKs but I cannot seem to get the logic working as anytime an object references an InspectionLocations object it is universally changing data for every report, which is leading be to the idea that I somehow need to use it as a blueprint.
I didn't post this in my question because it was getting long, but my best option so far seems to be to use a Django JSONField (as I am using Postgres), like so:
from django.contrib.postgres.fields import JSONField
class MoveInInspections(Inspections):
unit = models.ForeignKey(Unit, on_delete=models.CASCADE, db_column='unit_id')
data = JSONField()
class MoveOutInspections(Inspections):
unit = models.ForeignKey(Unit, on_delete=models.CASCADE, db_column='unit_id')
date_notice_given = models.DateField(blank=True, null=True, default=None)
date_vacated = models.DateField(blank=True, null=True, default=None)
data = JSONField()
To where I store the values of the InspectionLocations object's in a Dictionary
I’m using Django and I'm having a problem with a Python script that uses Django models
The script that I'm using takes data from an api and loads it into my database.
my model:
class Movie(models.Model):
title = models.CharField(max_length=511)
tmdb_id = models.IntegerField(null=True, blank=True)
release = models.DateField(null=True, blank=True)
poster = models.TextField(max_length=500, null=True)
runtime = models.IntegerField(null=True, blank=True)
description = models.TextField(null=True, blank=True)
edit = models.DateTimeField(auto_now=True, null=True, blank=True)
backdrop = models.TextField(max_length=500, null=True, blank=True)
popularity = models.TextField(null=True, blank=True)
the script:
movies = tmdb.Movies().upcoming()
results = movies['results']
ids = []
for movie in results:
data, created = Movie.objects.get_or_create(title=movie['title'],
tmdb_id=movie['id'],
release=movie['release_date'],
description=movie['overview'],
backdrop=movie['backdrop_path'],
poster=movie['poster_path'],
popularity=movie['popularity'])
The problem I'm having is that whenever I run the script, the entries are duplicated because the edit field is change, but the purpose I put the edit field is to know when exactly a movie got edited, ie: some other field got changed.
How can I avoid the duplicates, but also keep the edit field in case some real change happened?
but the purpose I put the edit field is to know when exactly a movie
got edited, ie: some other field got changed.
That probably means you are using the wrong function. You should be using update_or_create istead.
A convenience method for updating an object with the given kwargs,
creating a new one if necessary. The defaults is a dictionary of
(field, value) pairs used to update the object.
This is different from get_or_create, which creates an object if it does not exists, or simply fetches it when it does exist. update_or_create is the one that does the actually updating.
However, changing to this method doesn't solve this:
How can I avoid the duplicates, but also keep the edit field in case
some real change happened?
Duplicates are created because you do not have a unique index on any of your fields. Both get_or_create and update_or_create require that you have a unique field. It seems that the following change is in order:
class Movie(models.Model):
title = models.CharField(max_length=511)
tmdb_id = models.IntegerField(unique=True)
I am performing a data migration, moving images from inside one model out to their own model.
class OldCrappyModel(models.Model):
...
original_image = models.ImageField(upload_to=upload_original_image, null=True, blank=True)
my_events_image = models.ImageField(upload_to=upload_my_promotions_image, null=True, blank=True)
...
class MyImage(models.Model):
original_image = models.ImageField(upload_to=upload_original_image, null=True, blank=True)
my_events_image = models.ImageField(upload_to=upload_my_promotions_image, null=True, blank=True)
...
The upload_to methods just return a unique name for the file.
When I go to migrate them (in a South datamigration):
i = MyImage(
my_events_image = old.my_events_image,
original_image = old.original_image,
)
i.save()
The problem is, we have some images that are not in the same place as the new ones. When the copy happens, it translates the url from the old ImageField into a url that would work for the new one. For example:
old.url comes out to path/to/something/awesome.jpg
i.url becomes new/media/root/awesome.jpg
How can I preserve the ImageField without anything happening to it when it saves? I'd like to avoid having to make new copies of all the files if possible.
Disable upload_to for the duration of the migration. Set the upload_to manually while copying instances.
After the migration, enable it back.