How to inspect two tables at the same time in wagtail modeladmin? - wagtail

In my question, there are two related models:
class Simulation(index.Indexed, ClusterableModel):
name = models.CharField("算例名称", max_length=255, blank=True) name = models.CharField("算例名称", max_length=255, blank=True)
panels = [
MultiFieldPanel([
FieldPanel('name', classname="col10"),
MultiFieldPanel([InlinePanel('simulation',label='simulation_software'),]),
], "算例")
]
class SimulationSoftware(index.Indexed, ClusterableModel):
simulation = ParentalKey(Simulation, related_name='simulation', on_delete=models.CASCADE)
software = models.ForeignKey(DicSoftware, verbose_name="模拟软件", help_text="/admin/home/dicsoftware/", on_delete=models.CASCADE, blank=True, null=True, related_name='+')
scale = models.IntegerField("规模", blank=True);
panels = [
MultiFieldPanel([
FieldPanel('simulation', classname="col12"),
FieldPanel('software', classname="col12"),
FieldPanel('scale', classname="col12"),
], "算例输入")
]
I use modeladmin to manage the data in these two tables. When I inspect one Simulation instance, I can not inspect the SimulationSoftware related to it.
How can I inspect two table data at the same time?
Wish for your help.

Related

can't get django views to filter objects by category (foreignkey attribute)

So, I have this class and would like to filter the list of quizzes according to categories (which is a foreignkey). I would like for the view to only display quizzes for each of the categories separately such as 'History', 'Chemistry' and so on.
class QuizListView(generic.ListView):
#model = Quiz
queryset = Quiz.objects.filter(Category='History')
Models:
class Quiz(models.Model):
title = models.CharField(
verbose_name=_("Titulli"),
max_length=60, blank=False)
description = models.TextField(
verbose_name=_("Përshkrimi"),
blank=True, help_text=_("a description of the quiz"))
url = models.SlugField(
max_length=60, blank=False,
help_text=_("a user friendly url"),
verbose_name=_("user friendly url"))
category = models.ForeignKey(
Category, null=True, blank=True,
verbose_name=_("Kategoria"), on_delete=models.CASCADE)
the category class:
class Category(models.Model):
category = models.CharField(
verbose_name=_("Category"),
max_length=250, blank=True,
unique=True, null=True)
objects = CategoryManager()
class Meta:
verbose_name = _("Kategori")
verbose_name_plural = _("Kategoritë")
def __str__(self):
return self.category
THis is the error on the terminal:
Cannot resolve keyword 'quiz_category' into field. Choices are: answers_at_end, categor
y, category_id, data_postimit, description, draft, exam_paper, fail_text, id, max_questions, pass_mark, question, random_o
rder, single_attempt, sitting, success_text, title, url
tried other ways but can't seem to figure it out, any help highly appreciated
category refers to a Category object, if you want to filter on the value of the category field of the related category object, you use double underscores (__), so:
class QuizListView(generic.ListView):
model = Quiz
queryset = Quiz.objects.filter(category__category='History')

React / DRF: How to handle Many to Many relationship in POST request?

