Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-statsy seem to be a doubtful app
I have a bit of difficulties to understand how django-statsy works. Does anyone be able to tell me if it works well for them? I am a new programmer in Django and using the template, but it is unclear that we could use the following structure in a .html template : var statsy = new Statsy() statsy.send({ 'group': 'post', 'event': 'subscription' }); Am I right? -
Django: Truncate text given the width of parent div
I'm looking to achieve an effect using Django where the text will truncate (i.e. put ... at the end) when the length of the text exceeds that of the parent div. With Django, the template tag allows me to set a fixed number of characters at which the text will truncate {{ user.email|truncatechars:24 }} However, I'm looking for a more dynamic solution. Thanks! -
Django restrict/allow access by groups from ldap
I have Django project that has two apps App1 and App2) each app has only 1 view. . My project connected to openldap using django-auth-ldap. I have two groups(Group1, Group2). I Added decorators before my views in app1 and app2 (@login_required) and the result as expected that all users from group1 and group2 will be able to login to both apps. I want to be able to just allow group1 to access app1 only and group2 access app2 only. I tried many codes but no one work with me. Here is my code: app1.views.py from django.shortcuts import render from django.template import loader from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import views as auth_views @login_required(login_url='/accounts/login/') def index(request): #getting our template template = loader.get_template('main/index.html') #rendering the template in HttpResponse return HttpResponse(template.render()) Here is my ldap settings from settings.py: #Generated by 'django-admin startproject' using Django 1.11. import os import django AUTHENTICATION_BACKENDS = ('django_auth_ldap.backend.LDAPBackend',) import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType AUTH_LDAP_SERVER_URI = "ldap://mydomain.com" AUTH_LDAP_BIND_DN = "cn=admin,dc=mydomain,dc=com" AUTH_LDAP_BIND_PASSWORD = "mypass" AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=ou_org_unit,dc=mydomain,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)") AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=ou_org_unit,cn=group1,cn=group2,dc=mydomain,dc=com", ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)" ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT … -
django query running forever and not timing out
I have some django applications that is killing my mysql server there are queries that are running and not timing out and clogging my mysql server Just need help on how to resolve this issue the proper way not sure if this is how django is designed or i need to add a timeout settings i thought django should do this by default, not sure because makes zero sense to have this with no timeout Here are the queries that are not timing out or closing MySQL on localhost (5.7.19) load 5.27 4.81 4.69 4/2383 41852 up 0+00:18:41 [19:13:16] Queries: 8.6k qps: 8 Slow: 0.0 Se/In/Up/De(%): 61/01/02/00 Sorts: 0 qps now: 5 Slow qps: 0.0 Threads: 99 ( 99/ 1) 44/00/00/00 Key Efficiency: 98.9% Bps in/out: 839.8/22.3k Now in/out: 566.3/22.5k Id User Host/IP DB Time Cmd State Query -- ---- ------- -- ---- --- ----- ---------- 6 webapp_user localhost webapp_db 1096 Query Sending SELECT COUNT(*) FROM `django_session` WHERE `django_session`.`last_login` >= '2017-09-19 18:44:56' 9 webapp_user localhost webapp_db 1086 Query Sending SELECT COUNT(*) FROM `django_session` WHERE `django_session`.`last_login` >= '2017-09-19 18:45:09' 11 webapp_user localhost webapp_db 1085 Query Sending SELECT COUNT(*) FROM `django_session` WHERE `django_session`.`last_login` >= '2017-09-19 18:45:10' 15 webapp_user localhost webapp_db 1067 Query … -
Select2QuerySetSequenceView sends each item as a tuple of "(model id, object id)" - how does one use/retrieve the model id?
When joining multiple querysets of different models into a single queryset (using QuerySetSequence), each item in the queryset passed over to the front-end autocomplete is a pair of IDs - one representing the model, the other the PK of a specific object of that type. I can't find anything in the docs that explains how this ID is generated, nor how one could get a modeltype from the ID. It's not the same as calling typical python methods on classes such as .__class_. Example list data from a queryset: ['12-231','12-212','42-643','42-123','54-133'] The first value indicating the particular model that the following pk refers to. How do I use this value to lock in on the relevant model? -
Stop page from redirecting after form submission in Django
I am using django and I have created an app in which I want to upload a zip file which is saved in a specific location (At this point my django server is localhost) I have the following code which is working fine: This is my HTML Template: <form id="saveZipFile" enctype="multipart/form-data" action="" method="post"> {% csrf_token %} <input type="file" name="docfile" id="docfile"> <input type="submit" id="upload-button" value="Upload"> </form> This is my forms.py: class UploadFileForm(forms.Form): docfile = forms.FileField() This is my views.py: def handle_uploaded_file(f): with open('uploaded_zip.zip', 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['docfile']) return HttpResponse() else: form = UploadFileForm() return HttpResponse() urls.py: urlpatterns = [ url(r'^upload_file/$', views.upload_file, name='upload_file'), ] But in the end, the url is changing to /upload_file - which is correct as I understand - and that page is empty (since I am returning an empty HttpResponse) I am trying to build a Single-Page-Application and this redirection is throwing the entire state of my web-page out of the window. Is there any way in which I can possible make an AJAX call instead of using django forms? Thanks! -
Crispy forms django error: coercing to Unicode: need string or buffer, datetime.date found
So I have this error AFTER my database is populated, but when creating a NEW. If i don't run my csv importer I wrote (that just takes CSV files from an old database, imports models. Creates new instances of models, fills em out with the data and saves them) then adding a new Group (an entity in my app) works just fine. The form comes up empty and ready to go, if i run the importer then the edit breaks and the add with this error: I am not sure what is causing this. The importer is pretty simple. It might be that I have a parse_date from the csv function I miswrote? Usage parseDateTime(row[12]).strftime('%Y-%m-%d') def parseDateTime(dt): try: col_date_object = datetime.strptime(dt, '%m/%d/%Y') except ValueError: col_date_object = datetime.now() return col_date_object I double checked the import to and browsed the DB tables to make sure I wasn't off a row or a column or something. indeed things look good The model in question is this: @python_2_unicode_compatible class Group(models.Model): group_term = models.ForeignKey('GroupTerm', on_delete=models.SET_NULL, null=True, blank=True) #quesiton is can a group be termed many times? group_name = models.CharField(max_length=50) group_contact = models.CharField(max_length=50) tin = models.CharField(max_length=50) npi = models.CharField(max_length=50) notes = models.TextField(max_length=255, null=True, blank=True) start_date = … -
Django ImportError: No Modules named urls on apache2
Im trying to set up this repository on an apache production server in an Ubuntu Virtual Machine. After some troubles with apache I managed to get the wsgi-module and everything seemingly working together. However now Django seems to be acting up. When I'm trying to access the the website, I get the following error ImportError at / No module named urls Request Method: GET Request URL: http://opensr.human.uni-potsdam.de/ Django Version: 1.5 Exception Type: ImportError Exception Value: No module named urls Exception Location: /usr/local/lib/python2.7/dist- packages/django/utils/importlib.py in import_module, line 35 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/var/www/workspace', '/var/www/workspace/opensr'] Server time: Tue, 19 Sep 2017 17:39:45 -0400 Together with this traceback Environment: Request Method: GET Request URL: http://opensr.human.uni-potsdam.de/ Django Version: 1.5 Python Version: 2.7.12 Installed Applications: ('django.contrib.staticfiles', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.flatpages', 'django.contrib.sites', 'django.contrib.messages', 'bootstrap_admin', 'django.contrib.admin', 'test', 'colorful', 'ckeditor', 'sortedm2m', 'opensr') Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 103. resolver_match = resolver.resolve(request.path_info) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve 319. for pattern in self.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in url_patterns 347. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in urlconf_module 342. self._urlconf_module = import_module(self.urlconf_name) File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py" in import_module 35. __import__(name) File "/var/www/workspace/opensr/urls.py" in <module> 8. url(r'^test/', … -
Django model formsets- how do I create a mix of existing and pre-populated "new" entries
Lets say I am building a Reading List app. Each reading list has a name, and a number of ReadingListBook objects that link back to a book. Additionally, lets say that there are a number of users that have been given access to this reading list. Each user, after reading the book, is to give the book a rating of 1-10. See the following models: #models.py class Book(models.Model): name = models.CharField(max_length=255) class ReadingList(models.Model): name = models.CharField(max_length=255) class ReadingListBook(models.Model): reading_list = models.ForeignKey('ReadingList') book = models.ForeignKey('Book') class ReadingListBookUserRating(models.Model): reading_list_book = models.ForeignKey('ReadingListBook') user = models.ForeignKey(User) rating = models.IntegerField() #rating of 1-10 And the following ModelForm for a rating: #forms.py class RLBRatingForm(forms.ModelForm): class Meta: model=ReadingListBookUserRating fields = ['reading_list_book', 'rating'] At any given time, a user may have created ratings for some, all, or none of the books in a given reading list. My goal is to generate a formset, of multiple RLBRatingForms- one for each potentially rated book in a ReadingList. For any book that the user HAS rated, their existing rating will be pre-populated. For any book that they have not rated, the input field will be blank. I know how to create a formset for the existing ratings, but I am unsure … -
adding {% trans " " %} tag inside {% if .....%} tag
Base template that I have: {% load auth_extras %} {% if request.user|has_group:"Administrator" %} <li><a href="/admin/"> Admin Section &nbsp;</a></li> {% endif %} {% if request.user|has_group:"Moderator" %} <li><a href="/admin/">Admin Section </a></li> {% endif %} How to add {% trans " " %} tag to "Admin Section" in this case ??? Adding it dirrectly is restricted because I have tag in tag which is not allowed. Or will be better to ask - how to be in this case ? -
Insert python object in the Graphs javascript dataobject
I am working on the Python Django project and have added my HTML in the template folder. Now one of my page needs to render a graph. The data set of the graph is generated from the database and passed to the html. For a simple graph I have obtained the following code from HERE <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript"> window.onload = function () { var chart = new CanvasJS.Chart("chartContainerSet1", { theme: "theme1", title:{ text: "Restart Count PerDay" }, animationEnabled: true, axisX: { valueFormatString: "MMM", interval:1, intervalType: "Date" }, axisY:{ includeZero: true }, data: [ { type: "line", //lineThickness: 3, dataPoints: [ { x: new Date(2012, 00, 1), y: 450 }, { x: new Date(2012, 01, 1), y: 414}, { x: new Date(2012, 02, 1), y: 520, indexLabel: "highest",markerColor: "red", markerType: "triangle"}, { x: new Date(2012, 03, 1), y: 460 }, { x: new Date(2012, 04, 1), y: 450 }, { x: new Date(2012, 05, 1), y: 500 }, { x: new Date(2012, 06, 1), y: 480 }, { x: new Date(2012, 07, 1), y: 480 }, { x: new Date(2012, 08, 1), y: 410 , indexLabel: "lowest",markerColor: "DarkSlateGrey", markerType: "cross"}, { x: new Date(2012, 09, 1), y: 500 }, { … -
Append To Current Url Django
I have two URLs in Django. I would like to be able to use them almost as subdirectories. In my case, I have a table of parts belonging to a job, and in that table, i have buttons that would allow you to open a new URL with details of the part clicked. This would be the job URL. /view_job/1/ and when you click on an item I would like to be able to navigate to. /view_job/1/details/part1 Here are the two URLs. url(r'^view_job/([0-9]+)/$', app.views.viewfab, name='view_job'), url(r'^view_job/([0-9]+)/details/(.+?)$', app.views.viewfabdetail, name='fab_detail') and here is what I'm trying to achieve in the template. '<a href="{% url \'fab_detail\' "job number" record.mark %}">View</a>' the problem I am having is. I want to be able to pass the job number, which is /view_job/->"job number"<- to the template HTML and I have not been able to find out how to do so. Thanks for any guidance on the subject. EDIT Here is the model being used. class Fab(models.Model): jobid=models.IntegerField(default=0) mark=models.CharField(max_length=100) status=models.CharField(max_length=100) description=models.CharField(max_length=100) weight=models.CharField(max_length=100) truck = models.IntegerField(default=-1) load_date=models.DateField(null=True) check_date=models.DateField(null=True) checker=models.CharField(max_length=100) total=models.IntegerField(default=1) loaded=models.IntegerField(default=0) checked=models.IntegerField(default=0) -
Filtering object by datefield?
class Avergae(models.Model): state = models.ForeignKey(State, on_delete=models.CASCADE) region = ChainedForeignKey(Region, chained_field="state",chained_model_field="state", show_all=False, auto_choose=True, sort=False, on_delete=models.CASCADE) cluster = ChainedForeignKey(Cluster, chained_field="region",chained_model_field="region", show_all=False, auto_choose=True, sort=False, on_delete=models.CASCADE) school = ChainedForeignKey(School, chained_field="cluster",chained_model_field="cluster", show_all=False, auto_choose=True, sort=False, on_delete=models.CASCADE) average_date = models.DateField() average = models.DecimalField(max_digits=4, decimal_places=2) attendance = models.IntegerField() note = models.CharField(max_length=250) def __str__(self): return '{}: {}'.format(self.average_date, self.average) I wanted to filter the latest object according to the date. Needed to get the object that has most recent date value for attribute average_date. Please let me know the syntax. Thank you. -
Django, Ajax and Fotorama DB update
I'm trying to get images added to Fotorama Image slider from Django DB so far with no luck i would tremendously appreciate any assistance. I'm able to see the AJAX function returns values on the inspector console how ever cant get slider to display them. this is my urls.py url(r'image/busqueda/$', views.ImageBusqueda.as_view(), name='image-busqueda'), this is my views.py class ImageBusqueda(generic.TemplateView): def get(self, request, *args, **kwargs): images = Images.objects.all() data = serializers.serialize('json' ,images, fields= ('imagen','nombre','duracion')) return HttpResponse(data) and this is my JS <script> $(function () { $('.fotorama') .on('fotorama:show', function() { $.ajax({ url:'/image/busqueda/', type:'get', datatype:'json', success : function(data){ var img = "" for(var i = 0; i<data.lenght; i ++ ){ img += '<img src="' + data[i].fields.imagen + '"data-id="' + data[i].id + '">' } $('#img').html(img); } }); }) </script> this is the HTML <div class="fotorama" data-nav="false" data-shuffle="true" data-autoplay="true" data-arrows="false" data-loop="true" data-transition="dissolve" data-fit="cover" data-width="100%" data-height="100%" > {# NORMAL DJANGO WAY #} {# {% for img in imagenes %}#} {# <img src="{{ img.imagen.url }}" data-id="{{ img.id }}" >#} {# {% endfor %} #} {# JS WAY #} <div id="img"> </div> </div> -
Searching a Class by User ForeignKey
I have searched high and low and even in between and for some reason cannot come up with a clear answer... I am using django1.9 and created this model: class paymentInfo(models.Model): """ Model for storing payment info - Username as ForeignKey from userToCard - Store payment token - Store last 4 - Store card/bank name - Store bool value for Default method """ username = models.ForeignKey(User, db_column='username', on_delete=models.CASCADE) token = models.CharField(max_length=10) last_4 = models.IntegerField() bank_name = models.CharField(max_length=50) default = models.BooleanField(default=0) class Meta: # meta class to define the table name db_table = 'payment_methods' verbose_name_plural = 'Payment Methods' # for the admin site display ordering = ('username',) def __str__(self): return self.username # value displayed in admin view I have created some objects using some different usernames and want to filter out the paymentInfo objects by user. When I store the object, the database stores the user pk under the username column instead of the actual username string. I am not sure why, but that is not my issue here. My issue is when I am trying to filter out paymentInfo.objects using the username or the user pk. I cannot seem to filter it out and the error I normally get is … -
Django server stops when connecting to website through browser
python3 manage.py runserver 0.0.0.0:8000 From above code I'm starting my django website server. But when I'm trying to connect it through browser it stops server with exit code 1.0(killed). I'm opening my website through ip address of my remote server. -
User has no attribute get using inlineformset_factory
I am trying to add a One to Many relationship. Let's say student, class. My student model is giving me no attribute get error. The line before that says return data.get(name) Not very sure what is it trying to do. forms.py class StudentClassForm(ModelForm): class Meta: model = Student fields = ['name'] StudentClassFormSet = inlineformset_factory(Class, Student, form = StudentClassForm, extra=1) view.py ... add a new student student = Student.objects.get(id = student_id ) class = Class.objects.get(id = class_id) form = StudentClassFormSet(student, instance = class) model.py class Student class = models.ForeignKey(Class) -
How can I use the current Site as the default in a Django form using the Sites Framework?
I'm using the Sites Framework and want to save the current site as the default site value for one of my models. Model: class MyModel(models.Model): site = models.ForeignKey( Site, on_delete=models.CASCADE, default=Site.objects.get_current()) # THIS IS WHAT I WANT TO DO (DOESN'T WORK) ...other fields... Is there a way to automatically save the current Site object as the site attribute of MyModel anytime I save a MyModel instance? Or would I need to do this manually by overriding either the form's or the model's save method, (or similar override)? -
How to do a Django/Javascript combination; specifically - window.location
I have a Django/Phaser/Javascript set up like this: Project ----> Djangotemplates---------> Djangotemplates + example + static In the example folder is: example -----> templates -------> about.html + constr.html + game.html + index.html These are all django static files, no base.html, nothing really complicated except I have one problem. That is the main.js file in the js folder in the static folder. A link in the index.html file takes you to the game.html file which is basically the one single Phaser file that opens up the main.js file (that runs the game). Everything works so far, including the game itself. So... Index.html goes to game.html to main.js Now I have a method to get back to the main index.html file (from the game) - but THAT doesn't work. Like this: else{ if(flagGameover){ console.log("GOTO GAMEOVER"); window.location = 'index.html'; Now I've tried all sorts of things to make that last line work, but ?!!%*^?!##??? It seems if I put any Django code in the main.js file, such as: window.location = "{% url 'index' %}"; window.location = {% static '/example/templates/index.html' %}"; (and many more things taken off the Net, like script tags ) Putting in any Django code in the main.js seems to result … -
Ideal way to implement an article series / multipart blog post
I am in the process of writing a blogging engine in django, primarily as an educational exercise and I am wondering about implementing multi-part blog posts / series. I am working in python3/django so my code will be thus, though I'm mostly concerned with implementing the database structure properly. Given this generic model: class Article(models.Model): title = models.Charfield(255) content = models.TextField() My first idea is to simply add a series table and link it to the article: class Article(models.Model): title = models.Charfield(255) content = models.TextField() series = models.ForeignKey('Series') class Series(models.Model): title = models.Charfield(255) The issue that comes up next here is how to track the posts position and series length (ie: 2 of 4). I thought about using the series entry id's, or the post publish dates, though I can't guarantee that those will go in the same order as the posts. I could simply keep track of that on the article table. Then I can just use the .count() on the series objects for the series length, and get the article position directly from the field: which just doesn't seem to be as elegant as it could be: class Article(models.Model): title = models.Charfield(255) content = models.TextField() series = models.ForeignKey('Series') … -
Can you access a File browser thumbnail in a Django admin model class?
I have a Django application, with a model that has a Filebrowser field for uploading images. In the admin I have a method that returns an image html element so after a user uploads an image, they can see what they uploaded. Some images however are >10mb in size, and the page loads for a pretty long time. I tried looking through the File browser documentation to see if there was an attribute on File browser images that returns its thumbnail. obj.filebrowser_img.thumbnail or obj.filebrowser_img.url_thumbnail But I could only see ways to reference it in a Django template with fb_version template tags. Is it possible to retrieve the thumbnail version of the image outside of a template ? Admin.py class GalleryPhotoInline(admin.StackedInline): model = GalleryPhoto readonly_fields = ('image_tag',) fieldsets = ( (None, { 'classes': ('full-width',), 'fields': ('name', 'image', 'image_tag', 'display_order', 'is_published') }), ) def image_tag(self, obj): return u'<img src="{}" style="height: 125px;"></img>'.format(obj.image) image_tag.short_description = 'Image' image_tag.allow_tags = True Gallery Photo model class GalleryPhoto(models.Model): gallery = models.ForeignKey(PhotoGallery, null=True, blank=True, related_name='photos') name = models.CharField(max_length=255, null=True, blank=True) image = FileBrowseField(max_length=500, blank=True, null=True, verbose_name="Gallery Photo") create_date = models.DateTimeField(auto_now_add=True) display_order = models.IntegerField(default=99) is_published = models.BooleanField(default=True) def __str__(self): return "Gallery Photo" def get_thumbnail(self): return self.image class Meta: verbose_name = … -
Representation of objects
Sometimes we have to represent our objects of classes with it's attributes. Mostly we use def __str__ for string representation which generally return characters. But I have a class with no attribute that has characters. I wanted to represent that with the only attribute which is a DecimalField. Please help me to get the right syntax to represent my objects. -
Django & Celery - Accessing post_save data
I have a Celery task I'm attempting to call from a post_save signal. Signal is: @receiver(post_save, sender='foo.ModelClass') def execute_after_save(sender, instance, created, *args, **kwargs): special_task.apply_async(kwargs={'bar': instance.pk}, countdown=5) Task is: @app.task(bind=True) def special_task(bar, *args, **kwargs): bar = ModelClass.objects.select_for_update().get(pk=bar) print('Bar attribute: %s' % bar.attribute) With this iteration, I get an error saying special_task() got multiple values for argument 'bar'. In iterations where I send just the instance.pk as an arg, I get a TypeError saying I need to pass an integer. And when my signal looked like: @receiver(post_save, sender='foo.ModelClass') def execute_after_save(sender, instance, created, *args, **kwargs): special_task.apply_async(args=(instance.pk,), countdown=5) I get an error saying a ModelClass with that attribute DoesNotExist. I've looked at the other SO questions about this but I keep getting the same errors. Using Django 1.11.4, Celery 3.1.25 on Python 3.5. This task is eventually trying to select a newly saved ModelClass, perform additional work on it, and then save it again. How can I do this? -
Django Models: Generate field content from other fields in model instance
As an example, say I'm logging inventory items, and I need a unique identifier (that is also meaningful when read by itself) for each item. The following shows the model I am trying class InventoryItem(models.Model): item_name = models.TextField(max_length = 100) item_manufacturer = models.TextField(max_length = 20) item_product_num = models.TextField(max_length = 25) item_lot = models.TextField(max_length = 25) item_received_on = models.DateTimeField(auto_now_add = True) item_price = models.DecimalField() item_quantity = models.DecimalField() item_special_instructions = models.TextField(default = "NA", max_length = 200) item_reinspection_date = models.DateField() def makeUniqueID(self): unique_str = self.item_manufacturer + self.item_product_num + self.item_lot + datetime.datetime.now().strftime("%Y%m%d%H%M%S") return unique_str item_uniqueID = models.TextField(max_length = 50, default = self.makeUniqueID()) The above code errors NameError: name 'self' is not defined, and I suspect this is not the correct way to do this. Any help is greatly appreciated! The database I'm using is SQLite if that changes anything -
Wkhtmltopdf - How can I use a relative path?
I'd like to convert a Django template to pdf file. An image in template : <img src="{% static "img/person.png" }%" /> is changed to <img src="/static/img/person.png" /> and It works well in browser. But when I try to convert this html file to pdf file with Wkhtmltopdf module, there is an error : $ wkhtmltopdf --javascript-delay 5000 report.html report.pdf Warning: Failed to load file:///static/img/person.png (ignore) It seems that Wkhtmltopdf module needs only absolute path. If I set the src as a absolute path like : <img src="/home/bingbong/django/project/apps/static/img/person.png" /> It works well but I know it is not a good way. Is there any way to use static root path with Wkhtmltopdf? How can I convert it successfully?