Reverse for 'reg/{{post.pk}}/' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

94 views
Skip to first unread message

meInvent bbird

unread,
May 24, 2016, 8:53:51 AM5/24/16
to Django users
Reverse for 'reg/{{post.pk}}/' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

i follow django girl web , expect to go to /reg to fill a form and press save button then go to web /reg/<a number> 

it has error 

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

registration.html

{% block content %}

    <h1>New user registration</h1>

    <form method="POST" class="post-form">{% csrf_token %}

        {{ form.as_p }}

        <button type="submit" class="save btn btn-default" onClick="window.location.href='{% url 'reg/{{post.pk}}/'  %}'">Save</button>

    </form>

{% endblock %}

urls.py

from django.conf.urls import include, url

from . import views



urlpatterns = [

    url(r'^reg/$', views.post_new, name='post_new'),

    url(r'^reg/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),

]

views.py

from .forms import PostForm

from django.shortcuts import render

from django.template.loader import get_template



def post_new(request):

    form = PostForm()

    return render(request, 'registration.html', {'form': form})



def post_detail(request, pk):

    post = get_object_or_404(Post, pk=pk)

    if request.method == "POST":

        form = PostForm(request.POST, instance=post)

        if form.is_valid():

            post = form.save(commit=False)

            post.author = request.user

            post.ProjectName = request.ProjectName

            post.UserName = request.UserName

            post.Company = request.Company

            post.Contact = request.Contact

            post.InitialPassword = request.InitialPassword

            post.UserType = request.UserType

            post.BusinessType = request.BusinessType

            post.published_date = timezone.now()

            post.save()

            return redirect('registration.html', pk=post.pk)

    else:

        form = PostForm(instance=post)


    return render(request, 'registration.html', {'form': form})

models.py

from django.db import models

from django.utils import timezone
from django.apps import AppConfig

import csv
import os.path

USERTYPE = (  
    ('Cyberport Tenant', 'Cyberport Tenant'),
    ('SmartSpace User', 'SmartSpace User'),
    ('Cyberport Incubate', 'Cyberport Incubate'),
    ('Collaboration Center Subscriber', 'Collaboration Center Subscriber'),
    ('Cyberport Alumnus', 'Cyberport Alumnus'),
    ('Technology Partner', 'Technology Partner'),
    ('HKOSUG', 'HKOSUG'),
    ('Others', 'Others'),
)


BUSINESSTYPE = (  
    ('Building', 'Building'),
    ('Data Analysis', 'Data Analysis'),
    ('Digital Entertainment', 'Digital Entertainment'),
    ('Education', 'Education'),
    ('Games', 'Games'),
    ('Gaming', 'Gaming'),
    ('ICT', 'ICT'),
    ('Marketing', 'Marketing'),
    ('Social Media', 'Social Media'),
    ('Others', 'Others'),
)


class MyAppConfig(AppConfig):
    name = 'src.my_app_label'

    def ready(self):
        post_migrate.connect(do_stuff, sender=self)


class Post(models.Model):

    author = models.ForeignKey('auth.User')

    Email = models.CharField(max_length=70)
    ProjectName = models.CharField(max_length=70)
    UserName = models.CharField(max_length=70)
    Company = models.CharField(max_length=70)
    Contact = models.CharField(max_length=70)
    InitialPassword = models.CharField(max_length=70)
    UserType = models.CharField(max_length=30, choices=USERTYPE)
    BusinessType = models.CharField(max_length=30, choices=BUSINESSTYPE)
    #UserType = models.ChoiceField(choices=USERTYPE, required=True )
    #BusinessType = models.ChoiceField(choices=BUSINESSTYPE, required=True )

    #ProjectName = models.TextField()

    created_date = models.DateTimeField(default=timezone.now)

    published_date = models.DateTimeField(blank=True, null=True)



    def publish(self):

        self.published_date = timezone.now()
        isexist = os.path.isfile('newusers.csv') 
        with open('/home/martin/Downloads/site1/site1/reg/newusers.csv', 'a') as csvfile:
          fieldnames = ['name','email address','project','initial password','userType','contact','businessType','company']
          writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
          if isexist == false:
             writer.writeheader()
          writer.writerow({'name': UserName, 'email address': Email, 'project': ProjectName, 'initial password': InitialPassword,'userType': UserType, 'contact': Contact, 'businessType': BusinessType, 'company': Company,})


        self.save()



    def __str__(self):

        return self.title

forms.py

from django import forms



from .models import Post


USERTYPE = (  
    ('Cyberport Tenant', 'Cyberport Tenant'),
    ('SmartSpace User', 'SmartSpace User'),
    ('Cyberport Incubate', 'Cyberport Incubate'),
    ('Collaboration Center Subscriber', 'Collaboration Center Subscriber'),
    ('Cyberport Alumnus', 'Cyberport Alumnus'),
    ('Technology Partner', 'Technology Partner'),
    ('HKOSUG', 'HKOSUG'),
    ('Others', 'Others'),
)


BUSINESSTYPE = (  
    ('Building', 'Building'),
    ('Data Analysis', 'Data Analysis'),
    ('Digital Entertainment', 'Digital Entertainment'),
    ('Education', 'Education'),
    ('Games', 'Games'),
    ('Gaming', 'Gaming'),
    ('ICT', 'ICT'),
    ('Marketing', 'Marketing'),
    ('Social Media', 'Social Media'),
    ('Others', 'Others'),
)



class PostForm(forms.ModelForm):



    #if form.is_valid():

     #post = form.save(commit=False)

     #post.author = request.user

     #post.published_date = timezone.now()

     #post.save()m

    class Meta:

        model = Post

        fields = ('Email', 'ProjectName', 'UserName', 'Company', 'Contact', 'InitialPassword','UserType','BusinessType')
#fields = ('title', 'text',)
        UserType = forms.ChoiceField(choices=USERTYPE, required=True )
        BusinessType = forms.ChoiceField(choices=BUSINESSTYPE, required=True )

    

meInvent bbird

unread,
May 24, 2016, 8:53:51 AM5/24/16
to Django users
would like to press save button then call post_detail and append to csv, 

it return error

<button type="submit" class="save btn btn-default" onClick="window.location.href='{% url 'reg/{{post.pk}}'  %}'">Save</button>

Reverse for 'reg/{{post.pk}}/' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []



    ('Technology Partner', 'Technology Partner'),
    ('Others', 'Others'),
)


