Django AdminModel add_view prepopulated fields - python

I have a simple model being displayed in the admin. In the add view I have 4 fields, with the first field being a foreign key to user. I need to:
Pre-populate the user field.
Make the field read only.
I cannot find any documentation on this. I looked at the following links:
django admin "add page" initial datetime from GET parameters,
Customize Django Admin: Add More Than One Default Inline on Parent Add_View
EDIT:
I found a solution for my first problem here; Djanjo admin: Prefill data when clicking the add-another button next to a ForeignKey dropdown

Here, you need to add jQuery for prepopulate that particular field. Create your own js script file inside static directory of your app & just extend change_form.html of admin site. For example if you want add script.js script into your add template, your extended change_form.html will look like as follows:
{% extends 'admin/change_form.html' %}
{% load static %}
{% block admin_change_form_document_ready %}
{{ block.super }}
<script type="text/javascript" src="{% static 'qb/js/formset_handlers.js' %}"></script>
{% endblock %}

Related

How to refresh the admin/app view after some time in django

My app has two users, frontend and backend.
The frontend user will insert the data and the backend user will check the record of the app in the admin panel.
I want to refresh the app view of the admin panel every 10 or so seconds.
On the frontend, I can use this script to refresh
<script type="text/javascript">
setTimeout(function(){
location = ''
},60000)
</script>
But how do I refresh the backend?
I have searched and there are lots of stuff using ajax jquery, and others but I am sorry I am not familiar with any of them.
Just want a simple solution. Is it even possible?
override the admin changelist template and add that same code you have there.
make a template called [your model]_changelist.html. put it in [your app]/templates/admin/[your app]
{% extends "admin/change_list.html" %}
{% block extrahead %}
{{ block.super }}
<script>
[your script]
<script>
{% endblock %}
Then in admin.py
class [your model]Admin(admin.ModelAdmin):
change_list_template = "admin/[your app]/[your model]_changelist.html"

JSignature Field Not Appearing in Django

