Problem when deleting ImageField from database - python

models.py:
Picture = models.ImageField('Picture', null=True, blank=True)
When I give the command
person.Picture.delete()
the picture is deleted from the directory, but in the database still has the record of the file path in Picture as shown in image below. How can I delete it?

Set the field to None as well, so:
person.Picture.delete()
person.Picture = None
person.save()
Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase, so it should be: picture instead of Picture.

You need to try
person = Person.objects.get(User=User_)
person.Picture.delete(save=False)
...
person.save()
Try setting the path in your model something like below
Picture = models.ImageField(upload_to='Picture', null=True, blank=True)

Related

Unable to delete object from Django admin panel with MongoDB

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)

how to create Django preferences (Site dashboard)

Hi I have ready Django project and I want to create a control panel for it, for example I want to add a field with the name of the site, a field with a description of the site, and a field with the logo of the site, and I call them in the templates instead of changing them manually through the editor every time.
I upload the website logo to the static file and want to add an option to change it from the control panel instead of manually replacing it from the server.
I have attached an illustration of what I want to reach.
Thank you
I searched and did not find a solution for this, but I want to share the solution that I adopted myself
I created a new application called Settings and through it I created a modle for each setting I wanted.
UPDATED
I create new model:
from django.db import models
from django.utils.translation import gettext_lazy as _
class Option(models.Model):
key = models.CharField(max_length=50, verbose_name=_('Key'), null=True, blank=True, unique=True)
value = models.CharField(max_length=50, verbose_name=_('Value'), null=True, blank=True)
def __str__(self):
return self.key
Thus, you can use the values stored in the database:
#register.simple_tag
def get_option(key, default):
op = Option.objects.filter(key=key).first()
if op and op.value != '':
option = op.value
else:
option = default
return option

Django - Upload Image with the current user (Loggedin)

How do I save an Image in a specific folder, depending of whom is Loggedin?
My program creates a folder for every user that registers
after they login, they are able to upload some images.
The problem is when I try to save my image, I need to specify the path where is going to be Uploaded (with the userID)
Example:
If Bob is Loggedin, you will upload the images here: space/users/bob123/example.png
Model
class StudentPhotos(models.Model):
image = models.ImageField(upload_to= ??? , default="", null=True)
image_id = models.CharField(max_length = 15, null=False, editable=False, default=id_generator, primary_key=True)
user_id = models.CharField(max_length = 15, null=False, default="")
The main reason to save it that way is to be able to bring in my admin site all images from an user
Lets say you have your model like as follows(Demonstration only):
class StudentPhotos(models.Model):
image = models.ImageField(upload_to=name)
user = models.ForeignKey(User)
Here name (upload_to=name) can be function as follows:
def name(instance, fname):
return '/'.join(instance.user.get_full_name(), fname)
I personally make use of easy-thumbnails for the purpose of having image fields in my models and I am able to use name function in the way I have given above.
Hope, you can infer some relative information and be able to come up with a better solution for your needs.

Django admin List Display + ForeignKey = Empty Change List

I've got a weird problem in django admin list_display. Whenever I add a foreign key to a list_display the whole change list view goes blank showing only the total no of entries.
models.py:
class Organization(models.Model):
org_id = models.AutoField(primary_key=True)
org_name = models.CharField(max_length=288)
def __unicode__(self):
return self.org_name
class Meta:
db_table = u'organization'
class Server(models.Model):
server_id = models.AutoField(primary_key=True)
server_name = models.CharField(max_length=135,verbose_name="Server Name")
org = models.ForeignKey(Organization,verbose_name="Organization")
def __unicode__(self):
return self.server_name
class Meta:
db_table = u'server'
admin.py:
class ServerAdmin(admin.ModelAdmin):
list_display = ('server_name','org')
admin.site.register(Server,ServerAdmin)
Now I'd expect this code to show me the organization name in the ChangeList View, But instead I get this:
If I remove the org in the list_display of ServerAdmin class, I get this:
I didn't modify the template or override any ModelAdmin methods. I'm using Mysql(5.1.58) as my database that comes with ubuntu 11.10 repository.
I'll be really glad if I could a get a sloution for this problem guys. Thanks in advance.
I second Stefano on the fact that null=True, blank=True is to be added. But, I think you only need to add it to the org_name field of the Organization model. That should make your way through. It has to be done because you have run inspectdb to create models from your legacy DB. And probably the organization table in the DB has an empty string stored. So, adding the above would allow the Admin to have a blank field/column displayed.
Moreover, you can also try using callbacks in situations where you don't want to make changes to your model definition like the above.
Try adding null=True, blank=True to all your model fields.
Usually django admin will silenty fail (thus show no records in the list) if the row does not validate the model constraints.
See: https://stackoverflow.com/a/163968/1104941
Does the following work for you?
admin.py:
class ServerAdmin(admin.ModelAdmin):
list_display = ('server_name','org__org_name')
admin.site.register(Server,ServerAdmin)
I had a similar problem and solved it like this (using your example):
class ServerAdmin(admin.ModelAdmin):
list_display = ('server_name', 'get_org')
def get_org(self, obj):
return obj.org.org_name
get_org.short_description = 'Org'
admin.site.register(Server,ServerAdmin)

Django import problem with models.py and multiple ManyToManyFields()

I am working on creating a simple contest submission system using django. This is my first real django project. Basically each user can view a list of problems, submit a file, and view a results page.
Each problem can be associated with multiple contests, and different contests can use the same problem. Because of this, both problem and contest have a manyToManyField with each other. This is what is causing my problem.
Here is the initial models.py implementation I am going with:
startfile
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50)
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
class Problem(models.Model):
name = models.CharField(max_length=50)
filename = models.CharField(max_length=300)
contests = models.ManyToManyField(Contest)
class Contest(models.Model):
name = models.CharField(max_length=50)
problems = models.ManyToManyField(Problem)
date = models.DateField()
class Submission(models.Model):
user = models.ForeignKey(User)
problem = models.ForeignKey(Problem)
filename = models.CharField(max_length=300)
endfile
Is there a simple way to fix this? Or should I rethink my entire layout? I tried breaking each class into its own django app but I don't think thats how I should do it. The error I get is that Contest can not be found (because it exists lower in the file).
All advice is appreciated!
You don't need a ManyToManyField in both Contest and Problem. Many-to-many fields are already bidirectional. Just put it on one - doesn't matter which.
Djano will automatically create the reverse relation for you, so you only need to create it one end, eg.
class Problem(models.Model):
name = models.CharField(max_length=50)
filename = models.CharField(max_length=300)
contests = models.ManyToManyField(Contest, related_name='problems')
related_name gives you the possibility to assign a name to the reverse relation. Without defining the relation on the Contest model, you can then access eg. a_contest.problems.all()!

Categories

Resources