Revserse for 'files' with arguments '(' ',)' nout found. 1 pattern(s) tried: - django-templates

I am new to django and trying to understand foreign key relationships and how to access db information related to another. I am using django 2.0.
I keep receiving error: Revserse for 'files' with arguments '(' ',)' nout found. 1 pattern(s) tried:
Traceback:
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e,
request)
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request,
*callback_args, **callback_kwargs)
File "/home/travis/atom/My_Django_stuff/ixia_results/results/views.py" in
files
30. return render(request, 'results/results_files.html', context=
{'directory':directory})
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/shortcuts.py" in render
36. content = loader.render_to_string(template_name, context,
request, using=using)
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/template/loader.py" in render_to_string
62. return template.render(context, request)
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/template/backends/django.py" in render
61. return self.template.render(context)
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/template/base.py" in render
175. return self._render(context)
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/template/base.py" in _render
167. return self.nodelist.render(context)
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/template/base.py" in render
943. bit = node.render_annotated(context)
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/template/base.py" in render_annotated
910. return self.render(context)
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/template/loader_tags.py" in render
155. return compiled_parent._render(context)
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/template/base.py" in _render
167. return self.nodelist.render(context)
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/template/base.py" in render
943. bit = node.render_annotated(context)
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/template/base.py" in render_annotated
910. return self.render(context)
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/template/loader_tags.py" in render
67. result = block.nodelist.render(context)
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/template/base.py" in render
943. bit = node.render_annotated(context)
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/template/base.py" in render_annotated
910. return self.render(context)
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/template/defaulttags.py" in render
447. url = reverse(view_name, args=args, kwargs=kwargs,
current_app=current_app)
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/urls/base.py" in reverse
88. return iri_to_uri(resolver._reverse_with_prefix(view, prefix,
*args, **kwargs))
File "/home/travis/anaconda3/envs/MyDjangoMysqlEnv/lib/python3.6/site-
packages/django/urls/resolvers.py" in _reverse_with_prefix
632. raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /1/files/
Exception Value: Reverse for 'files' with arguments '('',)' not found. 1
pattern(s) tried: ['(?P<dir_pk>[^/]+)\\/files\\/$']
urls.py:
from results import views
app_name = 'results'
urlpatterns = [
path('', views.index, name='index'),
path('<dir_pk>/files/', views.files, name='files'),
path('results/<pk>/files/data/', views.data, name='data'),
]
views.py:
from django.shortcuts import render, HttpResponse, get_object_or_404,
redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from ixLoad_app.ixiapi import create_results_dir_db
from results.models import Directory, Files, Data
def index(request):
if request.POST.get('import'):
print('I made it here')
return redirect('results:index')
else:
result = Directory.objects.all()
print('I am here')
return render(request, 'results/index.html', context={'result':
result})
def files(request, dir_pk):
directory = get_object_or_404(Directory, pk=dir_pk)
#result = Files.objects.get(pk=pk)
print('directory id :', dir_pk, directory)
return render(request, 'results/results_files.html', context=
{'directory':directory})
models.py:
from django.db import models
class Directory(models.Model):
name = models.CharField(max_length=100, default='foobar', unique=True)
results_path = models.CharField(max_length=254, default='foobar',
null=True)
date_field = models.DateField(max_length=100, default=None, null=True)
class Meta:
verbose_name_plural = 'directory'
ordering = ['date_field']
def __str__(self):
return self.name
class Files(models.Model):
csv_filename = models.CharField(max_length=100, default="foobar")
directory = models.ForeignKey(Directory, on_delete=models.CASCADE,
related_name='files')
class Meta:
verbose_name_plural = 'files'
ordering = ['csv_filename']
def __str__(self):
return self.csv_filename
index.html:
<!DOCTYPE html>
{% extends "base.html" %}
{% block body_block %}
<br>
<h5>{{ info|cut:'passing' }}</h5><br>
<div class="container">
{% if result %}
<form method="POST">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
<div class="mb-4">
<input type="submit" value="Update Results"
name="update" id="update_submit" class="btn btn-
primary">
</div>
</form>
<table class="table table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">Date</th>
<th scope="col">ID</th>
<th scope="col"><div class="text-center">Results
Directory</div></th>
</tr>
</thead>
{% for dir in result %}
<tbody>
<tr class="">
<td>{{ dir.date_field }}</td>
<td>{{ dir.id }}</td>
<td>
<a href="{% url 'results:files' dir.pk %}">
<div class="text-center">{{ dir.name }}
</div>
</a>
</td>
</tr>
</tbody>
{% endfor %}
</table>
{% else %}
<form method="POST">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
<div class="mb-4">
<input type="submit" value="Import Results"
name="import" id="import_submit" class="btn btn-
primary">
</div>
</form>
{% endif %}
</div>
{% endblock %}
results_files.html:
<!DOCTYPE html>
{% extends "base.html" %}
{% block breadcrumb %}
<li class="breadcrumb-item">Results Directory</li>
<li class="breadcrumb-item">Result Files</li>
<li class="breadcrumb-item active">{{ results.csv_filename }}</li>
{% endblock %}
{% block body_block %}
<div class="container">
<table class="table table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">Directory</th>
<th scope="col"><div class="">Files</div></th>
</tr>
</thead>
{% for file in directory.files.all %}
<tbody>
<tr class="">
<td>{{ file.directory.name }}</td>
<td>
<a href="{% url 'data' file.pk %}">
<div class="">{{ file.csv_filename }}</div>
</a>
</td>
</tr>
</tbody>
{% endfor %}
</table>
</div>
I have looked through many of the same questions but and have found no resolution to my issue. I am sure it may be something simple but have spent many hours maybe someone can see something obvious I am doing wrong.

