Pass a file path as a URL parameter in Django - django

I'm using Django to create a webapp. When a user press on a certain button, it needs to pass a file path as parameter and a string parameter to one of my views. I can't simply use the parameter in the URL since the path contains several '/'. The way I have it setup right now is as follows:
parameters.py
class FilePathConverter:
regex = '^[/]'
def to_python(self, value):
value=str(value)
return value.replace("?", "/")
def to_url(self, value):
value=str(value)
return value.replace("/", "?")
urls.py
from django.urls import path
from . import views
from django.contrib import admin
from django.views import generic
from django.urls import path, register_converter
from . import converters, views
register_converter(converters.FilePathConverter, 'filepath')
urlpatterns = [
path('', views.index, name='webpanel-index'),
path('controlserver/<filepath:server_path>/<str:control>', views.index, name='controlserver'),
]
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Server
from django.contrib.auth.decorators import login_required
import subprocess
def controlserver(request, server_path, control):
if request.POST:
subprocess.call(['bash', server_path, control])
return render(request, 'index.html')
However, with this method, I get this error:
Reverse for 'controlserver' with keyword arguments '{'server_path': 'rien/', 'control': 'start'}' not found. 1 pattern(s) tried: ['controlserver/(?P<server_path>[^/]+)/(?P<control>[^/]+)$']

you can use Slug to resolve this patterns by :
from django.utils.text import slugify
path('controlserver/use slug .....', views.index, name='controlserver'),
but you need to put slug at views and templates So check this list of slug and pk :
https://github.com/salah-cpu/migration/blob/master/PATH_slug_pk

Related

My url not reading my function in views.py in DJANGO (found similar question not able to trace my issue)

mysite/urls.py
from django.contrib.auth import views
from django.views.generic.base import TemplateView
urlpatterns = [
url('update_db/(<dbname>)/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
url('mysite/login/', auth_views.LoginView.as_view(),name='login'),
url(r'^fetch/',include('polls.urls')),
url('mysite/logout/$', auth_views.logout, name='logout'),
]
polls.urls.py
from django.conf.urls import url
from . import views
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
urlpatterns = [
url('update_db/(?P<dbname>\w+)/$', login_required(views.MyView.get), name='x'),
url('', login_required(views.IndexView.as_view())),
]
fetch.html
<td>click</td>
polls/views.py
from django.shortcuts import render
from django.views.generic import TemplateView , ListView
from django.views.generic.edit import UpdateView
# Create your views here.
from django.http import HttpResponse
from .models import Item , DbRestorationLogDetails
class MyView(UpdateView):
logger.error('Something went wrong!')
print "THANKS FOR UPDATING"
template_name='fetch.html'
model = DbRestorationLogDetails
fields =['verification_status']
def get(self,request, dbname):
usname=request.user
print usname
print dbname
if request.method == "GET":
dblog = DbRestorationLogDetails.objects.get(dbname=dbname)
dblog.verification_status = 'Verified'
print dblog.verification_status
dblog.save()
#.update(dblogdetails.verification_status = 'Verified')
return HttpResponseRedirect(request.GET.get('next'))
NOTE: NOT able to reach to MyView.get() and no db update happening. I assume my code is not able to read my function.

page not found error in Django using a filter query {return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')}

I am making my first django practice project I have a view called PostListview :
from django.shortcuts import render
from django.utils import timezone
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from blog.models import Post, Comment
from blog.forms import PostForm,CommentForm
from django.urls import reverse_lazy
from django.views.generic import(TemplateView,ListView,DetailView,CreateView,UpdateView,
DeleteView)
class AboutView(TemplateView):
template_name = 'about.html'
class PostListView(ListView):
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
I have this in in the urls:
from django.conf.urls import url
from blog import views
urlpatterns = [
url(r'^$',views.PostListView.as_view(), name= 'post_list'),
And this is the template which is calling this view.
<li class="navbar-brand bigbrand" >My Tech Blog</li>
This view is also set as the default home view and it opens fine at the time i open the site url (localhost) but when I am clicking "My Tech blog " it gives a 404 error.
This is the main urls.py :
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from django.contrib.auth import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',include('blog.urls')),
url(r'accounts/login/$',views.login, name = 'login'),
url(r'accounts/logout/$',views.logout, name = 'logout',kwargs={'next_page':'/'}),
]
Just change
url(r'^$',views.PostListView.as_view(), name= 'post_list'),
with
url(r'',views.PostListView.as_view(), name= 'post_list'),

Custom template in django form wizard - NameError

I am trying to create custom templates for a simple contact form as per the django docs but I am getting a NameError. Looks like a simple issue but I can't figure it out. Any help will be greatly appreciated. The error message is:
"NameError at /contact/
name 'wizardcustomtemplate' is not defined"
where 'wizardcustomtemplate' is the app. Here is my code:
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from wizardcustomtemplate.forms import SubjectForm, SenderForm, MessageForm
from wizardcustomtemplate.views import ContactWizard
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^contact/$', ContactWizard.as_view(FORMS)),
)
views.py
import os
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.core.context_processors import csrf
from django.contrib.formtools.wizard.views import SessionWizardView
from django.contrib.formtools.wizard.views import WizardView
from django.core.files.storage import FileSystemStorage
from django.core.files import File
FORMS = [("0", wizardcustomtemplate.forms.SubjectForm),
("1", wizardcustomtemplate.forms.SenderForm),
("2", wizardcustomtemplate.forms.MessageForm)
]
TEMPLATES = {"0": "wizardcustomtemplate/subject.html",
"1": "wizardcustomtemplate/sender.html",
"2": "wizardcustomtemplate/message.html"
}
class ContactWizard(SessionWizardView):
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, **kwargs):
form_data = process_form_data(form_list)
return render_to_response('wizardcustomtemplate/thanks.html', {'form_data': form_data})
def process_form_data(form_list):
form_data = [form.cleaned_data for form in form_list]
return form_data
forms.py
from django import forms
class SubjectForm(forms.Form):
subject = forms.CharField(max_length = 100,initial='Wizard')
class SenderForm(forms.Form):
sender = forms.EmailField(initial='abcd#efgh.org')
class MessageForm(forms.Form):
message = forms.CharField(initial='How r u?')
The form wizard works fine if I don't use the custom templates (FORMS, TEMPLATES etc.) Please let me know if you need additional information.
Solved it by adding import wizardcustomtemplate in views.py as suggested by #Rohan.

