Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Route requests with query parameters in Django without prepending with a backslash
I'm trying to process requests that have query parameters similar to the following url: http://127.0.0.1:8080/foo?bar=-capacity. I've done quite a bit of trial and error with Django's url patterns and regex but no success so far. My regex knowledge is admittedly lite. This pattern url(r'^foo(.)$', views.QueryFoo.as_view()), will process the above request but the problem is it grabs regular get requests like the following: http://127.0.0.1:8080/foo. I can add a backslash to the url pattern like this url(r'^foo/(.)$', views.QueryFoo.as_view()), which seems to be the Django norm but then I have to handle get requests from two separate urls. Any suggestions? -
Django Inline Copy Entry
I have been browsing many questions about Django inline, but can't quite find how to do this. I am using Django Nested Admin and am wanting to see how I can copy an existing row in the admin so that when I click on "Add another", it creates the new one as a copy. Here is an example: As an example...let's say I am creating a set of recipes. In these recipes, I want to create "variations" with the ingredients. So if I had "Strawberry Smoothie", I want to create a "variation" that has both the regular option, as well as a lactose-free option. So I have my main model called "Recipe": class Recipe(models.Model): name = models.CharField(max_length=128) instructions = models.TextField(blank=True) From here, I then need to add the ingredients, so in my admin.py, I have added: class RecipeAdmin(NestedModelAdmin): model = Recipe inlines = (VariationsInline,) Using the Nested Inline, I have an inline that allows me to add as many Variations, where each variation can then have as many ingredients inside of it. The issue I am running into is that sometimes these variations have 10+ ingredients (and their respective quantities) and I have to remake those for each variation I … -
Django Formset Ajax
This is a very complex process...I have a formset (using jquery formset) in django and I would like to allow users to add forms and input data. Which are all good. The problem is when I try to include ajax. when the input data is changed, there will be a suggestions on what the currency inventory is. The ajax would work on one level only. SO if I add two forms or more forms, inventory number wouldn't show for Here is the code $('#form-inline tbody tr').formset({ addText: 'add link', deleteText: 'remove', prefix: 'positions' }); {% for forms in formset %} $(".{{forms.product.value}}").change( function(){ var symbol = $(".{{forms.product.value}} option:selected").text(); $.ajax({ url: "{% url 'inventory:get_inventory' portfolio_obj.id date %}", type: "GET", data: { 'product': product }, datatype: 'json', success: function(data) { $(".{{forms.id.value}}_ouput").html('Inventory Left'+' ' + data.inventory); }}); }); {% endfor %} html {% for forms in formset %} {{ forms.id }} <tr class="dynamic"> <td style="width:200px" class="{{forms.stock.value}}">{{ forms.product.errors }} {{ forms.product}} </td> <td>{{ forms.inventory.errors }} {{ forms.inventory}} </td> <td>{{ forms.price.errors }} {{ forms.price}} </td> <td style="padding-left: 10px;"> {{ forms.total.value|floatformat:2}} </td> <td style="padding-left: 10px;padding-right: 10px;"> {{ forms.weight.value|floatformat:2}}% </td> {% for op in forms.operation %} <td style="padding-left: 10px;"> {{ op}} </td> {% endfor %} <td>{{forms.operation.errors}} {% if … -
Including a listview in another listview for categories
I'm using a listview that gets me the category-names from one model(Choice) to render it to the choice_list.html On that choice_list.html I'm trying to include another list_view using an absolute url and slug field to only get the data back that belongs to that category. The problem so far is that it includes the second page fabric_list.html but it doesn't bring the data belonging to the view from that html file, instead it has the queryset as from choice_list.html. If I look at fabric_list.html directly, it show's me all the data I'm asking for at the moment, but I can't include it to another html file somehow. Urls.py urlpatterns = [ url(r"^detail/(?P<slug>[\w-]+)/$", views.CategoryListView.as_view(), name="cloth_detail"), ] Views.py class CategoryListView(ListView): model = Choice def get_context_data(self, **kwargs): context = super(CategoryListView, self).get_context_data(**kwargs) context.update({ 'choices': Choice.objects.order_by('category') }) return context class ClothListView(ListView): queryset = Fabric.objects.all() template_name = 'cloth/fabric_list.html' def get_queryset(self): return Fabric.objects.order_by('name') Models.py class Choice(models.Model): category = models.CharField(max_length=120) slug = models.SlugField(max_length=120, unique=True) def get_absolute_url(self): return reverse('cloth:cloth_detail', kwargs={'slug': self.slug}) def __str__(self): return self.category class Fabric(models.Model): AVAILABLE = [('available','available'), ('unavailable','unavailable'),] name = models.CharField(max_length=120) the_choices = models.ManyToManyField(Choice) availablity = models.CharField(choices=AVAILABLE,max_length=120) fabric_cover = ThumbnailerImageField(upload_to='fabric_images',blank=True, default='/placeholder/neutral_book_cover.png', resize_source=dict(size=(200, 200))) def __str__(self): return self.name html example: choice_list.html {% extends "base.html" %} {% block … -
Django rest framework hyperlinkrelatedfield for one table using primary key
I have a table called 'users' and 'location' . users table has a foreign key that relates to location table. I have a users serializer to get the JSON. What would I do to get the hyperlinks for the users table using its primary key. In django rest framework documentation, I couldn't find a solution. I tried using hyperlinkrelatedfield. But still I couldn't achieve this . can someone help me in finding the solution? -
URL pattern name as parameter in template
In my project I have several user types and each of them has separate URL pattern for signup process. I use the same template to render the signup form for each of this types of users and only pass form itself as parameter to template. The problem I'm having is I can't wrap my head around how to dynamically pass url pattern name to template so that every time Submit is clicked appropriate url pattern is called? <form class="form-horizontal" action="{% url 'appropriate_url_pattern' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.non_field_errors }}</p> ... rendering a form here... <input class="btn btn-default" type="submit" </div> </form> -
Trying to create hyperlink from Google Map lat/lon to individual posts Django
I'm currently trying to create hyperlinks to posts that are currently displayed on a google map. The map shows each post based on its latitude and longitude. The code below links to the title of each post, but the issue with that is the title will often times be uppercase or have spaces. Here's what I have: ` <div class="court-listing" id="map-canvas"></div> <script> function initialize() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: {lat: 40.674, lng: -73.945}, zoom: 12, styles: [ {elementType: 'geometry', stylers: [{color: '#242f3e'}]}, {elementType: 'labels.text.stroke', stylers: [{color: '#242f3e'}]}, {elementType: 'labels.text.fill', stylers: [{color: '#746855'}]}, { featureType: 'administrative.locality', elementType: 'labels.text.fill', stylers: [{color: '#d59563'}] }, { featureType: 'poi', elementType: 'labels.text.fill', stylers: [{color: '#d59563'}] }, { featureType: 'poi.park', elementType: 'geometry', stylers: [{color: '#263c3f'}] }, { featureType: 'poi.park', elementType: 'labels.text.fill', stylers: [{color: '#6b9a76'}] }, { featureType: 'road', elementType: 'geometry', stylers: [{color: '#38414e'}] }, { featureType: 'road', elementType: 'geometry.stroke', stylers: [{color: '#212a37'}] }, { featureType: 'road', elementType: 'labels.text.fill', stylers: [{color: '#9ca5b3'}] }, { featureType: 'road.highway', elementType: 'geometry', stylers: [{color: '#746855'}] }, { featureType: 'road.highway', elementType: 'geometry.stroke', stylers: [{color: '#1f2835'}] }, { featureType: 'road.highway', elementType: 'labels.text.fill', stylers: [{color: '#f3d19c'}] }, { featureType: 'transit', elementType: 'geometry', stylers: [{color: '#2f3948'}] }, { featureType: 'transit.station', elementType: 'labels.text.fill', stylers: … -
django imagefield form, how can I display image in the form
I have a Django ImageField model that I would like to add in the form to display image. How can I do that ? I tried this but the answer is incomplete. Display image from ImageField by means of form class PictureWidget(forms.widgets.Widget): def render(self, name, value, attrs=None): html = Template("""<img src="$link"/>""") return mark_safe(html.substitute(link=value)) class EmployeeFaceImageUploadForm(forms.ModelForm): face_image = forms.ImageField(widget=PictureWidget) class Meta: model = Employee fields = ("face_image",) there are errors. Im not sure how to complete this. NameError: name 'Template' is not defined NameError: name 'mark_safe' is not defined AttributeError: 'Template' object has no attribute 'substitute' My main goal is to have image shown in the form which has the ImageField field -
Django Form becomes Invalid When Field is Disabled
I am developing a django application for tracking a list of (music) albums that I've listened to, and when I've listened to them. I am trying to come up with how to render a form for creating a Listen (one of my models) for a specific Album (another model). The relevant part of Listen is very simple: class Listen(models.Model): """A model representing an instance of listening to an album. """ album = models.ForeignKey(Album, on_delete=models.CASCADE) listen_date = models.DateField(default=datetime.date.today, null=True) I have a generic CreateView for creating a view with no pre-populated data: class ListenCreate(generic.edit.CreateView): """View for adding a new Listen. """ model = Listen form_class = ListenForm template_name = 'tracker/generic_form.html' Then ListenForm looks like: class ListenForm(forms.ModelForm): class Meta: model = Listen fields = ['album', 'listen_date'] I've created a view that then is meant to add a listen for a specific album, where the album is deduced from an artist and album name in the URL: class ListenCreateForAlbum(generic.edit.CreateView): """View for creating a listen for a specific album. """ model = Listen form_class = ListenFormForAlbum template_name = 'tracker/generic_form.html' def get_initial(self): initial = copy.copy(self.initial) # Get the initial Album using the artist/album names in the URL initial['album'] = Album.objects.get( name__iexact=unquote_plus(self.kwargs['album_name']), artist__name__iexact=unquote_plus(self.kwargs['artist_name'])) return initial Now, … -
Django how to do aggregation on three tables
I'm doing now educational exercise about django ORM. Need to show total values of orders for particular customers for chosen Supplier on Northwind database, the database diagram can be found here: Northwind database diagram So far I did: QuerySet of ORDER_DETAILS objects that have products made by SUPPLIERS.supplierid = 1 >>> od =OrderDetails.objects.filter(product__in=(Products.objects.filter(supplier=(Suppliers.objects.get(supplierid=1))))) QuerySet of ORDERS objects that have ORDER_DETAILS products made by SUPPLIERS.supplierid = 1, without duplicated ORDERS Objects >>> o = Orders.objects.filter(orderdetails__in=od).distinct() Firstly I'm not sure if those two statements are correct? Secondly I have QuerySet of ORDERS objects that are about products manufactured by chosen supplierid and can't find a way to aggregate it to get total values of orders for particular customers. -
How to hash text with md5 in django? [duplicate]
This question already has an answer here: python django unsalted md5 password hash format 3 answers I need to generate some key or 'token' based in the combination of some email and password sended. I want this in MD5 but I don't know what plugins or libriries or something help me to do this... The equivalent of what I want in php is the next: <?php $email = $_POST['email']; $pass = $_POST['pass']; $token = MD5($email.'-'.$pass); ?> How can I do this in Django? -
Django template renders all my files at once
I am stuck with this issues for a while now. It goes like this: I have a model with lectures. I want that for every lecture to be able to upload multiple files, so I created a model that has FileField. So in my template, I want that for every lecture, the files would be displayed and downloadable as well. The Issue is that every lecture displays all the files that have ever been uploaded in the admin panel. Here is my code: class Lecture(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures') lecture_category = models.IntegerField(choices=((0, "Classes "), (1, "Seminars"), ), default=0) lecture_title = models.CharField(max_length=100) content = models.TextField() files = models.OneToOneField('FileUpload', on_delete=models.CASCADE, null=True, blank=True, ) def __str__(self): return str(self.lecture_category) class FileUpload(models.Model): files = models.FileField(upload_to='documents', null=True, blank=True) def __str__(self): return str(self.files) def file_link(self): if self.files: return "<a href='%s'>download</a>" % (self.files.url,) else: return "No attachment" file_link.allow_tags = True file_link.short_description = 'File Download' <ul> {% regroup lectures by get_lecture_category_display as category_list %} <h3>Lectures</h3> <ul> {% for category in category_list %} <strong> <li>{{ category.grouper }}</li> </strong> <ul> {% for c in category.list %} ............. <li>{{ c.lecture_title }}</li> <li>{{ c.content }}</li> {% for file in files %} {% if file.files %} <li><a href='{{ MEDIA_URL }}{{ file.files.url }}'>download</a></li> … -
Override the default UserAttributeSimilarityValidator error message in django
I am trying to override the default UserAttributeSimilarityValidator error message in django, but i don't know how? -
Is it possible to monkey patch Django's reverse?
Some of our urls include #. These are used for reverse lookup, both using reverse and the {% url template tag (which uses reverse internally). Django 1.8 used to leave it alone, 1.11 now encodes it to %23. Is it possible to put a monkey patch wrapper somewhere and have it be used everywhere without fail? Here's the wrapper I have: def patch_reverse(func): def inner(*args, **kwargs): print "inner reverse" url = func(*args, **kwargs) return url.replace("%23", "#") return inner from django.urls import base base.reverse = patch_reverse(base.reverse) The print statement is so I can see if it's actually running. I've tried putting it in settings, the __init__ of the first installed app, and in the urls of the first installed app. Nothing works. -
Regrouping in a Django template after the first regroup
I'm trying to create a page that has a group of photos, categorized by event, then within the event, by date. Currently, in my view, I am doing this: photos = Photo.objects.all().order_by('event') Then, in my template, I am doing this: {% regroup photos by event as event_list %} {% for event in event_list %} <h6 class="event-title"> {{ event.grouper|safe }} ({{ event.grouper.date }}) </h6> {% for photo in event.list %} <img data-src="{{ photo.thumbnail.url }}" alt="{{ event.grouper|safe }} ({{ event.grouper.date }})" class="img-responsive img-thumbnail" /> {% endfor %} {% endfor %} Is there a way I can group the photos once again by photo.date_captured? Would it be better to do this in the view? -
How do I grab the first objects from a Django queryset?
execution_list = JobExecution.objects.filter(job__name=job_name).order_by('-build_id')[:50] last = execution_list.pop(1) print last.id I've also tried execution_list[0], which throws another queryset error. How do I i just grab the first object from the queryset? I am aware that I can just append .last() to the query, but the problem is I need the full list as well as the first item. What am I doing wrong here? Error: 'QuerySet' object has no attribute 'pop' -
Django Multiple Files Upload Using Ajax without forms
I have an aplication in Django 2.0 where one user can upload many images of their diplomas at the same time but also, I need to make this with ajax so the page will not reload. This is my models.py class diploma(models.Model): user = models.ForeignKey(user, on_delete=models.CASCADE, null=True) diploma=models.ImageField(default='nopic.png', null=True) def __str__(self): return self.diploma And this is my file input in my template upload.html <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <input type="file" id="images" name="images[]" multiple accept="image/jpg,image/png,image/jpeg,image/gif"> <a onclick="uploadWithAjax()"> Upload Images </a> If you notice, there's no Form html tag. Just an 'a' link that calls the function uploadWithAjax(). This is my script with the uploadWithAjax() function function uploadWithAjax() { var files = $('#images')[0].files; $.ajax( { type: "POST", url: "/UploadImages/", data: "", //I DON'T KNOW WHAT DATA I HAVE TO PUT HERE success: function(result) { alert('IMAGES UPLOADED'); } }); } I Think I have to send the 'files' variable in the 'data' atribute of ajax, but I'm not sure becouse there are files and dont normal inputs. Please help. This is my ajax.py file, where I recive the images def UploadImages(request): diplomas = request.FILES['images'] #I don't know if this is correct I didn't finish the view becouse I don't know how to continue or how … -
Using django orm to update a table without deleting relations
I have this two related django models class Item(models.Model): item_nbr = models.IntegerField(primary_key=True) created = models.DateTimeField(auto_now_add=True) item_nbr_desc = models.CharField(max_length=155) class SetItem(models.Model): set_id = models.CharField(primary_key=True, default='', max_length=12) set_nbr = models.IntegerField() items = models.ForeignKey(Item) Im running an script (periodically) to read the Item table from another database and to update the django db database. Im using the django orm framework in this task script.py from app.models import Item item_table = pd.read_sql(__) item_table = some_transformations(item_table.copy()) #I remove all the Items that will be updated Item.objects.filter(item_nbr__in=item_table.item_nbr.unique()).delete() item_table_records = item_table.to_dict('records') item_instances = [] fields = item_table.keys() for record in item_table_records: kwargs = { field: record[field] for field in fields } item_instances.append(Item(**kwargs)) Item.objects.bulk_create(item_instances) # update the new rows the problem is that the setItem table its deleted each time that I delete the Items related (because the on_delete=models.CASCADE behavior). I want to update the items not erasing the setItem related rows, and i don't want to change the on_delete default behavior because just in this script I need to upload a whole table, its possible that i want to delete a Item in another context and i hope that the cascade behavior is working. what can i do? its there a bulk update function that might perform … -
Django REST framework queryset object has no attribute pk
I am building a larger Django-based web app, but I have a blocking issue with an API view that should return some data. I the application I have a model (mail.models.Message) and a matching serializer and viewset. For a reporting feature, I need to get filtered set of results and have therefoer created a seperate rest_framework.views.APIView for the purpose of the reporting. The model is located in one app and the reporting is in another app. Here is the model: class Message(models.Model): class Meta: ordering = ('-timestamp',) get_latest_by = 'timestamp' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) from_address = models.CharField("From", max_length=511, blank=True, default="", db_index=True) from_domain = models.CharField(max_length=255, blank=True, default="", db_index=True) to_address = models.CharField("To", max_length=511, blank=True, default="", db_index=True) to_domain = models.CharField(max_length=255, blank=True, default="", db_index=True) subject = models.TextField(blank=True, default="", db_index=True) client_ip = models.GenericIPAddressField("Client IP", db_index=True, null=True) mailscanner_hostname = models.CharField(max_length=255, db_index=True) spam_score = models.DecimalField(db_index=True, default=0.00, max_digits=7, decimal_places=2) mcp_score = models.DecimalField(db_index=True, default=0.00, max_digits=7, decimal_places=2) timestamp = models.DateTimeField(db_index=True) size = models.FloatField(default=0) token = models.CharField(max_length=255, null=True) mailq_id = models.TextField("Mailqueue identification", null=True) whitelisted = models.BooleanField(db_index=True, default=False) blacklisted = models.BooleanField(db_index=True, default=False) is_spam = models.BooleanField(db_index=True, default=False) is_mcp = models.BooleanField(db_index=True, default=False) is_rbl_listed = models.BooleanField("Is RBL listed", db_index=True, default=False) quarantined = models.BooleanField(db_index=True, default=False) infected = models.BooleanField(db_index=True, default=False) released = models.BooleanField(db_index=True, default=False) def __str__(self): … -
Django Markdownx preview shown only after reloading page
I want django-markdownx to show maths formulas and equations and therefore integrated 'python-markdown-math' with it. Everything works as usual apart from the fact that I need to reload the page to get a preview of the typed mathematical formulas or symbols. The issue is only occurring when I type mathematical formula not others texts or upload image. Maths related stuffs (like $$..$$) seems to get skipped in preview and is shown only when I reload/refresh the page. Parts of my code: # settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' MARKDOWNX_MARKDOWN_EXTENSIONS = [ 'mdx_math', ] MARKDOWNX_UPLOAD_MAX_SIZE = 5 * 1024 * 1024 # 5 MB MARKDOWNX_SERVER_CALL_LATENCY = 1000 MARKDOWNX_IMAGE_MAX_SIZE = { 'size': (500, 500), 'quality': 90, 'crop': True, } MARKDOWNX_MEDIA_PATH = 'markdownx/' # models.py class MyModel(models.Model): content = MarkdownxField() @property def get_content(self): return mark_safe(markdownify(self.content)) # in my template <head> <title>MathJax TeX Test Page</title> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [["$","$"],["\\(","\\)"]]} }); </script> <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> </script> </head> <body> <form method="POST" action=""> {% csrf_token %} {{ form }} <input type="submit" name="" value="submit"> </form> {{ form.media }} </body> </html> Please help me find the problem which is causing such a behaviour. Note: Reloading … -
functools has no 'lru_cache' installing Django
$ pip install django Collecting django Using cached Django-2.0.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-capC7C/django/setup.py", line 32, in <module> version = __import__('django').get_version() File "django/__init__.py", line 1, in <module> from django.utils.version import get_version File "django/utils/version.py", line 61, in <module> @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-capC7C/django/ -
How can I formulate this ForeignKey scheme?
I'm finding some difficulty resolving this problem in designing my Django models. The essential setup is a bipartitie graph (allowing for parallel edges), where the vertices on both sides of the graph express a lot of common logic. I am having trouble creating a model which allows for both vertices to be shared within the same database, and allows querying of all the edges incident to a vertex. I considered using an inheritance scheme, wherein vertices in a partition inherit from a parent Vertex class, but I kept tripping up, and really started perseverating on whether Django had some hidden, native and concise means of doing this. The current setup is about: class Vertex(models.Model): PARTITION_CHOICES = ( ('a': 'type a'), ('b': 'type b') ) partition = models.CharField(choices=PARTITION_CHOICES) # A bunch of other logic... class Edge(models.Model): ref_a = models.ForeignKey(Vertex, limit_choices_to={'partition': 'a'}, related_name='edges') ref_b = models.ForeignKey(Vertex, limit_choices_to={'partition': 'b'}, related_name='edges') # More logic... The obvious issue here is that both these foreign keys have the same related name, therefore clash. Tips from the wise? -
SQL error when running Django Migration
Environment: Ubuntu/Apache I am getting the following error when running a migration. Below the error is the migration file. The migration runs fine on a dev machine, but is erroring out when trying to deploy. The error is coming up within the Django code, so I don't have a lot to go on in order to sort this out. A summary of the migration is that it is removing null=True from three ManyToManyField fields and is changing the upload_to value for the remaining fields shown. Django (1.11.9) and psycopg2 (2.7.3.2) versions match on both machines. Is it possible to tell from this error message which field (if a specific field is the problem) is causing the error? Running migrations: Applying manager.0035_auto_20180119_1138...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 244, … -
Django Pipeline 1.6 & Sass
Javascript compresses fine and straight CSS works. But SASS doesn't seem to work at all What I'm using 1.7.11 Django 1.6.13 django-pipeline 2.7.9 Python I installed ruby-sass on debian apt-get -y install ruby-sass And it runs from the commandline using the default SASS_BINARY command /usr/bin/env sass -h Usage: sass [options] [INPUT] [OUTPUT] Description: Converts SCSS or Sass files to CSS. Here are my django settings.py pipeline settings # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' STATICFILES_DIRS = ['assets'] STATIC_ROOT = '/app/static' PIPELINE_STORAGE = STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', ) PIPELINE = { 'PIPELINE_ENABLED': True, 'COMPILERS': ('pipeline.compilers.sass.SASSCompiler'), 'JAVASCRIPT': { 'application': { 'source_filenames': ( 'assets/javascripts/*', ), 'output_filename': 'javascripts/application.js', } }, 'STYLESHEETS': { 'application': { 'source_filenames': ( 'assets/stylesheets/application.scss' ), 'output_filename': 'stylesheets/application.css', 'extra_context': { 'media': 'screen,projection', }, }, } } -
All my files are rendered instead of selected ones
So I have this FileField which allows users to upload many files in the admin panel. Everything is fine. But when I want to see the files in the template, for each lecture, then each each lecture displays all the files from other lectures as well. Each lecture is supposed to show its particular uploaded files. So my guess its either the view, either the template. <ul> {% regroup lectures by get_lecture_category_display as category_list %} <h3>Lectures</h3> <ul> {% for category in category_list %} <strong> <li>{{ category.grouper }}</li> </strong> <ul> {% for c in category.list %} ............. <li>{{ c.lecture_title }}</li> <li>{{ c.content }}</li> {% for file in files %} {% if file.files %} <li><a href='{{ MEDIA_URL }}{{ file.files.url }}'>download</a></li> {% endif %} {% endfor %} {% endfor %} </ul> {% endfor %} </ul> </ul> def courses(request, slug): query = Course.objects.get(slug=slug) context = {'courses': Course.objects.filter(slug=slug), 'lectures': query.lectures.order_by('lecture_category'), 'files': FileUpload.objects.order_by('files'), } return render(request, 'courses/courses.html', context)