In your view you write:
def files(request, dir_pk):
directory = get_object_or_404(Directory, pk=dir_pk)
#result = Files.objects.get(pk=pk)
print('directory id :', dir_pk, directory)
return render(request, 'results/results_files.html', context=
{'directory':directory})
So that means that the context contains a directory variable, not a dir variable. So dir.pk can not be processed in the template, and will default to the string_if_invalid (by default '', the empty string) in the template engine settings). Since dir.pk results in the empty string, it can no longer find the relevant URL. We should thus use directory.pk instead, and preferably use a named parameter in results_files.html:
<!DOCTYPE html>
{% extends "base.html" %}
{% block breadcrumb %}
<li class="breadcrumb-item">Results Directory</li>
<li class="breadcrumb-item">Result Files</li>
<li class="breadcrumb-item active">{{ results.csv_filename }}</li>
{% endblock %}
{% block body_block %}
<div class="container">
<table class="table table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">Directory</th>
<th scope="col"><div class="">Files</div></th>
</tr>
</thead>
{% for file in directory.files.all %}
<tbody>
<tr class="">
<td>{{ file.directory.name }}</td>
<td>
<a href="{% url 'data' file.pk %}">
<div class="">{{ file.csv_filename }}</div>
</a>
</td>
</tr>
</tbody>
{% endfor %}
</table>
</div>
I would also advise to use a path converter [Django-doc] in your URL pattern:
# urls.py
from results import views
app_name = 'results'
urlpatterns = [
path('', views.index, name='index'),
path('<int:dir_pk>/files/', views.files, name='files'),
path('results/<int:pk>/files/data/', views.data, name='data'),
]

Related

Vue - change/set a variable value in template