Where to store my index.html and index view for a non-static Django homepage

I'm creating a Django project and currently have 3 apps (products, questions and choices) - I've got them all functioning separately/together as I'd like and am using namespaces and include as part of my urls (my urls.py given below...)
### urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic import TemplateView
admin.autodiscover()
urlpatterns = patterns('',
url(r'^products/', include('products.urls', namespace='products')),
url(r'^questions/', include('questions.urls', namespace='questions')),
url(r'^choices/', include('choices.urls', namespace='choices')),
url(r'^admin/', include(admin.site.urls)),
)
Now I'm looking to add an index page (accessible at localhost:8000/) that will allow me to access all models created. I'm happy with my views.py...
## views.py
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from products.models import Product
from questions.models import Question
from choices.models import Choice
class IndexView(generic.ListView):
template_name = 'index.html'
context_object_name = 'latest_product_list'
def get_queryset(self):
return Product.objects.all()
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['questions'] = Question.objects.all()
context['choices'] = Choice.objects.all()
return context
What I'd like to know is, what is the most sensible combination of urls.py entry, positioning of views.py and location of index.html to allow me to show a combination of my models on the landing page?
Thanks,
Matt
Create another app (I tend to name it home). That way, your home app can import models from products, questions and choices.
App layout
home/urls.py
home/views.py
home/templates/index.html
Include your home urls just like your other apps (but don't use a prefix)
url(r'^', include('home.urls', namespace='home')),

Django: How can i get the url of a template by giving the namespace?

While i'm rendering a template i would like to retrieve the url of the template by giving the namespace value and not the path. For example instead of this:
return render(request, 'base/index.html', {'user':name})
i would like to be able to do the following:
from django.shortcuts import render
from django.core.urlresolvers import reverse
return render(request, reverse('base:index'), {'user':name})
but the above produces an error. How can i do it? Is there any way to give the namespace to a function and get the actual path?
Extended example:
- urls.py
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
url(r'^', include('base.urls', namespace='base')),
)
- app base: urls.py
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('base.views',
url(r'^/?$', 'index', name='index'),
)
- app base: views.py
from django.shortcuts import render
from django.core.urlresolvers import reverse
def homepage(request):
'''
Here instead of 'base_templates/index.html' i would like to pass
something that can give me the same path but by giving the namespace
'''
return render(request, 'base_templates/index.html', {'username':'a_name'})
Thanks in advance.
Template names are hard coded within the view. What you can also do is that you can pass the template name from the url pattern, for more details see here:
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('base.views',
url(r'^/?$', 'index',
{'template_name': 'base_templates/index.html'},
name='index'),
)
Then in view get the template name:
def index(request, **kwargs):
template_name = kwargs['template_name']