BUSINESSTYPE = (  
    ('Building', 'Building'),
    ('Data Analysis', 'Data Analysis'),


forms.py

    ('Technology Partner', 'Technology Partner'),
    ('Others', 'Others'),
)


BUSINESSTYPE = (  
    ('Building', 'Building'),
    ('Data Analysis', 'Data Analysis'),
)



class PostForm(forms.ModelForm):



    #if form.is_valid():

     #post = form.save(commit=False)

     #post.author = request.user

     #post.published_date = timezone.now()

     #post.save()m

    class Meta:

        model = Post

        fields = ('Email', 'ProjectName', 'UserName', 'Company', 'Contact', 'InitialPassword','UserType','BusinessType')
#fields = ('title', 'text',)
        UserType = forms.ChoiceField(choices=USERTYPE, required=True )
        BusinessType = forms.ChoiceField(choices=BUSINESSTYPE, required=True )


registration.html

{% block content %}

    <h1>New user registration</h1>

    <form method="POST" class="post-form">{% csrf_token %}

        {{ form.as_p }}

        <button type="submit" class="save btn btn-default" >Save</button>
    </form>

{% endblock %}
    

ludovic coues

unread,
May 24, 2016, 9:07:25 AM5/24/16
to django...@googlegroups.com
It should work better this way:
<button type="submit" class="save btn btn-default"
onClick="window.location.href='{% url 'post_detail' pk=post.pk
%}'">Save</button>

the url template tag take a route name, not an url as it first argument.
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/4c6f022c-9222-4991-b6f7-9574b9386c16%40googlegroups.com.
>
> For more options, visit https://groups.google.com/d/optout.



--

Cordialement, Coues Ludovic
+336 148 743 42

meInvent bbird

unread,
May 25, 2016, 9:23:49 PM5/25/16
to Django users
what is the url template tag take a route name?

so far, error is Reverse for 'views.post_detail' with arguments '()' and keyword arguments '{u'pk': ''}' not found. 0 pattern(s) tried: []

meInvent bbird

