Creating list of photos in Django - django

On the webpage I am currently working on I have to display profiles of different persons. Each person has a profile image that is displayed on the right side. Furthermore, I have the content saved as markdown on the server.
Now I want to add the possibility to add an optional list of images that are displayed under the text and shows something about the person. My model for the person looks like that:
class stipendiat(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
content = models.TextField()
year = models.IntegerField(blank=False, null=False)
form = models.IntegerField(blank=False, null=False)
image = models.ImageField(upload_to='stipendiaten/', blank=True, null=True, default='default.jpg')
gallery = # This is the question
def __unicode__(self):
return self.first_name + " " + self.last_name
Because I want to save some data about the image the model should look like that:
class Image(models.Model):
caption = models.CharField(max_length=512)
year = models.IntegerField()
image = models.ImageField(upload_to=upload_path_handler, blank=False, null=False)
For convenience it should be possible to add an image while editing the form for the person. To be precise, I want to add a person and fill in the necessary information (first_name, last_name, content etc.). At the end should be a list of connected images and a button to add an image rapidly.
Is it necessary to use an external app or is there an elegant solution with relation fields?

Maybe you should use a different model for the gallery images and a foreign key field to link the two models together
class Image(models.Model):
#...
stipendiat = models.ForeignKey(Reporter)
Now you can retrieve the Gallery Images for a stipendiat with id 1 like this
Image.objects.filter(stipentiat__pk=1)

Related

fetch data from pre-existing table and paste it into view of another django model

How can I make real-time changes to my view using the Django model and a pre-existing table?
I have a table of random data of people like this
people table
and I have a model with
class Todo(models.Model):
title = models.CharField(max_length=100)
memo = models.TextField(blank=True)
voyageur = models.PositiveIntegerField(default=1)
# set to current time
created = models.DateTimeField(auto_now_add=True)
completed = models.BooleanField(default=False)
# user who posted this
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
I want the data from the people table to be changed in the memo text fields in real-time as I change the value of voyageur which can be associated with the primary key of "people"
visualize in real-time data as I change the value of voyageur
is this possible?
do I have to pass from a front end app like react to do that?

Django M2M queryset with multiple instances and Q

I have the following models:
class Thematics(models.Model):
title = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return self.title
class Pathology(models.Model):
title = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return self.title
class Organ(models.Model):
title = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return self.title
class Surgerytype(models.Model):
title = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return self.title
class Content(models.Model):
thematics = models.ManyToManyField(Thematics, null=True, blank=True)
pathology = models.ManyToManyField(Pathology, null=True, blank=True)
organs = models.ManyToManyField(Organ, null=True, blank=True)
surgery = models.ManyToManyField(Surgerytype, null=True, blank=True)
I have a lot of Content instances, which themselves have a lot of M2M instances related to them. You can think of Surgerytypes as tags.
I have this query:
content = Content.objects.all()
# surgeries is an array of Surgerytype instances titles
query = content.filter(Q(surgery__title__in=surgeries)
For simplicity I will focus on one M2M model, Surgerytype, and admit that I could replicate then chain the query with the 3 other models.
I create 3 instances of Surgerytype with title: "Diagnosis", "Surgery", "Therapeutic"
I then create 3 instances of Content to which I add these M2M relations with surgery (the M2M to Surgerytype)
Content instance 1 --> add(Diagnosis)
Content instance 2 --> add(Diagnosis, Surgery)
Content instance 3 --> add (Diagnosis, Surgery, Therapeutic)
The whole idea here is to have a dynamic filtering by the client/doctor who can choose tags to get to the type of content he needs.
So if he/she clicks :
on Diagnosis and no other tag, the doctor should see Content instance 1,2 and 3.
on Diagnosis and Surgery or just Surgery, the doctor should see Content instance 2 and 3
on Diagnosis, Surgery, Therapeutic or just Therapeutic, the doctor should see Content instance 3
On Diagnosis and Therapeutic, the doctor should see Content 3
So this is an AND problematic.
When I ajax send to my backend a tag (i.e. a Surgerytype instance title), all good the query returns all the instances of Content that include this tag. Now, the problem is that if I select two tags, the queryset returns nothing instead of all Content instances that include these 2 tags and possibly more tags. I have found on SO how to do this for 1 M2M model in the Content model but it is quite dirty and not scalable at all (there are 3 other M2M/filters to add in the real Content model). Any ideas? Found many questions related to the subject but it doesn't seem to have a definitive, scalable answer. Many thanks to you all

Getting a column instead of an object when relating with PrimaryKeyRelatedField in Django-Rest-Framework

I have a model for applications, which among many attributes have a category. This category is in fact a key to another model that has the category ID, its name, and so on.
class Application(models.Model):
title = models.CharField(max_length=50)
vendor = models.CharField(max_length=50, default="Unknown", null=False)
.
.
.
category = models.ForeignKey('ApplicationCategory', related_name='applications', null=False, default=1, on_delete=models.SET_DEFAULT)
class ApplicationCategory(models.Model):
name = models.CharField(max_length=20, null=False)
description = models.CharField(max_length=200, null=False)
Then, on the Django REST serializers side I have the serializer for the applications:
class SoftwareSerializer(serializers.ModelSerializer):
category = serializers.PrimaryKeyRelatedField(queryset=ApplicationCategory.objects.all())
class Meta:
model = Application
fields = ['id', 'title', ... 'category']
Which is generating the expected API view, with a dropdown for the categories, but showing them as the ApplicationCategory objects and not giving me their name.
API showing Category dropdown with objects instead of names
Is there a way to access attributes of those objects to show the name in the dropdown, for usability sake?
I have also tried creating a CategorySerializer object (class CategorySerializer(serializers.ModelSerializer)) and then using it as category = CategorySerializer(many=False) but instead of dropdowns, I get open text fields for the attributes of the category.
Am I trying to do something that is not expected to work?
try to define the desired text in str method for your ApplicationCategory class:
class ApplicationCategory(models.Model):
name = models.CharField(max_length=20, null=False)
description = models.CharField(max_length=200, null=False)
#example
def __str__(self):
return '%s: %s' % (self.name , self.description)

Post made up of blocks (text, image, video)

I'm trying to create a image site with a similar form for adding posts as on Imgur. A post should be made up of unlimited number of blocks of various types (text, image, video) that create finished blog post.
User chooses with which block he wants to start (maybe upload an image) and then adds another block by clicking a button.
I can't figure out a sensible model for blocks that would make up a single post.
This is my Post model:
class Post(models.Model):
author = models.ForeignKey('auth.User')
text = models.TextField() #just a placeholder until blocks work
created_date = models.DateTimeField(
default=timezone.now)
isWaiting = models.BooleanField(default=True)
isLocked = models.BooleanField(default=False)
views = models.IntegerField(default=0)
tags = TaggableManager(help_text="")
I don't know if I should define separate models for textblock, imageblock and videoblock (all with ForeignKey to Post model) or if there's a better solution.
I thought of a universal model that would store a TextField (for text written by the user) and a FileField (for image and video upload) used for every block type but one of the Fields in every record would always be empty (user can only write text or upload a file per block) and it seems like a "waste of space".
I appreciate any ideas for solving this problem.
If anyone comes across a similar problem I chose a universal content block design with many fields (some are empty depending on a block type, ex. media is empty when adding text block). It was easier for me to implement and later add necessary JS for dynamically adding more PostBlocks to Post.
Relevant models:
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
created_date = models.DateTimeField(default=timezone.now)
views = models.IntegerField(default=0)
tags = TaggableManager(help_text="")
class PostBlock(models.Model):
POST_TYPE_CHOICES = (
('TXT', 'Text'),
('IMG', 'Image'),
('VID', 'Video'),
)
postid = models.ForeignKey('Post', on_delete=models.CASCADE)
text = models.TextField(max_length=1024, blank=True)
media = models.FileField(upload_to=content_path, blank=True, validators=[
validate_file_extension])
contenttype = models.CharField(
max_length=3,
choices=POST_TYPE_CHOICES,
default='IMG',
)
order = models.IntegerField(default=0)
One Post can have as many PostBlocks as you need.

Django CMS Custom plugin - how to handle translations

I have a carousel which consists of a Gallery model that has several Picture models. The Picture model looks like this:
class Picture(models.Model):
gallery = models.ForeignKey(Gallery)
image = models.ImageField(upload_to="uploads/images/")
title = models.CharField(max_length=30, null=True, blank=True)
tagline = models.CharField(max_length=30)
description = models.CharField(max_length=100)
page_link = PageField(related_name="Page", null=True, blank=True)
As the website has 3 languages, how can the admin use the same carousel for all languages, having the same image, but different translatetions for texts?
There has to be a better way than just using title_en, title_de, etc, right?
I would highly recommend django-hvad.
Here's your models.py as an hvad TranslatableModel:
class Picture(TranslatableModel):
translations = TranslatedFields(
title = models.CharField(max_length=30, null=True, blank=True)
tagline = models.CharField(max_length=30)
description = models.CharField(max_length=100)
)
gallery = models.ForeignKey(Gallery)
image = models.ImageField(upload_to="uploads/images/")
page_link = PageField(related_name="Page", null=True, blank=True)
def __unicode__(self):
return self.lazy_translation_getter('title', self.pk)
As mentioned in the docs, this app is still in Beta but I've used it in many production environments and works good.
One thing to keep in mind is that it does bring a few limitations.
The way it works is it creates a model called PictureTranslation (or something like that) which will have your three fields title, tagline, description and a ForeignKey to Picture.
You can still do picture_instance.title as long as the picture_instance is language aware.
If you would like, I can give a better explanation based on your specific use case.