I need your help. I am a django beginner and I am unable to use linkcolumn from django-tables2. I am really disappointed because I am sure it's really simple but until now, it doesn't work. I thank you in advance for the time granted to my problem and beg your pardon if it's stupid of simplicity ;-)
Sum up:
index.html returns a django-tables2 table and everything is ok
I want to change datas of column "name" to hyperlink (using linkcolumn) with target ".../Audit/1/" where 1 comes from pk of the clicked row of course
An error occurs:
NoReverseMatch at /fr/Audit/
Reverse for 'detail' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Request Method: GET
Request URL: http://localhost:8000/fr/Audit/
Django Version: 1.6.5
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'detail' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Exception Location: /opt/myenv/local/lib/python2.7/site-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 452
Python Executable: /opt/myenv/bin/python2.7
Python Version: 2.7.6
Audit/models.py
# -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from MyParam.models import MyModel, MyMptt
from mptt.models import TreeForeignKey
from organization.models import Org
class Grid(MyMptt):
name = models.CharField(max_length = 45, verbose_name=_(u"grille d'audit"))
parent = TreeForeignKey('self', limit_choices_to={'act': True}, related_name='children', null=True, blank=True, verbose_name=_(u"parent"))
class MPTTMeta:
order_insertion_by = ['name']
class Meta:
verbose_name = _(u"grille d'audit")
verbose_name_plural = _(u"grilles des audits")
def __unicode__(self):
return unicode(self.name)
Audit/urls.py
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from Audit import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<grid_id>\d+)/$', views.detail, name='detail'),
url(r'^(?P<grid_id>\d+)/vote/$', views.vote, name='vote'),
url(r'^(?P<grid_id>\d+)/report/(?P<report_id>\d+)$', views.report, name='report'),
)
Audit/tables.py
# -*- coding: utf-8 -*-
import django_tables2 as tables
from django_tables2.utils import A
from Audit.models import Grid
class GridTable(tables.Table):
name = tables.LinkColumn('detail', args=[A('pk')])
class Meta :
model = Grid
# add class="paleblue" to <table> tag
attrs = {"class": "paleblue"}
VISU = ("id", "name", "parent")
sequence = VISU
fields = VISU
Audit/views.py
# -*- coding: utf-8 -*-
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from django_tables2 import RequestConfig
"""
from django.views import generic
"""
from Audit.models import Grid, Item, Assessment, Report, ReportContent
from Audit.tables import GridTable
from organization.models import Org
def index(request):
"""
audit_grid_list = Grid.objects.all().order_by('name')[:5]
context = {'audit_grid_list': audit_grid_list}
return render(request, 'Audit/index.html', context)
"""
table = GridTable(Grid.objects.all())
RequestConfig(request).configure(table)
RequestConfig(request, paginate={"per_page": 25}).configure(table)
return render(request, "Audit/index.html", {"table": table})
def detail(request, grid_id):
org_list = Org.objects.all().order_by('name')[:5]
grid = get_object_or_404(Grid, pk=grid_id)
return render(request, 'Audit/detail.html', {'grid': grid,'org_list': org_list})
Audit/templates/index.html
{# Audit/templates/index.html #}
{% load render_table from django_tables2 %}
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="{{ STATIC_URL }}django_tables2/themes/paleblue/css/screen.css" />
</head>
<body>
{% render_table table %}
</body>
</html>
Audit/templates/detail.html
<h1>{{ grid.name }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'Audit:vote' grid.id %}" method="post">
{% csrf_token %}
<!-- test pour choix du service -->
<label for="org">Choix de la cible de l'audit</label>
<select name="org" id="org">
{% for firm in org_list %}
<option value="{{ firm.id }}">{{ firm.name }}</option>
{% endfor %}
</select><br>
{% for item in grid.Item_grid.all %}
<h2>{{ item.name }}</h2>
{% for assess in item.Assessment_item.all %}
<input type="checkbox" name="item{{ forloop.parentloop.counter }}[]" id="item{{ forloop.parentloop.counter }}[]" value="{{ assess.id }}" />
<label for="item{{ forloop.parentloop.counter }}">{{ assess.name }}</label><br />
{% endfor %}
{% endfor %}
<input type="submit" value="Vote" />
</form>
Your URL regex has a named group, so grid_id should be a keyworded argument. Use
name = tables.LinkColumn('detail', args={'grid_id': A('pk')})
Related
I want to show the topic title in the website template url link on django 3.
currently opening the topic id number.
for example : http://localhost:8000/detay/4
for example : http://localhost:8000/detay/2
for example : http://localhost:8000/detay/1
but I want to do it this way
for example : http://localhost:8000/detay/1/this-is-topic-title
or
for example : http://localhost:8000/detay/3/this-is-topic-title
.
.
.
views.py
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import *
# Create your views here.
def index(request):
girdiler = Deneme1Model.objects.filter(yuklemeTarihi__lte=timezone.now()).order_by('-yuklemeTarihi')
context ={
'girdiler':girdiler
}
return render(request, 'deneme1Uygulama/index.html', context)
def ekle(request):
return render(request, 'deneme1Uygulama/ekle.html')
def detay(request, pk):
girdiler = Deneme1Model.objects.filter(pk=pk)
context ={
'girdiler':girdiler
}
return render(request, 'deneme1Uygulama/detay.html', context)
def sayfaYok(request):
return render(request, 'deneme1Uygulama/404.html')
urls.py
from django.urls import path
from .import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.index, name='index'),
path('ekle/', views.ekle, name='ekle'),
path('detay/<int:pk>', views.detay, name='detay'),
path('404/', views.sayfaYok, name='sayfaYok'),
]
urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
from django.db import models
from django.utils import timezone
# Create your models here.
class Deneme1Model (models.Model):
baslik = models.CharField(max_length=50, verbose_name='BAŞLIK')
aKaydi = models.CharField(max_length=50, verbose_name='A KAYDI')
dosyaYukle = models.FileField(upload_to='media', verbose_name='DOSYA YÜKLE')
yuklemeTarihi =models.DateTimeField(default =timezone.now)
yayinKontrol = models.BooleanField(default=True)
def __str__(self):
return self.baslik
detay.html
{% block content %}
<div class="row">
{% if girdiler %}
{% for girdi in girdiler %}
<div class="col-12 d-flex justify-content-center">
<div class="card w-100">
<img class="card-img-top img-fluid umaxhe20" src=" {{ girdi.dosyaYukle.url }} " alt="Card image cap">
<div class="card-body">
<h5 class="card-title"> {{ girdi.baslik }} </h5>
<p class="card-text"> {{ girdi.aKaydi }} </p>
{{ girdi.yuklemeTarihi }}
</div>
</div>
</div>
{% endfor %}
{% else %}
{% url 'sayfaYok' %}
{% endif %}
</div>
{% endblock content %}
Not tested but probably something like this
urls.py
urlpatterns = [
path('detay/<int:pk>', views.detay, name='detay'),
path('detay/<int:pk>/<string:topic>', views.detay_topic, name='detay-topic'),
]
views.py
def detay_topic(request, pk, topic):
...
i'm creating a 'create an account view ' which the user can store his image, name ,lastname ....
on my database the name,lastname... are registred but the image is not stored.why?
in models.py:
from django.db import models
class information(models.Model):
name=models.CharField(max_length=50)
lastname=models.CharField(max_length=50)
email=models.CharField(max_length=50)
password=models.CharField(max_length=50)
img=models.ImageField(upload_to='media',blank=True)
in forms.py:
from app1.models import information
from django import forms
class create_form(forms.ModelForm):
class Meta:
model=information
fields=[
'name',
'lastname',
'email',
'password',
'img'
]
in views.py:
def create_view(request,*args,**kwargs):
my_form=create_form(request.POST or None)
if my_form.is_valid():
my_form.save()
print(my_form.cleaned_data['img'])**#########print :None**
context={"form":my_form}
return render(request,'first create.html',context )
in templates:
<main>
<section>
<form action="" method="Post"> {% csrf_token %}
{{form.as_p}}
<input type="submit" value="save"/>
</form>
</section>
</main>
url.py
from django.contrib import admin
from django.urls import path
from app1 import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('home/', views.firstview, name='home'),
path('Create/', views.create_view, name='create'),
path('home/main/', views.homeview, name='main')
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
You made two mistakes here. First of all, you need to pass request.FILES to the form:
from django.shortcuts import redirect
def create_view(request,*args,**kwargs):
if request.method == 'POST':
my_form=create_form(request.POST, request.FILES)
if my_form.is_valid():
my_form.save()
return redirect('some-view')
else:
my_form = create_form()
context={'form': my_form}
return render(request,'first create.html', context)
and furthermore you need to specify enctype="multipart/form-data" in your <form> tag:
<main>
<section>
<form action="" method="Post" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="save"/>
</form>
</section>
</main>
Note that you better implement the Post/Redirect/Get pattern [wiki] and thus make a redirect(..) [Django-doc] in case of a succesful POST request.
i am trying to populate existing data in the database into a dropdownlist
where i want just to make the data appear inside the dropownlist.
when i run the system it display the below error :
DoesNotExist at / testmodel3 matching query does not exist. Request
Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 2.1.7
Exception Type: DoesNotExist Exception Value: testmodel3 matching
query does not exist.
it says that the error is at line 14
tmn3 = testmodel3.objects.get(name = tmn)
i create class in models.py
map the page in the url.py
create form
create a template
create a function in views.py.
models.py
class testmodel3(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return str(self.name)
url.py
from django.contrib import admin
from django.urls import path
from.views import *
urlpatterns = [
path('admin/', admin.site.urls),
path('', home),
]
forms.py
from django import forms
from .models import *
class drodownForm(forms.ModelForm):
class Meta:
model = testmodel
fields = ('name',)
home.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST">{% csrf_token %}
<table>
<tr><td>mouhafazat name:</td>
<td>
<select name = "dropdwn1">
{% for testmodel in testmodel3name %}
<option value="{{ testmodel3.name }}">{{ testmodel3.name }}</option>
{% endfor %}
</select>
</td>
<td><input type="submit" value="click" /></td>
</tr>
</table>
</form>
</body>
</html>
views.py
from django.shortcuts import render
from django.http import HttpResponse
from testapp.models import *
from testapp.forms import drodownForm
def home(request):
testmodel3name = testmodel3.objects.all()
print(testmodel3name)
tmn = request.POST.get('dropdwn1')
if request.method =='GET':
form = drodownForm()
else:
tmn3 = testmodel3.objects.get(name = tmn)
print("test for dropdown")
return render(request,'./home.html',{'form': form, 'testmodel3name': testmodel3name})
i expect to view the stored data in a dropdown list
I am trying to build a simple landing page in Django that will allow users to sign up for an email newsletter. I am using this cookie cutter template - https://github.com/Parbhat/cookiecutter-django-foundation - because it integrates Foundation 6 from the jump.
The challenge is that the form fields are not showing in the template. Any help would be appreciated.
My models.py is:
class Subscribe(models.Model):
email = models.EmailField()
subscription_status = models.BooleanField(default=True)
create_date = models.DateTimeField(auto_now_add = True, auto_now = False)
update_date = models.DateTimeField(auto_now_add = False, auto_now = True)
def __unicode__(self):
return self.email
My forms.py is:
from django import forms
from .models import Subscribe
class SubscribeForm(forms.ModelForm):
class Meta:
model = Subscribe
fields = ('email',)
My views.py is:
from django.shortcuts import render
from subscribers.forms import EmailForm, SubscribeForm
from .models import Subscribe
def home(request):
form = SubscribeForm(request.POST or None)
if form.is_valid():
new_join = form.save(commit=False)
#we might need to do something here.
email = form.cleaned_data['email']
new_join_old, created = Subscribe.objects.get_or_create(email=email)
#new_join.save()
context = {"form": form}
template = "pages/home.html"
return render(request, template, context)
And my template is:
{% extends "base.html" %}
{% load foundation_formtags %}
{% block content %}
<section class="hero">
<!-- HERO SECTION -->
<div class="homebox">
<div class="wrap">
<p>Lorem Ipsum</p>
<form class="form" method="post" action=""> {% csrf_token %}
{{ form|as_foundation }}
<input type='submit' value='Subscribe' class='btn' />
</form>
</div>
</div>
</section>
My urls.py is:
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.conf.urls import url
from . import views
from subscribes.views import home
urlpatterns = [
url(r'^$', home, name='home'),
]
Thanks!
Ive been Playing around with django to create an asset management app and have hit a wall on the file upload to model instance behaviour.
I am attempting to use the ModelForm class in Forms.py
Basically im pretty certain that form.save() is not writing my uploaded file to disk to update my model instance.
Do I have to write a form.save definition into my AssetForm ? or have I missed something else.
Appreciate any help.
My project is built around the Polls tutorial https://docs.djangoproject.com/en/1.8/intro/tutorial01/ and the minimal file upload tutorial at Need a minimal Django file upload example.
Here is my model .py
class Category(models.Model):
category_text = models.CharField(max_length=200)
def __str__(self): # __unicode__ on Python 2
return self.category_text
class Asset(models.Model):
asset_text = models.CharField(max_length=200)
asset_tag = models.CharField(max_length=200)
asset_category = models.ForeignKey(Category)
cert_date = models.DateTimeField('cert published')
def __str__(self): # __unicode__ on Python 2
return self.asset_text
def was_certed_recently(self):
return self.cert_date >= timezone.now() - datetime.timedelta(days=365)
was_certed_recently.admin_order_field = 'cert_date'
was_certed_recently.boolean = True
was_certed_recently.short_description = 'Certified recently?'
docfile = models.FileField(upload_to='documents')
Here is my forms.py
from django import forms
from django.forms import ModelForm
from polls.models import Asset
class AssetForm(ModelForm):
class Meta:
model = Asset
fields = '__all__'
Here is my views.py
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.http import HttpResponse
#from django.template import RequestContext, loader
from django.shortcuts import get_object_or_404, render
from django.http import Http404
from polls.models import Asset
from polls.forms import AssetForm
def list(request, asset_id):
# Handle file upload
ID = asset_id
p = get_object_or_404(Asset, pk = asset_id)
if request.method == 'POST':
form = AssetForm(request.POST, request.FILES, instance= p )
if form.is_valid():
form.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('list', args=(p.id,)))
else:
form = AssetForm() # A empty, unbound form
# Load documents for the list page
documents = p
# Render list page with the documents and the form
return render_to_response(
'polls/list.html',
{'documents': documents, 'ID': ID, 'form': form},
context_instance=RequestContext(request )
)
def index(request):
latest_asset_list = Asset.objects.order_by('-cert_date')[:]
context = {'latest_asset_list': latest_asset_list}
return render(request, 'polls/index.html', context)
url.py
from django.conf.urls import url
from . import views
urlpatterns = [
#url(r'^/list/$', 'list', name='list'),
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<asset_id>[0-9]+)/$', views.list, name='list'),
# ex: /polls/5/results/
url(r'^(?P<asset_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<asset_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
Finally my list.html template
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Minimal Django File Upload Example</title>
</head>
<body>
<!-- List of uploaded documents -->
{% if documents %}
<ul>
<p>Current Doc.</p>
<li>{{ documents.docfile.name }}</li>
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
<ul>
{{ ID }}
<!-- Upload form. Note enctype attribute! -->
<form action="{% url 'list' ID %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</html>
You're doing various things twice. For example, at the start of your function, you get an Asset into p and then you get the same one into a. Why?
More significantly, in the is_valid() block you create a new Asset object just from the uploaded file, with no other data from the form, but then you save the form itself which should update the existing Asset. This might be the cause of your problem - you should remove the lines with docfile and just save the form.