Working in Vue, I am trying to set a variable based on another variable within the template. This is within a loop, and I need to set a value that can be used in 'next' iteration of the loop (to change the way a table is rendered, based on the variable).
I have the following:
<template>
...
<tbody v-for="(lo,index) in learn" :key="lo.id">
<tr>
<td colspan="2">LO{{index+1}} {{lo.attributes.field_lo}}</td>
<td v-if="!nextDist"> </td>
</tr>
<tr>
<td>
<div
v-for="(pass,index) in lo.attributes.field_pass"
:key="index"
>P{{pStep()}} {{pass}}</div>
</td>
<td>
<div
v-for="(merit,index) in lo.attributes.field_merit"
:key="index"
>M{{mStep()}} {{merit}}</div>
</td>
<td v-if="lo.attributes.field_dshared && next" ***SET VALUE OF this.next*** rowspan="3">
<span class="has-text-weight-bold">D{{dStep()}} </span>{{lo.attributes.field_dist}}
</td>
<td v-else-if="!lo.attributes.field_dshared" ***SET VALUE of this.next*** ><span class="has-text-weight-bold">D{{dStep()}} </span>{{lo.attributes.field_dist}}
</td>
***else render nothing***
</tr>
</tbody>
</template>
export default {
name: "SpecUnit",
components: {
EssentialContent
},
data() {
return {
unit: "",
learn: "",
nextDist: "",
next: ""
};
},
...
}
What I'd like to be able to do is set the value of 'next' (this.next) so that when the loop iterates, I can check to see if I should which of the I should render or render nothing (because we are 'rowspanning').
I've tried computed and methods, but can't seem to get this working. I've looked to use Vue.set, but I'm struggling with that.
I'm still new to Vue, so any help would be greatly appreciated.
Thanks
It looks like Florian Reuschel had a similar problem and already solved it (although with some caveats)
Let's say we have something like that:
<!-- List.vue -->
<ul>
<li v-for="id in users" :key="id">
<img :src="getUserData(id).avatar"><br>
🏷️ {{ getUserData(id).name }}<br>
🔗 {{ getUserData(id).homepage }}
</li>
</ul>
His approach is to use a helper renderless component with a scoped slot
const Pass = {
render() {
return this.$scopedSlots.default(this.$attrs)
}
}
and then
<!-- List.vue -->
<ul>
<Pass v-for="id in users" :key="id" :metadata="getUserData(id)">
<li slot-scope="{ metadata }">
<img :src="metadata.avatar"><br>
🏷️ {{ metadata.name }}<br>
🔗 {{ metadata.homepage }}
</li>
</Pass>
</ul>
If you take a look at the comments section on his blog article, you will see other approaches, too. For example, you can use an expression inside v-bind
<li v-for="id in users" :key="id" :demo="item = getUserData(id)">
<img :src="item.avatar" /><br />
🏷️ {{ item.name }}<br />
🔗 {{ item.homepage }}
</li>

Datatables: Issue with font-awesome icon in header being displayed on new line

