Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No migrations to apply. I got this error in test
I got an error when I do test, Operations to perform: Apply all migrations: admin, app, auth, contenttypes, sessions Running migrations: No migrations to apply. I wrote in test.py class UserModelTests(TestCase): def test_is_empty(self): queryset = User.objects.order_by('user_id').values()[:2] expected = [ {'name': 'Tom', 'user_id': 1, 'nationarity': 'America', 'dormitory': 'A', 'group': 3} ] for idx, item in enumerate(expected): self.assertDictEqual(item, queryset[idx]) I read documents and other web site, I found fixtures & setUp() are needed maybe, but I cannot understand how to write it.How should I fix this?What should I add to this code? -
Django not serving webpack
My application structure looks like - MyProject -- MyProject/ -- assets/ -- bundles/ # this is where the bundles get outputted -- js/ -- node_modules -- templates -- webpack-stats.json -- webpack.config.js All relevant code concerning webpack on the django side: INSTALLED_APPS = [ ... 'webpack_loader', ] WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), } } ... STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'assets') ] My url file looks like this from django.conf.urls import url from django.contrib import admin import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index), ] on the webpack side: var path = require("path") var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') module.exports = { context: __dirname, entry: './assets/js/index', output: { path: path.resolve('./assets/bundles/'), filename: "[name]-[hash].js", }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), ], module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ } ] } } My template file looks like this {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Example</title> </head> <body> <div id="react-app"></div> {% render_bundle 'main' %} </body> </html> When I run python manage.py runserver, my html file gets sent back to me on localhost:8000 but the javascript file … -
Django-autocomplete-light & QuerySetSequence - getting the name of the original model for each QuerySequenceModel
I have 3 models from cities_light: City, Region and Country. I'm using QuerySetSequence with Django-autocomplete to create a queryset involving all 3 of these models, so that a user can type in one search bar to search for all types of location. I have things working but my current implementation feels very hacky, so I'm looking to see if there's a better way of doing this. As far as I can tell, while QuerySequenceModel inherits all the attributes of the relevant model (in this case, either City, Region or Country), it doesn't have an attribute that simply returns the name of the model it's inheriting from. So, the only way I can see of actually determining which model a QuerySequenceModel is to rather naively check to see whether it contains any defining attributes that uniquely identify it as either a City, Region or Country. Thus: for queryset in locations.query._querysets: if not hasattr(queryset.model, 'country'): profile.favourite_countries = queryset elif hasattr(queryset.model, 'region'): profile.favourite_cities = queryset elif hasattr(queryset.model, 'country'): profile.favourite_regions = queryset This works, but is hardly elegant, and also needs additional hacking in order to be fully functional (i.e. recognizing when one location type isn't present). For reference, here is the full list … -
How do I create and submit a form from a model inside a modal?
In my app I needed to add a form created from a model so I can add and edit records in my database. I did it in the following way to render the form in a separate page.: 1) I created a forms.py file: from django import forms from store_app.models import Product class AddNewProductForm(forms.ModelForm): class Meta: model = Product fields = ["title", "description", "weight", "price"] # Fields from my model class EditProductForm(forms.ModelForm): class Meta: model = Product fields = ["title", "description", "weight", "price"] # Fields from my model 2) Then I created the html template to display the form, edit_product.html: {% extends "store_app/base.html" %} {% load static %} {% block title %}Edit Product{% endblock %} {% block content %} <h1>Edit Product</h1> <form method="POST"> {{ form.as_p }} {% csrf_token %} <input type="submit" class="btn btn-primary" value="Submit!"> </form> {% endblock %} 3) After that, I added the following to my app's views.py: from store_app.models import Product from store_app.forms import EditProductForm from django.shortcuts import render, get_object_or_404 def index(request): return render(request, 'simple_app/main.html') def edit_product_view(request, id): instance = get_object_or_404(Product, id=id) form = EditProductForm(instance=instance) if request.method == "POST": print("POST") form = EditProductForm(request.POST, instance=instance) if form.is_valid(): form.save(commit=True) return index(request) else: print("ERROR FORM INVALID") return render(request, 'simple_app/edit_product.html', {'form': form}) … -
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 = …