I am trying to display some data in my Django admin ReadOnlyFields, but I am unable to display, I want to display emailid and verify_emailid in the same line in the fields, I can do it using fieldset but it's displaying lable also, please let me know how I can display data without a table.
Here is my admin.py file...
class MyModelAdmin(ReadOnlyAdminMixin, CustomModelAdmin):
fields = (('emailid','verify_emailid),'mobilenumber','type')
here emailid and verify_emailid display in the same line but the issue is the verify_emailid display label, and I don't want the label of verify_emailid, please let me know how I can remove the verify_emailid label...
If you want complete control of the text for a particular line, you could add a method to control that line, and then add that method as a readonly field:
Solution
from django.utils.html import format_html
class MyModelAdmin(ReadOnlyAdminMixin, CustomModelAdmin):
fields = ('my_custom_line','mobilenumber','type')
def my_custom_line(self, instance):
return format_html('<p>{} {}</p>', instance.emailid, instance.verify_emailid)
How does the solution work
Any method on ModelAdmin class that returns some text, can be used as a readonly field. You can read more about this in the docs.
format_html is just a safe way of inserting html, to avoid various attacks. The values listed after the html are inserted into the html as would normally happen. You can edit this line anyway you like to get the desired affect. You can read about that here.
Related
I have a string variable in a Python file that I am trying to render in my HTML template. The variable is called contacts, and in my template, I have {{contacts|default:"null"}}. From the documentation, it seems like that should work, but the template keeps coming up with the null keyword. I've scoured the documentation and found nothing. Probably a super simple thing I'm overlooking that has frustrated me to no end.
In the python file, I'm using an API to get a JSON and unloading it into a dictionary (don't know all the specific terms), where I then extract the value I need into a string:
...
dict_data = dict(json.loads(data))
contacts = str(dict_data["contact_count"])
Then in my HTML file:
<p class="spotbanner">
{{contacts|default:"null"}} spots left!
</p>
Is there something else I'm missing? Something super simple that I just don't understand about Django despite having used this method before? Happy to provide more information.
Poked around a teensy bit more and found an answer. For those like me:
It's not as simple as just rendering the variable. Django doesn't see it until you import the .py file into your views.py. Once you've done that, you'll need to create a context in the method that renders the page. For me, it finally worked once I added:
context = context = {"contacts":contacts}
Maybe a simple example might help you. Calling render_to_string to load a template HTML in Django.
Be aware the key name will map to the variable name in the HTML
from django.template.loader import render_to_string
rendered = render_to_string('my_template.html', {'foo': 'bar'})
# {{foo}} will show string 'bar' in HTML
Referral: https://docs.djangoproject.com/en/3.1/topics/templates/
Accordingly, by your cases, suppose we'll see something like
contacts = str(dict_data["contact_count"])
# if you want to show contact_count --> use {{contact_count}} in HTML
rendered = render_to_string('my_template.html', contacts)
I m using wagtail 2.8
I have article as snippet and i want to create articles page add all in easy way with out need to add them one by one (i have 400 )
i am using stream Field with StructBlock
class NewsListBlock(blocks.StructBlock):
slug = blocks.CharBlock(help_text='Block Slug')
items = blocks.ListBlock(SnippetChooserBlock(News))
class Meta:
label = 'News'
icon = 'doc-full'
Create a Django management command to read and load the data into your model.
I'm new to Django and I'm developing a project in which there are profile pages.
Well, the problem is that the primary key has whitespaces but I don't want them to show in the url, neither like "%20%", I want to join the words. For example:
website.com/Example Studios --> website.com/examplestudios
I've tried this:
url ( (r'^(?P<studio_name>[\w ]+)/$').replace(" ", ""), views.StudioView, name = 'dev_profile')
But didn't work (it seems like it turns the raw part to string before reading the url) and with 're' happens the same. I've been searching for solutions but I'm not able to find them (and slugify doesn't convinces me).
What's solution to this or what do you recommend?
In urls you define patterens which Django will catch e.g. r'^test/$' this means that when someone try to get yourdomain.com/test Django will catch it and call the view which will probably render template. You need to solve your problem on url generation e.g. in template . Therefore in urls:
url ( (r'^(?P<studio_name>[\w ]+)/$'), views.StudioView, name = 'dev_profile').
You need to transform primary key to word without space in template. One way is to use slug for every record.
Also add slug field to Studio model which is autogenerated and non-editable field(you can generate it from name e.g. Example Studios->examplestudios).
I am looking for a way to render a variable that will be available in the context of the the page where the cms page will be rendered.
Ex:
I have in the context the logged in user and I also have the last transaction he made on the website.
I would like the text in the rich text field in Wagtail to be like this so that the marketing team can tweak the copy.
Hello ||firstname|| thanks for your purchase. ||productname|| will be
shipped to you soon. The expected delivery date is
||expected_delivery_date||
To be less confusing I replace the double brackets by double pipes to show that the templating system does not need to be django templates for those ones. Simple templating is enough maybe using https://docs.python.org/3.4/library/string.html#template-strings
I think I can achieve this by doing:
A stream field that would have blocks of rich text field and a custom block with the possible context variable they can use
A custom render function that would regex and replace the merge tags in the rich text block with the context values
Create a new filter for simple templating. ex: {{ page.body|richtext|simpletemplate }}
Is there any more obvious way or out of the box way to do templating from within a rich text field?
It would be clunky with a separate streamfield block for each inserted context variable. You'd have to override the default rendering which wraps elements in div tags. However I like that it is more foolproof for the editors.
I've done something like the custom rendering before, but with simple TextFields for formatting special offer code messages. Wagtail editors were given the following help_text to illustrate:
valid_placeholders = ['offer_code', 'month_price']
template_text = models.TextField(
_('text'),
help_text="Valid placeholder values are: {all_valid}. Write as {{{example}}}".format(
all_valid=", ".join(valid_placeholders),
example=valid_placeholders[0],
)
)
This rendered as Valid placeholder values are: offer_code, month_price. Write as {{offer_code}}.
Then in the view:
template_keys = [i[1] for i in Formatter().parse(template_text)]
…and continued rendering from there. Remember to validate the field appropriately using the above Formatter().parse() function too.
I used Django's template formatting rather than Python's string.format() because it fails silently, but you could go with string.format() if cleaned adequately.
The custom template filter would feel easiest to me, so I'd start with that approach and switch to a custom render function if I ran into hurdles.
I found an easier way to do this. I wanted my editors to be able to create pages with dynamic customization to the individual user. With this, my editors are actually able to put template variables into any type of content block as {{ var }} which works just like the Django templating language. For my use case, I am allowing my editors to create email content in the CMS, then pulling that to send the emails:
This is the function to call:
def re_render_html_template(email_body, context):
"""
This function takes already rendered HTML anbd re-renders it as a template
this is necessary because variables added via the CMS are not caught by the
first rendering because the first rendering is rendering the containing block,
so instead they are rendered as plaintext in content the first render, e.g., {{ var }}
Example:
input: <p>Hey {{ user_account.first_name }}, welcome!</p>
output: <p>Hey Brett, welcome!</p>
#param email_body: html string
#type email_body: str
#param context: context dictionary
#type context: dict
#return: html string
#rtype: str
"""
from django.template import Context
from django.template import Template
template = Template(email_body)
context = Context(context)
email_body = template.render(context)
return email_body
Then I call it like so:
email_body = render_to_string(template, context)
# need to re-render to substitute tags added via CMS
email_body = re_render_html_template(email_body, context)
How can I have URLs like example.com/category/catename-operation/ in Django?
Also in some cases the user enters a space separated category, how can I handle that?
E.g if the user enters the category as "my home", then the URL for this category will become
example.com/my home/ which is not a valid URL.
How can I handle these things?
If you want to keep your URLs pretty, for example when a user enters "my category" you could have "my-category" instead of "my%20category" in the URL. I suggest you look into SlugField (http://docs.djangoproject.com/en/dev/ref/models/fields/#slugfield) and prepopulating that slugfield using ModelAdmin's prepopulated_fields attribute.
http://example.com/my%20home/ is a valid URL where space character is escaped and Django will do all escaping/unescaping for you.
You can use the slugify template tag within your views to deal with spaces and such like so:
from django.template.defaultfilters import slugify
slugify("This is a slug!") # Will return u'this-is-a-slug'
You can try an improved version of SlugField called AutoSlugField which is part of Django Custom Management Command Extensions.
You could consider adding a URL-friendly name to your category and using that in the URL instead.
As another example you could have example.com/tv/ and have the category called "Televisions."
How can I handle these things?
If you want to handle this thing, to obtain my-url, then use the form field clean method to return the valid url. Thats what it is meant for.