First time posting on the site, apologies before hand as I am a newbie.
Building a Django project in Visual Studio for a class and need a signature form to appear on one of the pages. Currently been following this guide: https://pypi.org/project/django-jsignature/ but have hit a roadblock as all I can get to show on the page is a save button. Below I've listed what I've got.
forms.py
from django import forms
...
from jsignature.forms import JSignatureField
from jsignature.widgets import JSignatureWidget
...
class SignatureForm(forms.Form):
signature = JSignatureField()
template.html
{% extends "app/layout.html" %}
{% block content %}
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
{{form.media }}
<form action="." method="POST">
{% for field in form %}
{{ field.label_tag }}
{{ field }}
{% endfor %}
<input type="submit" value="Save"/>
{% csrf_token %}
</form>
</body>
{% endblock %}
views.py
from jsignature.utils import draw_signature
from app.forms import SignatureForm
...
def signature(request):
assert isinstance(request, HttpRequest)
return render(
request,
'app/template.html',
{
'title':'About',
'message':'Your application description page.',
'year':datetime.now().year,
}
)
def my_view(request):
form = SignatureForm(request.POST or None)
if form.is_valid():
signature = form.cleaned_data.get('signature')
if signature:
#as an image
signature_picture = draw_signature(signature)
#or as a file
signature_file_path = draw_signature(signature, as_file=True)
Again, when taken to my template page all that populates is a lone save button. I included this in the body of my layout html page as I had read it could be an issue with running the script on the page but still no luck.
<script src="ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Can anyone point me in the right direction? Hopefully I have provided sufficient info.
I had the same problem. I fixed it by changing where I put {{ form.media }}.
Documentation says to put it above the form, I instead inserted it bellow all my other JS imports.
base.html
.
.
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.bundle.min.js"</script>
{% block extra_javascript %}{% endblock %}
form-template.html
{% extends "base.html" %}
{% crispy form main_helper%}
{% block extra_javascript %}
{{form.media}}
{% endblock %}
I know this is old, but I just installed django-jsignature and had the same issue. I am new to Django and would like to share the solution to those that are also new to Django and want to use django-jsignature in their project.
There are a few things you have to check.
First, use Chrome, then go to Developer Tools. Check your console and see if you have Javascript errors. If you do, you have to modify 2 files.
The 2 files you have to modify can be found at https://github.com/fle/django-jsignature/pull/11/commits
Reload your template page, and see if you still have javascript errors on your page.
I am using jQuery Core 3.4.1. and this is working great for me with no errors. I have placed the jquery script link on the head section of my html page.
Remove all other javascript dependencies just to make sure they are not conflicting.
Now if you no longer have javascript errors and you still don't have a signature pad, move to step 2.
Load your html template in Chrome and View Page Source. On where you're supposed to have the signature section, you should see a "hidden" div with in the form. That means that the form loaded correctly in html, but your CSS may cause this section not to display correctly.
If that is the case, try creating a new template and just have the jsignature template code in it without any CSS just to test.
If you do not see a "hidden" div on your signature template html when clicking on View Page Source, that means you're page did not render correctly.
a. On your views.py, make sure you add {'form': form } in your context. This instruction was not included in the Readme.
example: return render(request, 'your_signature_template.html', {'form': form }
b. On your signature_template html file, make sure you have {{ form.media }} on top of your form.
Follow exactly what's in the django jsignature tutorial on the pypi site and just make sure you have the latest version of jquery in the head tag of your template. And also dont forget to pass an empty instance of the Signature form to your render method through to your template
I made a demo. Checkout https://djsign.herokuapp.com
And you can find the codes at https://github.com/mnnlthmpsn/djsignature.git
Same Problem, different solution:
I tried to embed the sign-field in a modal, where AGBs should be shown and signed.
Beforehand i made sure that the signaturefield would show up correctly when using nothing but the example-case by fle plus my own base with header and sidebar. There, everything was working allright.
When trying to embed it into another page (with or without being in a modal), the Signaturefield would not show up, but DevTools (Chrome) showed that it loaded correctly.
I saw the size properties of the field being "ratio" for "height" and "width", and fixed "height" to 200px. Then everything worked all right.
forms.py:
from django import forms
from .models import Signature
from jsignature.widgets import JSignatureWidget
from jsignature.forms import JSignatureField
class SignatureForm(forms.ModelForm):
signature = JSignatureField(widget=JSignatureWidget(jsignature_attrs={'color': '#e0b642', 'height': '200px'}))
class Meta:
model = Signature
fields = ['signature']

Filename only in django form field

I have a model that contains a filefield and am using a modelform to add instances. When I come to modify an instance the form shows the current file and displays the file path ie library/filename.
Is there a way to show just the filename in the form?
Thanks
I got around this by using javascript.
I added the following to my model..
def filename(self):
return os.path.basename(self.file.name)
Then added this into my javascript in my template
{% block javascript %}
<script>
{% if part.file %}
$('[href="{{ part.file.url }}"]').html("{{ part.filename }}");
{% endif %}
</script>
{% endblock %}
This changed the link to show just the filename
A FileField will use by default the FileInput widget that produces a <input type="file"> HTML tag. I don't think you can change the default "display full path" behaviour from Django, check this post.
However, you can customise things in your ModelForm like that:
class YourForm(ModelForm):
class Meta:
...
widgets = {
'your_file_attribute': FileInput(attrs={'html_attribute': value}),
}

Adding css/js files to the home site in the admin's panel django

I am trying to add a simple script to my admin's panel in django. I am following this example from the doc, which works when I do this:
class ArticleAdmin(admin.ModelAdmin):
class Media:
js = ("my_code.js",)
admin.site.register(Article, ArticleAdmin)
my_code.js (which lives in STATICFILES_DIRS) gets executed when I open the "Article" link in the admin's panel (so this would be the example url: localhost:8000/admin/news/article/)
However, I want it to be executed in the home site, as in right after I login to the admin's panel (this would be the url:localhost:8000/admin/) . Where do I have to insert the class Media then?
Are you trying to make your custom javascript appear on all admin pages? Then the best thing to do is to override the default admin templatte.
Look in your django installation and find django/contrib/admin/templates/admin/base.html make a copy of it in templates/admin in your project folder. Then simply add the following to the html.
<script scr="my_code.js" type="text/javascript"></script>
Then the js will be available on all admin pages.
I found another way which is overriding instead of replacing as explained in here.
If you place the file base.html into templates/admin:
{% extends "admin/base.html" %}
{% load static %}
{% block footer %}
{{ block.super }}
<script type="text/javascript" src="{% static 'my_code.js' %}"></script>
{% endblock %}
This will insert the script after the footer in the at localhost:8000/admin/.
Here I am "overriding" the base.html. But since I am using .super (explained here) it adds the script after the footer tag.

Google map Autocompletion in Django Admin Add form

I have a model which uses source and destination fields and these are usually populated from a frontend template. Template has two form fields which are associated with Google map autocomplete APIs. But if I want to create a new object through admin panel, how can I integrate autocomplete API with add form's source and destination fields?
You can easily use something like https://github.com/ubilabs/geocomplete/ in django admin —
Override the change form template to include the required js:
{% load staticfiles %}
{% block extrahead %}{{ block.super }}
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/geocomplete/1.4/jquery.geocomplete.min.js"></script>
<script src="{% static 'path/to/your/js/geocomplete.js' %}"></script>
{% endblock %}
In your own js file:
$("#address_input").geocomplete();
Docs here on how to populate form using the library:
https://github.com/ubilabs/geocomplete/#populate-form-data
There is Django admin widget called django-location-field that does exactly what you ask. I use it in my projects.
https://github.com/caioariede/django-location-field

Categories

Resources