Customising specific fields in Django Admin change form - django

I have a couple of fields in my model that to which I wish to add a link that will allow the user to search for names/files (external from the application's database).
So what I would like is:
Field name: [text box] - LINK
Is there a straightforward django way of achieving this?
Cheers.

You need to change the widget that the form field uses to display the models information. You basically add some html after the input to link to where you want.
Here's some code I put together to create a widget that displays how many characters are left for a CharacterField so it's similar to what you are looking to do:
https://github.com/pastylegs/django-widget-charsleft/blob/master/widget_charsleft/widgets.py

Related

Flask WTForms - option_widget for SelectMultipleField?

I have a field in my Flask WTForm which uses a SelectMultipleField. I'm using a frontend library which renders the choices fine from the db and adds them to the input field as tags when I select them (like the tags do on this website when creating a question!).
However the data is not being saved, form.field.data and request.form.getlist('field') etc all show None. If I add option_widget=widgets.CheckboxInput to the SelectMultipleField, I can select and save data.
So what I'm wondering is, do I need make a custom field or widget in order for the form to use the selected options as the form data (for example, instead of checking if the field has been checked, it checks if it's in the input field). Going a bit mad reading all the documentation so grateful for a hint in the right direction! Code below:
field = SelectMultipleField(
"fieldname",
validators=[Optional()],
widget=widgets.ListWidget(prefix_label=False),
# option_widget=CheckboxInput(),
)
please try this way
from flask_appbuilder.fieldwidgets import Select2ManyWidget
"users": QuerySelectMultipleField(
_("group.user"),
query_factory=lambda: db.session.query(User),
widget=Select2ManyWidget(),
default=[],
),
The result will look like the image below

Illustrated texts in Django model

I am trying to make one Blog using Django 2.0 and I have already created a primitive one. It has a Post model which is as follows:
class Post(models.Model):
PriKey = models.CharField(max_length=255,primary_key=True)
Heading = models.CharField(max_length=100)
DateOfPost = models.DateField(default=datetime.date.today())
Content = models.TextField()
As it can be seen, the content area is only textual and as of now, I can't add any special style or pictures inside my content.
I thought of using HTML tags inside the text content but they are appearing unchanged when the web page is rendered.
So my question is, is there any way of storing pictures along with the text in the content field of the Post model? I want to make something like this
Is there any way of showing the pictures in their respective positions using Django model? If no, is there any other way of doing this?
Also, is there any way of storing HTML codes inside django models and render them as it is when the website is run?
You can store html tags inside the field.
while rendering, to template mark it as safe
{{ post.content|safe }}
This will render all the html tags.
But this is not a good way as it makes you vullerable to cross site scripting attacks
A better method is to use something like a ckeditor
It provides a RichTextField and RichTextUploading Field and using this you can upload pictures, videos, code snippets, style your text and a lot more inside one field.
There are many other optons, but I prefer ckeditor
Ckeditor is a cross platform editor, django-ckeditor is a library containing django implementation of ckeditor which gives you full backend and frontend combined
ckeditor
django-ckeditor
django-pagedown A django app that allows the easy addition of Stack Overflow's "PageDown" markdown editor to a django form field, whether in a custom app or the Django Admin
I think you should give it a try
Cheers :)

Save the dynamically populated value on dropdown

I'm using wagtail CMS for Django, I want to add a dynamically populated value for a dropdown and save it on the Page model, this is my code:
class MyPage(Page):
domain = CharField(max_length=10, choices=MY_CHOICES)
subdomain = CharField(max_length=10, choices=[('', '------')]
I've got some frontend logic to populate dynamically the options for subdomain, but after I hit save I got: The page could not be created due to validation errors And in the subdomain field: Select a valid choice. [my value] is not one of the available choices.
I can't use ForeignKey to populate subdomain because it depends from an external API service that we're using.
I tried to use a custom field that inherits from CharField with no success, it looks it executes validate method only for the domain field.
If you use the choices argument, you have to predefine the list of possible values. Read the relevant part of the docs (last two paragraphs of that section).
You could omit the choices argument from the model field definition and only render a HTML select tag in the frontend (which is then filled with options dynamically, like you explained).
You could also look into changing the default widget of the CharField to a select tag, like this answer and this part of the docs show.

'Hiding' form query from URL (Django 1.3)

I have a form with 6-7 fields. After user input, my webapp searches for those fields in a database and displays the results.
Now the issue is, that the URL ends up having all the form field names and their values in it.
result/?name=lorem&class=arc&course=ipsum
Now with the form having 7-8 fields the url ends up looking ugly.
Is there a Django technique to 'hide' these from the URL? Quotes around hide because I'd be okay with a completely different way to pass the objects to my database from the form as well.
Use a POST request. Here's the django docs on forms and a specific example using POST>. HTML-wise, all you need to do is change the method on the form tag.
I do not recommend to use POST requests for search. If you'll use GET it will be easer for user, he can just bookmark a link and save search or share search results with friends.

Alternative form for Django's `ChoiceField` that can handle thousands of entries

I have a form with a ChoiceField in it. It is rendered to the user as a dropdown box.
Problem is, I have thousands of entries in this field, which is causing the page to (a) load very slowly and (b) be sluggish.
I want an alternative widget, instead of Select, that could handle more than 10,000 choices.
Something like the admin's raw_id_fields would be good (if only it were usable in general forms...) but I'm open to ideas.
If autocomplete is an option for your UI you can take a look to django-simple-autocomplete:
App enabling the use of jQuery UI autocomplete widget for
ModelChoiceFields with minimal configuration required.
EDITED (reply OP comment)
I have not tested this solution, but digging documentation and source it seems that not all data is loaded at a time:
The ability to specify an URL for the widget enables you to hook up to
other more advanced autocomplete query engines if you wish.
Source code:
def get_json(request, token):
"""Return matching results as JSON"""
...
di = {'%s__istartswith' % fieldname: searchtext} # <- look here!
items = queryset.filter(**di).order_by(fieldname)[:10]
Widget source code
$("#id_%(name)s_helper").autocomplete({
source: function(request, response){
$.ajax({ # <-- look here
url: "%(url)s",
data: {q: request.term},
success: function(data) {
I don't know what is the raw_id_fields but why not use a model to store all your choices ?
class Choice(models.Model):
value = models.CharField()
class MyModel(models.Model):
choice = models.ForeignKey(Choice)
It would then be easy to select it if you want to display only 20 at a time for example.
Based on this comment (which really, you should have included in your question):
Let me clarify my task: I have 10,000 users. I have a form in which
you choose a user. You need to be able to choose any user you want.
You can't just load 20, because then you won't be able to choose the
other 9,980 users.
If you want something built-in, you can use the FilteredSelectMultiple widget from django.contrib.admin.widgets, which puts a filter on your select.
You should also cache the results of the 10,000 users so you don't hit your db everytime. This is what is causing your delay, not the number of users (which is tiny, for practical performance problems).