I am creating an admin view into user details on a website. From that view I want the admin to be able to edit certain columns from certain tables, but not all columns. To indicate which columns are editable I am using a font-awesome icon to show that column is editable. JS will be applied to then allow the admin to do any editing. However, I'm stuck with the formatting simply not working as expected. It keeps showing the icon on a new line creating the ugly table as shown here:
HTML
I have tried several ways to load the table so it will be rendered properly but nothing I have tried has worked. The HTML is loaded through a twig which is received from an AJAX call:
<table class="user-members-data">
<thead>
<tr>
{% for key in user_details|keys %}
<th>{{ key }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
<tr>
{% for value in user_details %}
<td>{{ value }}</td>
{% endfor %}
</tr>
</tbody>
</table>
jQuery
On return the Datatable is initialised but before initialisation the edit icons are added to the relevant column titles. The editable columns are returned as a separate json_encoded array which is checked against (jquery_data.editable_columns):
$( 'table.user-members-data thead th' ).each( function(){
var header = $( this ).html()
if( jQuery.inArray( header, response.jquery_data.editable_columns ) !== -1 ){
$( this ).html( header + ' <i class="fas fa-pencil-alt" edit="' + header + '"></i>' )
}
})
$( 'table.user-members-data' ).DataTable( {
'scrollX' : true,
'ordering' : false,
'paging' : false,
'info' : false,
'searching': false
} )
Load icon through HTML
Alternatively I have tweaked the twig to include the edit icon and to load the Datatable without jQuery adding the icons:
{% for key in user_details.table|keys %}
<th>
{{ key }}
{% if key in user_details.editable_columns %}
<i class="fas fa-pencil-alt" edit="{{ key }}"></i>
{% endif %}
</th>
{% endfor %}
This resulted in the exact same issue with the new lines.
columns.adjust()
Elsewhere I have seen advice to use this after the draw of the Datatables to fix any width issues. This has not worked for me either.
It feels as if Datatable is simply not seeing the icon at all when setting the width of the column?
Thank you to andrewjames for pointing the way in the comments.
The solution came by wrapping the title in a span with display:block; and white-space:no-wrap; added as styling.
$( 'table.user-members-data thead th' ).each( function(){
var header = $( this ).html()
if( jQuery.inArray( header, response.jquery_data.editable_columns ) !== -1 ){
$( this ).html( '<span style="display:block; white-space:nowrap;">' + header + ' <i class="fas fa-pencil-alt" edit="' + header + '"></i></span>' )
}
})

Render image in left and right side of the screen alternatively

I want to render image in left and right side of the screen alternatively, dynamically in django template. I am not sure how to render it, like if it is 0th for loop counter the image should appear on the left of the screen, for the next iteration the image should render in right and so on.
This is my requirement
This is what I have achieved
Code below
HTML
{% block content %}
<!-- Banner -->
<div class="banner">
<div class="container-fluid banner-content">
<h3>{{page.banner_head}}</h3>
{{page.banner_desc|richtext}}
</div>
</div>
<section class="solution-section">
<div class="container-fluid">
{% for i in page.solutions.all %}
<div class="row pb-5">
<!-- Image -->
<div class="col-md-6">
<div class="solution-image">
<figure class="text-center">
<h6>{{ i.img_text }}</h6>
</figure>
{% image i.sol_img original as img %}
<img src="{{ img.url }}" class="img-fluid solution-index-image" alt="{{ img.alt }}">
</div>
</div>
<!-- Text -->
<div class="col-md-6 solution-desc">
<h5>{{i.sol_head}}</h5>
{{i.sol_desc|richtext}}
learn more
</div>
</div>
{% endfor %}
</div>
</section>
{% endblock %}
models.py
class SolutionPage(Page):
banner_head = models.CharField('Banner Title', blank=True, max_length=255)
banner_desc = RichTextField('Banner Description', blank=True)
content_panels = Page.content_panels + [
MultiFieldPanel([
FieldPanel('banner_head'),
FieldPanel('banner_desc'),
], heading='Banner Section'),
InlinePanel('solutions', label='Solution Details'),
]
class Solution(Orderable):
sol_img = models.ForeignKey(
'wagtailimages.Image',
null = True,
blank = True,
on_delete = models.SET_NULL,
related_name = '+',
verbose_name = 'Solution Image',
)
img_text = models.CharField('Image Text', blank=True, max_length=255)
sol_head = models.CharField('Solution Heading', max_length=100, blank=True)
sol_desc = RichTextField('Solution Description', blank=True)
sol_link = models.CharField('Button Link', max_length=255, blank=True)
page = ParentalKey('SolutionPage', related_name='solutions')
panels = [
ImageChooserPanel('sol_img'),
FieldPanel('img_text'),
FieldPanel('sol_head'),
FieldPanel('sol_desc'),
FieldPanel('sol_link')
]
Check odd/even in the template with {% if forloop.counter|divisibleby:"2" %}.

Can not display my comment lists for a post

i have tried to add and display comments list in my django post_detail template yet its not displaying...
This is my comment models...
class Comment(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE)
content = models.TextField()
active = models.BooleanField(default=True)
created = models.DateTimeField(blank=True, auto_now=False, auto_now_add=True)
class Meta:
ordering = ['created']
def __str__(self):
return "Comment by {} on {}".format(self.author, self.content)
i then added the comment model into my post module as follows...
from comments.models import Comment
class Post(models.Model):
comment = models.ForeignKey(Comment, blank=True, null=True)
Here is my post views.py
def post_detail(request, slug):
post = get_object_or_404(Post, slug=slug)
return render(request, "blog/post_detail.html", {
'post':post,
})
comments = post.comment.filter(active=True)
if request.method == 'POST':
#A comment was posted
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid() and user.is_authenticated():
#Create new comment but dont save to DataBase first
new_comment = comment_form.save(commit = False)
#Assigns the current instance to the comment
new_comment.post = post
#Saves the comment to DataBase
new_comment.save()
else:
comment_form = CommentForm()
return render(request, "blog/post_detail.html", {
'post':post,
'comments': comments,
'comment_form': comment_form
})
finally i tried to display these into my template yet i couldn't get the list of comments for each post
<!-- displays available comments for this post -->
{% for comment in comments %}
<div class="media d-block d-md-flex">
<img class="d-flex rounded-circle avatar z-depth-1-half mb-3 mx-auto" src="https://mdbootstrap.com/img/Others/documentation/img (2)-mini.jpg" alt="Avatar">
<div class="media-body text-center text-md-left ml-md-3 ml-0">
<h5 class="mt-0 font-weight-bold blue-text">comment {{ forloop.counter }} by {{ comment.author }} {{ comment.created }}</h5>
{{ comment.content|linebreaks }}
</div>
</div>
{% endfor %}
</div>
</div>
<!--/.Comments-->
{% endif %}
<!-- Displays comment form for registered users else link visitors to registeration page -->
{% if user.is_authenticated %}
{% if new_comment %}
<h4><span class="badge badge-pill green">your comment has been added<i class="fa fa-check" aria-hidden="true"></i></span></h4>
{% else %}
<form method="POST">
{% csrf_token %}
<div class="form-group shadow-textarea">
<label for="exampleFormControlTextarea6">Add a comment</label>
<textarea class="form-control z-depth-1" id="exampleFormControlTextarea6" rows="3" placeholder="Write something here...">
{{ comment_form.as_p }}
</textarea>
</div>
<div class="text-center mt-4">
<button class="btn btn-info btn-md" type="submit" value="add comment">submit</button>
</div>
</form>
{% endif %}
{% else %}
<h4>You have to register in order to comment this post </h4>
{% endif %}
please i need help getting this to display
it have eaten up my day.
I finally found the error...
i was rendering the post_detail template before the comment_form
here is my final code
def post_detail(request, slug):
post = get_object_or_404(Post, slug=slug)
comments = Comment.object.filter(active=True)
if request.method == 'POST':
#A comment was posted
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid() and user.is_authenticated():
#Create new comment but dont save to DataBase first
new_comment = comment_form.save(commit = False)
#Assigns the current instance to the comment
new_comment.post = post
#Saves the comment to DataBase
new_comment.save()
else:
comment_form = CommentForm()
return render(request, "blog/post_detail.html", {
'post':post,
'comments': comments,
'comment_form': comment_form
})

How do i dynamically/evaluate via expression json property in django template

reading in a JSON for sport. using a partial for matchup markup.
awayteam and home team for most part share identical markup but the JSON properties which I have no control are such below:
<div class="away {{game.awayTeam_last_name|slugify}}">
<a href="#" title="{{game.awayTeam_first_name}} {{game.awayTeam_last_name}}">
<span class="{{league}}-logo"></span>
<span class="city">{{game.awayTeam_first_name}}</span>
{% if game.event_status != "pre-event" %}
<span title="score">{{game.awayTeam_score}}</span>
{% else %}
<span title="record entering game">(0-0)</span>
{% endif %}
</a>
</div>
<span>#</span>
<div class="home {{game.homeTeam_last_name|slugify}}">
<a href="#" title="{{game.homeTeam_first_name}} {{game.homeTeam_last_name}}">
<span class="{{league}}-logo"></span>
<span class="city">{{game.homeTeam_first_name}}</span>
{% if game.event_status != "pre-event" %}
<span title="score">{{game.homeTeam_score}}</span>
{% else %}
<span title="record entering game">(0-0)</span>
{% endif %}
</a>
</div>
is there a way to shrink/refactor the above like some expression valuator to make home and away passed via a variable.
didn't answer own question but i did get Data guys to better format the data, so became..
awayteam: { first_name:'', last_name:'', score:'' }
hometeam: { first_name:'', last_name:'', score:'' }
allowing me to shrink in half the template =)