Dynamic queryset for foreignKey in Single Page Application with Django - angularjs

I have a single page application with AngularJs and Django. On my main page, I get all the forms needed when loading the page. BUT, some fields are dynamically updated.
Let's say I have
class Model1(models.Model):
pass
class Model2(models.Model):
model_1 = models.ForeignKey(Model1)
forms:
class Model2Form(forms.ModelForm):
class Meta:
model = Model2
fields = ('model_1', )
My SPA allows me to create instances of Model1 (without reloading the page). I know how to filter the options shown and dynamically add the new instances in the select field BUT, doing so, when the html is first rendered, before angular magic takes place and filter the available options, I get the queryset made by django which is by default model.objects.all(). All right, I'd like to display none of that. I tried to add in the init of my function:
self.fields['model_1'].queryset = Model1.objects.none()
and indeed no option is displayed in the select field when the form is first rendered but then, I can't validate my form, I get the error: Select a valid choice. That choice is not one of the available choices. (obviously, it had no option available due to the queryset.none() )
I'd really like not to load forms when called but doing it when my page first load. Is there any option to help me do so?
Cheers guyz,
Keep rocking

You need to specify that the model_1 field of Model2 can be null, as specified here:
Allow null in foreign key to user. Django
model_1 = models.ForeignKey(Model1, null=True, blank=True, default = None)

I find out how to handle that problem. It is quite stupid, I did not give you all the parameters of the problem.
The forms are rendered on load but when I validate it, it goes through a CRUD operation and an OTHER form is initialized at this point which will handle the data I'm sending. So I can override the queryset in the init of that (second) form based on some extra kwargs to differentiate between the form I'm using for the first rendering and the form to handle my data.
No need to make any field nullable or add extra validation.
Hope I'm clear enough. Cheers

Related

Is there a way to show images in a Wagtail Model Admin Record Listing page?

I have reviewed the question on Is there any way to show a field on a listing page in Wagtail admin? but my situation seems to similar but also different enough that that particular solution won't work for me. Instead of on the Page listing I wish to achieve a similar thing on the Model Admin listing and I would think this should be such a common requirement that I am picking that someone must have done this before I have attempted it.
I haven't really figured out how to even try anything to get started but what I have looked at is the modeladmin template tags under wagtail.contrib.modeladmin on GitHub but I am completely guessing.
Can anyone point me to which templates I need to modify and whether I need to modify any of the template tags and how to override anything I need to override?
There's no need to override templates for this - this is standard functionality in ModelAdmin. Adding extra fields to the listing is done by setting list_display on the ModelAdmin class:
class BookAdmin(ModelAdmin):
model = Book
list_display = ('title', 'author')
For displaying images, ModelAdmin provides ThumbnailMixin:
from wagtail.contrib.modeladmin.mixins import ThumbnailMixin
from wagtail.contrib.modeladmin.options import ModelAdmin
class BookAdmin(ThumbnailMixin, ModelAdmin):
model = Book
thumb_image_field_name = 'cover_image'
list_display = ('title', 'author', 'admin_thumb')
('admin_thumb' is a special-purpose field name provided by ThumbnailMixin, and should be used rather than the actual image field on your model - cover_image in this example.)

How can the category and product fields in Shopizer be customized, if possible at all?

I am currently using Shopizer as a sort of headless CMS, leveraging its out of the box admin pages and REST API for the content. There is a page for editing products in the admin system but I would like to add and/or remove specific fields. Making changes to the base code seems to be the most obvious solution but it is taking me a significant amount of time to implement it successfully.
Is there some sort of a config file or an initialization process to customize the fields for creating categories and products using Shopizer's admin page? What is the best practice for this scenario if the former approach is not possible?
If you need to add fields the easiest way is to add them in model objects
com.salesmanager.core.model.*
Example of an annotated field
#Column (name ="IP_ADDRESS")
private String ipAddress;
Once you restart your instance the new field will be available.

ManyToManyField is not getting saved in Wagtail Page

I have a subclass of Wagtail Page class that has field of django ManyToManyField type. When I try to create a new instance of my page object, I get a list of objects that the the ManyToManyField points to and I am able select multiple items. However, after creating that page when I try to edit the same page, it seems no data got saved for the ManyToMany field. I know in Django ModelAdmin one have to override the save_related() to save ManyToMany field data. Is there a similar method for the Wagtail Page model?
You should define the field as a ParentalManyToManyField relation, as per the example here: http://docs.wagtail.io/en/v1.13.1/getting_started/tutorial.html#categories
This is a variant of ManyToManyField which is able to keep track of the relation in memory, allowing it to work in situations such as previewing and saving as draft (where it doesn't get saved to the normal database records).
I was able to use the 'after_edit_page' and 'after_create_page' hooks to save the data for the page's ManyToMany fields.

wagtail modeladmin: is it possible to add "explore child pages" column?

I've been using wagtail-modeladmin to create custom lists of certain page types. That gives me the ability to edit those pages. But I'd also like to be able to click through somehow to the "normal" admin explorer version of those pages, and be able to view/add child pages to them.
essentially giving myself a column with the little arrows in on the right, just like in the normal wagtail admin page explorer...
OK I know it's bad form to answer your own question, but I've got this working by using a custom method on the model admin object that reverse wagtails admin urls:
class MySpecialPageModelAdmin(ModelAdmin):
def view_children(self, obj):
url = reverse('wagtailadmin_explore', args=[obj.id])
return format_html(f'View Children')
list_display = ('title', 'live', 'view_children')
but actually, I think I'm not going to end up using this, just replacing this particular modeladmin with a direct link to the right place in the explorer.

Django ModelForm save using db_alias param "using"

Is it possible to save ModelForm object data with db_alias different than "default"
my_form = MyModelForm(request.POST)
my_form.save(commit=True,using="db_alias")
as well as saving data with model instance?
Thank you.
Short Answer: Unfortunately ,you can't save the form that way. If you form doesn't contain ForeignKey or m2m fields (or you are controlling them yourself, for example using an autocompletefield, etc.), you can handle the object after the form:
_obj = _form.save(commit=False)
_obj.save(using=_db_alias)
Long answer: If you want the modelform to behave like a normal one with ForeignKeys and m2m-fields, something like:
# The form's foreign_keys and m2m-fields get the data from the db_alias database
# and evertyhing is sdisplayed correctly on the template.
_form = myModelForm(request, db_alias=_db_alias)
# The form saves to the correct DB and foreigns & M2ms are matched correctly in this DB
# _form.save()
Although this would be ideal, you just can't use this behaviour. There are many DB hooks that you need to alter in Django code to get this working. What I have done is to create a new modelform class from the base modelform, and get the (partial) functionality described before.
Hope this helps, and also hopping a better solution comes soon.

Resources