unread,
May 25, 2016, 9:46:26 PM5/25/16
to Django users


On Tuesday, May 24, 2016 at 9:07:25 PM UTC+8, ludovic coues wrote:

ludovic coues

unread,
May 26, 2016, 10:24:44 AM5/26/16
to django...@googlegroups.com
Have you done the django tutorial ? It help a lot when starting with django.

Your problem come from site1/urls.py . `include(admin.site.urls)` work
because you import admin. `include(site1.reg.urls)` cannot work
because site1 is not defined.

Also, the djangogirls tutorial [1] have a great chapter about form.

[1] http://tutorial.djangogirls.org/en/django_forms/
> https://groups.google.com/d/msgid/django-users/c1208d34-7a9c-41cc-b42b-e2021b6c168f%40googlegroups.com.

meInvent bbird

unread,
May 26, 2016, 9:24:22 PM5/26/16
to Django users
this works, because i set ROOT_URLCONF

since it work, it can go to registration.html by reading urls.py in directory reg


INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'site1',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'site1.reg.urls'

meInvent bbird

unread,
May 26, 2016, 9:41:51 PM5/26/16
to Django users

i succeed to make it trigger something when press button after read tutorial again

however got error,

WSGIRequest' object has no attribute 'Email'




def post_new(request):

    #post = get_object_or_404(Post)

    #form = PostForm()

    #return render_to_response(request, 'registration.html', {'pk': 12})

    #return render(request, 'registration.html', {'form': form})
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)

            #post.author = request.user

            post.Email = request.Email

            post.ProjectName = request.ProjectName

            post.UserName = request.UserName

            post.Company = request.Company

            post.Contact = request.Contact

            post.InitialPassword = request.InitialPassword

            post.UserType = request.UserType

            post.BusinessType = request.BusinessType

            post.published_date = timezone.now()

            post.publish()
            #self.published_date = timezone.now()
            return redirect('post_detail', pk=post.pk)
            #isexist = os.path.isfile('newusers.csv') 

            #with open('/home/martin/Downloads/site1/site1/reg/newusers.csv', 'a') as csvfile:

             #fieldnames = ['name','email address','project','initial password','userType','contact','businessType','company']

             #writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

             #if isexist == 0:

              #writer.writeheader()

             #writer.writerow({'name': request.user, 'email address': request.Email, 'project': request.ProjectName, 'initial password': request.InitialPassword,'userType': request.UserType, 'contact': request.Contact, 'businessType': request.BusinessType, 'company': request.Company,})



            return redirect('hello.html', pk=post.pk)
    else:
        form = PostForm()
    return render(request, 'registration.html', {'form': form})

meInvent bbird

unread,
May 26, 2016, 9:58:23 PM5/26/16
to Django users
so far, the link do not have querystring, the error is WSGIRequest' object has no attribute 'Email'

meInvent bbird

unread,
May 26, 2016, 10:47:18 PM5/26/16
to Django users
i succeed to save to csv, 

i use post instead of request

but it is quite odd, it do not have request in query string in link

writer.writerow({'name': post.UserName, 'email address': post.Email, 'project': post.ProjectName, 'initial password': post.InitialPassword,'userType': post.UserType, 'contact': post.Contact, 'businessType': post.BusinessType, 'company': post.Company,})

ludovic coues

unread,
May 27, 2016, 3:37:49 AM5/27/16
to django...@googlegroups.com
You have a query string when you do GET request.
The form is sending a POST request, with the data in the body of the request.
> https://groups.google.com/d/msgid/django-users/8d54d3e3-88cc-4847-ac8b-38edfcfa4bfe%40googlegroups.com.

Florian Schweikert

unread,
May 30, 2016, 8:33:32 AM5/30/16
to django...@googlegroups.com
On 24/05/16 08:46, meInvent bbird wrote:
> <button type="submit" class="save btn btn-default"
> onClick="window.location.href='{% url 'reg/{{post.pk}}' %}'">Save</button>

You cannot access a variable like this in a template.
There is also no point in trying to access an url using url providing an
url. Your url pattern is called 'post_detail'.

Try something like:
{% url 'post_detail' pk=post.pk %}

More information is available in the docs:
https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#url

--
Florian
Reply all
Reply to author
Forward
0 new messages