How do I make sure that Many-To-Many relationships are considered in my POST-request to a Django Rest Framework API?
I have the following models:
models.py
class Tag(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.name
class Blog(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
tags = models.ManyToManyField(Tag, blank=True, related_name="blogs")
url = models.URLField(max_length=250, unique=True)
owner = models.ForeignKey(User, related_name="blogs", on_delete=models.CASCADE)
slug = models.CharField(max_length=20, default="blogs")
def __str__(self):
return self.name
And I am making the request like:
Frontend (don't mind the missing brackets)
const addContent = (content) => {
axiosInstance
.post(`/content/blogs/`, content, tokenConfig(auth.token))
.then((res) => {
dispatchMessages(
createMessage({ contentAdded: "Submitted successfully" })
);
The content object I am passing in looks like:
const content = {
name: "content title",
description: "content description",
url: "content URL",
tags: ["tag1", "tag2", "tag3"],
};
The POST request itself is going through and all the fields are posted correctly except for the tags, which appear empty.
Example Response:
{
"id": 2,
"tags": [],
"name": "Blog #1",
"description": "Its the best",
"url": "https://website.com",
},
My serializer looks like:
serializers.py
class BlogSerializer(serializers.ModelSerializer):
tags = serializers.SlugRelatedField(many=True, read_only=True, slug_field="name")
owner = CustomOwnerField(read_only=True)
class Meta:
model = Blog
fields = "__all__"
And the viewset:
api.py
class BlogViewSet(viewsets.ModelViewSet):
permission_classes = [
permissions.IsAuthenticatedOrReadOnly
]
serializer_class = BlogSerializer
def get_queryset(self):
return Blog.objects.all()
Thank you for any tips
you have done all the tedious work. The only thing that is not allowing the tags to get saved is the read_only=True in the SlugRelatedField argument. This argument ignores the field when it is posted. So you have to remove read_only=True so that tags get parsed. I would go a little further and add queryset in the slugrelatedfield as queryset=Tags.objects.all()
This would only work if you have already created tags in your db and then you add the same names in your list. If you want to create them dynamically when you post them you have to modify the default create method in your serializer(check here)

ImageChooserPanel wrongfully showing as Select widget

I find stack overflow very difficult to use and I am probably going to be slammed for trying but here goes.
I am trying to get an image field to bring up the standard wagtail image chooser dialog but it's displaying in wagtail admin as a Select widget with no option to upload new image.
from django.db import models
from modelcluster.fields import ParentalKey
from wagtail.core.models import Page, Orderable
from modelcluster.models import ClusterableModel
from wagtail.admin.edit_handlers import (
FieldPanel,
MultiFieldPanel,
InlinePanel,
PageChooserPanel,
)
from wagtail.images.edit_handlers import ImageChooserPanel
class HomePage(Page):
def get_context(self, request):
context = super().get_context(request)
# Add extra variables and return the updated context
context['sections'] = Sections.objects.all()
return context
class Sections(ClusterableModel):
title = models.CharField(max_length = 60, blank = False, null= True)
section_image = models.ForeignKey(
"wagtailimages.Image",
null=True,
blank=False,
on_delete=models.SET_NULL,
related_name="+",
)
panels = [
FieldPanel("title"),
ImageChooserPanel("section_image"),
InlinePanel("albums"),
]
class Albums(ClusterableModel):
title = models.CharField(max_length = 60, blank = False, null= True)
section = ParentalKey("Sections", related_name="albums")
panels = [
FieldPanel("title"),
InlinePanel("images"),
]
class GalleryImage(Orderable):
album = ParentalKey("Albums", related_name="images")
galleryimage = models.ForeignKey(
"wagtailimages.Image",
null=True,
blank=False,
on_delete=models.SET_NULL,
related_name="+",
)
panels = [
ImageChooserPanel("galleryimage"),
]
This is probably a rookie mistake and would appreciate if someone can show me why gallery image is not rendering correctly.
Unfortunately this is an open bug in Wagtail: https://github.com/wagtail/wagtail/issues/5126
Historically, nesting InlinePanels has not been well-supported in Wagtail - there are some improvements in progress which will hopefully make it into the forthcoming 2.7 release, but this particular issue is still outstanding.

How to add list filter and search field in Wagtail default admin Page

Is there any way to put a search field and list filters in a Page-derived model, without customize a ModelAdmin? I would like to use the default admin page for Page-derived model.
models.py
class FolderPage(Page):
body = StreamField([
('paragraph', blocks.RichTextBlock()),
('embedded_video', EmbedBlock(icon='media')),
('table', TableBlock()),
], null=True, blank=True, verbose_name=u'Corpo da Notícia')
search_fields = Page.search_fields + [
index.SearchField('body'),
index.SearchField('title'),
index.FilterField('live'),
]
Currently it is a feature in development, you cand see here in order to get a direction about that.

Django CreateAPIView not saving image portion of django model

I am trying to make a django rest api which allows admin users to add images which the api clients can sync and display. My view responsible for creating the Clothing model, which holds a title and an image, is not working as it only saves the title but not the image.
Here is the Clothing model:
class Clothing(models.Model):
title = models.CharField(max_length=50, blank=False)
img = models.ImageField(blank=True, null=True, upload_to='catalog/')
Here is the view:
class AddClothingView(CreateAPIView):
queryset = Clothing.objects.all()
serializer_class = ClothingSerializer
And here is the serializer:
class ClothingSerializer(ModelSerializer):
class Meta:
model = Clothing
fields = '__all__'
How can I fix this such that the images are saved in the catalog/ folder in my project?

Resources