Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Forms - What does (?P\d+)/$ signify? Help please
I am new to django. I was creating forms in django with the help of an online tutorial. I didnot understand a line in the urls.py file. Can someone explain what exactly it means? from django.conf.urls import url from . import views from . views import BlogListView, BlogDetailView, BlogCreateView urlpatterns = [ url(r'^$', views.BlogListView.as_view(), name='post_list'), url(r'^post/(?P<pk>\d+)/$', BlogDetailView.as_view(), name='post-detail'), url(r'^post/new/$', BlogCreateView.as_view(), name='post_new'), url(r'^post/(?P<pk>\d+)/edit/$', BlogUpdateView.as_view(), name='post_edit'), ] I did not understand the following line: url(r'^post/(?P<pk>\d+)/$' What does (?P\d+)/$ signify? Help please -
Conditionally pass model decleration in Meta to django ModelForm
Is there a way to conditionally pass the model class to the meta in a model form before instantiation / the metaclass magic happens? I have a lot of "specification" fields that need to have update / create views and they all have the same fields excluded. Hence, I can just set excludes and the model form will do the rest for all of them. Thus, I only really need one form / one update form for all of this. It'd be exceedingly redundant to define update and create views for all of these... With this I can just use one update and one create view for all of them passing the form_class in my urls.py as BaseUpdate(form_class=MyBaseForm(ModelClass)) and BaseCreate(form_class=MyBaseForm(ModelClass)) -
Django gets all checkboxes values, checked or un-checked
Using Django's User model, I have the following template: {% for account in accounts %} <tr> <td> {{ account.username }} </td> <td> <input type=checkbox name=account value="{{ account.id }}" {% if account.is_active %}checked{% endif %}> </td> </tr> {% endfor %} which shows the status of each account and the user may update them. In the views: accounts = request.POST.getlist('account') # This will get only the `checked` ones for account in User.objects.filter(id__in=accounts): if account is checked: # Only hypothetical ... account.is_active = True else: account.is_active = False account.save() Questions: How do I retrieve ALL checkboxes, checked or un-checked? How can the retrieved list contains the status of each account, so that I can set the account's is_active field accordingly? -
Rendering the same html in Django
I am trying to set up navigation with Django, however, each time I try to navigate it goes back to the same page again. Please help, any advice will be appreciated. Thank you! views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect #from django.contrib.auth import views as auth_views #from . import views # Create your views here. def login(request): return render(request, 'login.html') def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() #username = form.cleaned_data.get('username') #raw_password = form.cleaned_data.get('password1') #user = authenticate(username=username, password=raw_password) #login(request, user) return redirect('/templates') else: form = UserCreationForm() return render(request, 'templates/signup_form.html', {'form': form}) in Project the file called urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^login/', include('website.urls')), url(r'^signup/', include('website.urls')), url(r'^admin/', admin.site.urls), ] in the app website urls.py from django.conf.urls import url from django.contrib.auth.views import login from . import views # urlpatterns = [ url(r'^', views.login, name=''), url(r'^login/', login, {'template_name': 'templates/login.html'}), url(r'^signup/', views.signup, name = 'signup') #url(r'^login/$', index,{{'template_name': 'templates/index.html' }}) ] -
what is web deployment,
I am learning web development. But am very confused about the term web deployment. What does web deployment actually mean. what's the difference between web deployment and getting a website to run online? I am a django newbie and have just deployed a small app on heroku. TIA -
cannot integrate third party markdown extension into django-wiki markdown
I'm trying to use this extension: https://github.com/aleray/mdx_semanticdata with django-wiki's markdown but I am unable to get it to work (though it works in the python/django shell just fine). (django-wiki: https://github.com/django-wiki/django-wiki/) Adding this line %%dc:author :: Sherry Turkle | Turkle's%% %%dc:title::Second Self%% was an early book on the social aspects of computation. to a django-wiki article (with mdx_semanticdata and semanticdata as extensions, see settings.py at the bottom) gives me <p><span>Turkle's</span> <span>Second Self</span> was an early book on the social aspects of computation."</p> Whereas doing import markdown text = "%%dc:author :: Sherry Turkle | Turkle's%% %%dc:title::Second Self%% was an early book on the social aspects of computation." html = markdown.markdown(text, ['semanticdata']) print(html) In the python shell gives me: <p><span content="Sherry Turkle" property="dc:author">Turkle's</span> <span content="Second Self" property="dc:title">Second Self</span> was an early book on the social aspects of computation.</p> Notice the spans from the python shell have content and property tags. I would like to have the content and property tags in django-wiki. Can anyone help? My settings.py: WIKI_MARKDOWN_KWARGS = { 'extensions': [ 'semanticdata', 'footnotes', 'attr_list', 'headerid', 'extra', 'mdx_semanticdata', ], 'safe_mode': False, } -
r.article_set.all() does not make a query through .objects whereas returns a query
In Django's tutorial,Django at a glance | Django documentation | Django r.article_set.all() does not make a query through .objects whereas returns a query. It's quick example: #mysite/news/models.py from django.db import models class Reporter(models.Model): full_name = models.CharField(max_length=70) def __str__(self): # __unicode__ on Python 2 return self.full_name class Article(models.Model): pub_date = models.DateField() headline = models.CharField(max_length=200) content = models.TextField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): # __unicode__ on Python 2 return self.headline Working in Django shell, # Create a new Reporter. >>> r = Reporter(full_name='John Smith') # And vice versa: Reporter objects get API access to Article objects. >>> r.article_set.all() <QuerySet [<Article: Django is cool>]> Return a QuerySet,even if a Managers is not called. I search through the documentation and learn that A Manager is the interface through which database query operations are provided to Django models. At least one Manager exists for every model in a Django application. So I can understand: >>> Article.objects.all() <QuerySet [<Article: Django is cool>]> Django adds a Manager with the name objects to every Django model class. Managers | Django documentation | Django As for r.article_set.all(), it does not make a query through .objects whereas returns a query. article_set is neither the attribute of Reporter or django.db.models.Model … -
How to write dynamic webpage in django
I am new in djnago and want to design dynamic website with the help of django framework. In my website website I have written a code in html where I defined a text box for an IP address and summary details to fetch the details from server and display on webpage, Here user first enter the IP address then click on submit button after that this will call you script which is present on django framework and script will execute command on server and display it's output then again execute another command and display it's output, so i'm looking a similar way of execution on django. Here except displaying commands output on server prompt it should publish output on webpage but one after another execution of commands on server. Please see below HTML code snippet. <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Netconf</title> </head> <body> <h3>Netconf Blast Command Generation:</h3> <table> <tr width=100%> IP Address <h4> <form method="POST">{% csrf_token %} Enter IP Address: <input type="text" name="cmd_string" id="cmd_string"/> </form> </h4> </tr> <tr> <br> <input type="submit" value="Submit"/> </tr> </table> <br> <table> <tr> <details> <summary>Cli show:</summary> <p>{{output}}</p> </details> </tr> <br> <tr> <details> <summary>Netconf show:</summary> <p>{{netconfoutput}}</p> </details> </tr> <br> <tr> <details> <summary>List of Netconf command:</summary> <p>{{netconfcommand}}</p> … -
Create AWS S3 Buckets in my webapplcation users
I am developing an Django Web Application. Is there a way that I can create buckets in my users AWS S3 accounts using Boto3. -
Django Authentication - Created CustomUser and now I can't login anymore
I've put together a custom user model to store a few new fields and to keep the DB/UI models separate. I can create the user fine from a python shell and validate the password: >python manage.py shell -c " from itemdb.models import MyUser; user = MyUser.objects.create_user('mypass','AD','Joe','Smith','1233','joe@smith.com'); print user.check_password('mypass'); " True But when I point my app to the new "MyUser" model, I can't login via the web form anymore: Please enter a correct userid and password. Note that both fields may be case-sensitive. I created a new "users" table with the required fields and the hashed password values are being stored in the "password" field. I've written a few functions that may override the default functions, like "get", "save" etc. I'm guessing the issue is in there somewhere. My other guess, is somehow the form is not passing the right credentials. I know the easiest and cleanest way is to extend the model -- I've read all the posts & tutorials. But I want to keep the DB & UI code separate as much as possible. I think I'm close. What's missing? Any ideas as to why the validation isn't working via the website? Thanks. Postgres 9.6 Python 2.7 Django … -
Django is not rendering CSS
I'm having trouble doing an signup page with Django. I wanted to know how to put the form page with the models and have it inserted into the database. I have the index.html and I would like to connnect it with the models. Meaning, when i hit submit it will take all the data to the database. Any help would be appreciated. I'm new to Django. Thank you! views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect #from . import views # Create your views here. def index(request): return render(request, 'index.html') def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'signup.html', {'form': form}) settings.py Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.11.7. import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*o7vg-hqbcx9bqh6fcg^daw21(#2bb8ik14-^02e!nus*y##&c' # SECURITY WARNING: don't run with debug turned on in production! DEBUG … -
Django nvalid literal for int() with base 10.
I have two models Post and Category . models.py class Post(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) content = models.TextField() posted = models.DateField(db_index=True, auto_now_add=True) category = models.ForeignKey('blog.Category') def __unicode__(self): return '%s' % self.title class Category(models.Model): title = models.CharField(max_length=100, db_index=True) slug = models.SlugField(max_length=100, db_index=True) def __unicode__(self): return '%s' % self.title views.py def post_view(request, slug, slug1): return render(request, 'post_view.html', { 'post': get_object_or_404(Post, category=slug, slug=slug1) }) def category_view(request, slug): category = get_object_or_404(Category, slug=slug) return render(request, 'cat_view.html', { 'category': category, 'posts': Post.objects.filter()[:5] }) urls.py url(r'category/(?P<slug>[-\w]+)/$', views.category_view, name='cat_view'), url(r'category/(?P<slug>[-\w]+)/(?P<slug1>[-\w]+)/$', views.post_view, name='post_view'), and finally the templates category.html {% block content %} {% if posts %} <ul> {% for post in posts %} <li><a href="{% url 'blog:post_view' slug=post.category slug1=post.slug %}"> {{ post.title }}</a></li> {% endfor %} </ul> {% else %} <p>There are no post yet in the {{ category.title }} category ! </p> {% endif %} {% endblock %} post.html {% block content %} <h1>{{ post.title }}</h1> <p>{{ post.content }}</p> <small>{{ post.posted }}</small> {% endblock %} The error is raised whenever I try to access a specific Post through the links on the category.html. At first I thought it was because of the regex in the urls.py , but it seems to be a problem … -
Understanding a traceback error [ DJANGO / PYTHON ]
I am trying to understand a traceback error. See below. What im doing is Manipulating PDF Form Fields with Python. Im using pdftk and fdfgen, just Manipulating PDF Form Fields with Python im following this example http://evanfredericksen.blogspot.mx/2014/03/manipulating-pdf-form-fields-with-python.html Traceback: File "/home/myproject/webapps/app/lib/python2.7/Django-1.11.7-py2.7.egg/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/myproject/webapps/app/lib/python2.7/Django-1.11.7-py2.7.egg/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/myproject/webapps/app/lib/python2.7/Django-1.11.7-py2.7.egg/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/myproject/webapps/app/app/home/views.py" in main 113. fields = get_fields(pdf_path) File "/home/myproject/webapps/app/app/home/views.py" in get_fields 67. data_string = check_output(call).decode('utf8') File "/usr/lib64/python2.7/subprocess.py" in check_output 568. process = Popen(stdout=PIPE, *popenargs, **kwargs) File "/usr/lib64/python2.7/subprocess.py" in __init__ 711. errread, errwrite) File "/usr/lib64/python2.7/subprocess.py" in _execute_child 1327. raise child_exception Exception Type: OSError at /pdf_test/1/ Exception Value: [Errno 2] No such file or directory My views code is: def combine_pdfs(list_of_pdfs, outfile): ''' Use pdftk to combine multiple pdfs into a signle pdf ''' call = ['pdftk'] call += list_of_pdfs call += ['cat', 'output'] call += [outfile] print(" ".join(call)) try: data_string = check_output(call).decode('utf8') except IOError: raise PdftkNotInstalledError('Could not locate PDFtk installation') return outfile def get_fields(pdf_file): ''' Use pdftk to get a pdf's fields as a string, parse the string and return the fields as a dictionary, with field names as keys and field values as values. … -
Gunicorn not generating sock file
I have an django application which I want to run using gunicorn and nginx. I have my application installed in this directory: /website/davidbien/ I get to the point where I run django's dev webserver and can access that. I then run: gunicorn davidbien.wsgi:application --bind 0.0.0.0:8000 And this works fine as well. After this I create a script: #!/bin/bash NAME="davidbien" DJANGODIR=/website/davidbien SOCKFILE=/website/davidbien/davidbien.sock USER=ec2-user GROUP=ec2-user NUM_WORKERS=3 DJANGO_SETTINGS_MODULE=davidbien.settings DJANGO_WSGI_MODULE=davidbien.wsgi echo "Starting $NAME as `whoami`" cd $DJANGODIR source ../virtual/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file= And this runs fine as well as I get: Starting gunicorn 19.7.1 Arbiter booted Listening at: unix:/website/virtual/run/gunicorn.sock (3354) [INFO] Using worker: sync [INFO] Booting worker with pid: 3361 [INFO] Booting worker with pid: 3362 [INFO] Booting worker with pid: 3363 [DEBUG] 3 workers The problem is that .sock file is not generated at all! I can't move on with nginx config as this file is not available. I gave 777 access to /website/ folder and everything inside it but this still doesn't work. I tried sudo as well and nothing. Logs show that it's … -
JSON data from Django view
I want to query the database for one row of a table, and send this data in JSON format from a Django view: I checked Django serializer for one object, and I came up with: class BaseView(TemplateView): def get_context_data(self, **kwargs): context = super(BaseView, self).get_context_data(**kwargs) data = Language.objects.get(id=1) array_result = serializers.serialize('json', [data], ensure_ascii=False) context['oneLanguageItemInJSON'] = array_result[1:-1] return context But it sends the object like: "{ "fields": {"prop1": "val1", "prop2": "value2", "prop3": "val3" }, "model": "front.language", "pk": 1 }" Anyone knows what can be done here to get a normal JSON object? -
Using Django Login Required Mixin
I have a class based view which I would like to make accessible only when a user is logged in, and I would like to redirect unauthenticated users back to the index page This is the view in question: class ArtWorkCreate(CreateView, LoginRequiredMixin): login_url = '/login/' redirect_field_name = 'login' model = ArtWork fields = ['userID','title','medium','status','price','description'] This is the related Model class ArtWork(models.Model): userID= models.ForeignKey(MyUser, on_delete=models.CASCADE) title = models.CharField(max_length=100) medium = models.CharField(max_length=50) price = models.FloatField() description = models.TextField(max_length=1000) status = models.CharField(max_length=4, default="SALE") def __str__(self): return self.title And this is the related URL url(r'artwork/add/$', ArtWorkCreate.as_view(), name='artwork-add'), and this is the URL I would like to redirect to where the user is NOT logged id url(r'^index/$', views.index, name='index'), My goal is to make the form only accessbile to logged in user where they can only add an artwork item under their own name and lastly this is the model form class ArtWorkForm(ModelForm): class Meta: model = ArtWork fields = ['title','medium','status','price','description'] -
Any ideas as to why my Django form won't render widget classes?
I have this ModelForm and I am trying to render a class in the html, however it won't work. Here is what I have: class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ( 'first_name', 'profile_pic', 'location', 'title', 'user_type', 'website', 'twitter', 'dribbble', 'github' ) widget = { 'first_name':forms.Textarea(attrs={'class':'form-control'}), 'profile_pic':forms.TextInput(attrs={'class':'form-control'}), 'location':forms.TextInput(attrs={'class':'form-control'}), 'title':forms.TextInput(attrs={'class':'form-control'}), 'user_type':forms.TextInput(attrs={'class':'form-control'}), 'website':forms.URLInput(attrs={'class':'form-control'}), 'twitter':forms.TextInput(attrs={'class':'form-control'}), 'dribbble':forms.TextInput(attrs={'class':'form-control'}), 'github':forms.TextInput(attrs={'class':'form-control'}), } I have tried this... class UserProfileForm(forms.ModelForm): first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) class Meta: model = UserProfile fields = ( 'first_name', 'profile_pic', 'location', 'title', 'user_type', 'website', 'twitter', 'dribbble', 'github' ) Neither of them work, I have been looking all over for how to get this to work but I can't seem to figure it out. -
Django_q : not running without sync=True and assigning proper names
I am pretty sure I am missing something but I been thruthe documentation but couldn't find it. How do I give a task a proper name of my own instead of the one it generates on its own? I tried name='xxxxx' but name is not recognized but group works well. when I run async(), I can see message INFO Enqueed somenumber but the task never runs. But if I do sync=True (which the documentation even states and i noticed is for testing purposes), it does run and works pretty well. In my admin, i don't see new additions to scheduled tasks (not sure if thats where it should go either). -
parameterize testing with django settings
Am working on a django reusable package that am planning to use with multiple project. I've used pytest to build test suite, I've used parametrized helped in pytest to run a single test with multiple configuration. Yet, I would like to run all my tests using different settings combinations available_backends = [ 'django_profile.auth_backends.drf.RestFramework', 'django_profile.auth_backends.kong.Kong', ] def pytest_generate_tests(metafunc): # if 'stringinput' in metafunc.fixturenames: if 'auth_backend' in metafunc.fixturenames: metafunc.parametrize( 'auth_backend', available_backends ) @pytest.fixture(params=['auth_backend', ]) def auth_backend(request, settings): settings.DJANGO_PROFILE_AUTH_BACKEND = request.auth_backend return settings I experimented with the above approach, but this also means I have to add auth_backend to each test case, I don't believe this is ideal. Any one can recommend a way for me to run all my tests using different setting combinations? Regards -
Django - Best approach for managing 2+ types of users
There will be 2+ different types of users in my project, each with their own custom fields and permissions. Since I'm not changing the method of authentication, I plan to use the default User and create profile models. My question is, is it better to create a singular profile model, containing all the custom fields for each user type, and display the appropriate ones for each user (see method 1 below)? Or is it better to create a separate profile model for each user type (see method 2)? Method 1 from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, ...) usertype1_customfield1 = models.CharField(...) usertype1_customfield2 = models.CharField(...) ... usertype2_customfield1 = models.CharField(...) usertype2_customfield2 = models.CharField(...) ... # and so on for each user type... Method 2 from django.contrib.auth.models import User class ProfileUserOne(models.Model): user = models.OneToOneField(User, ...) customfield1 = models.CharField(...) customfield2 = models.CharField(...) ... class ProfileUserTwo(models.Model): user = models.OneToOneField(User, ...) customfield1 = models.CharField(...) customfield2 = models.CharField(...) ... # and so on for each user type... -
Rebuild_index does not update new items Haystack Elasticsearch Django
Have been looking around for this solution but can't find anything. I have just started using Haystack == 2.6.1 and am using Elasticsearch==2.4.1 and Elasticsearch server 2.4.6. I was able to perform searches and get results after following haystack's getting started. After I run python manage.py rebuild_index It worked the first time because like I said I was able to perform searches. But then I added 3 entries to my db and tried to rebuild and/or update the index. But now I see this: RuntimeWarning: DateTimeField Order.dateEntered received a naive datetime (2017-11-11 16:07:54.324473) while time zone support is active. RuntimeWarning) Indexing 32 orders GET /haystack/_mapping [status:404 request:0.004s] And so when I search I still do not see my new entries. I now have 35 orders (it indexed only 32) and I'm seeing this 404 response for GET /haystack/_mapping. Sorry I am new so some of the questions may seem silly: What is haystack expecting to GET; I have a local server running for elasticsearch but is there supposed to be a haystack server as well? Would haystack fail to index new items due to the naive datetime WARNING? And do I have to restart the elasticsearch server each time I … -
Pass multiple checkbox selections in a template to a form
I'm new to Django and i'm still learning the ropes. I have the following template, that allows the user to select multiple check boxes. Now I'd like for those options to be passed to a new url path after the user pushes a button. If i'm going about this the wrong way let me know and give a suggestion. <div class="container"> <div class="row"> <div class="col"> <h3>Financial</h3> <ul> {% for app in fingrouplist %} <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" > {{ app.report_name_sc }}</li> {% endfor %} </ul> </div> <div class="col"> How would I pass the result of my checkboxes on report_id to a new form and have it pre-populated with these items after hitting my input/submit button. </br></br> <input class="btn btn-primary" type="button" value="Request Access"> Below is my view and as you'll see I have a lot more grouplists that all use report_id and I want all them to be passed to the form that is generated based on these checkboxes. def profile(request): owner = User.objects.get (formattedusername=request.user.formattedusername) reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername, active = 1).values('report_name_sc') reportIds = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_id', flat=True) reportaccess = QvReportList.objects.filter(report_id__in= reportIds).values_list('report_name_sc', flat = True) reportGroups = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_group_id', flat=True) reportlist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).exclude(active=0) allreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id … -
Django generate a JSON with a recursive query
Currently I have this model: class Group(models.Model): dependency = models.ManyToManyField('self') name = models.TextField() A example of data structure: Group 1 Group 2 Group 3 Group 4 Group 2 Group 5 Group 6 Group 1 and Group 4 don't have parent group, so are main group. I need to create a JSON, with this structure: [{ 'id': 1, 'name': 'Group 1', 'json_id': 1, 'children': [{ 'id': 2, 'name': 'Group 2', 'json_id': 2 }, { 'id': 3, 'name': 'Group 2', 'json_id': 3 } ] }, { 'id': 4, 'name': 'Group 4', 'json_id': 4, 'children': [{ 'id': 2, 'name': 'Group 2', 'json_id': 5 }, { 'id': 5, 'name': 'Group 5', 'json_id': 6, 'children': [{ 'id': 6, 'name': 'Group 6', 'json_id': 7 }] }] } ] json_id is autoincremental will be added in python. How can I genrate this json. -
Can' t able to pass the two paraameters in url python
Defined the function and try to pass the two parameters in the URL and run it then it shows the error "not enough arguments for format string" Here is the code views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponse def detail(request, question_id,choice): response="You're looking at question %s and choice %s." return HttpResponse(response % question_id , choice) urls.py from django.conf.urls import url from . import views urlpatterns = [ url( r'^$', views.index , name='index' ) , url( r'^(?P<question_id>[0-9])/(?P<choice>[0-9]+)/$', views.detail , name='detail' ) , ] When i pass the url http://127.0.0.1:8000/polls/1/2/ Error TypeError at /polls/1/2/ not enough arguments for format string How to solve it? -
Django gunicorn access denied error
I've setup an application to run with gunicorn on nginx. Here's my gunicorn's setup: #!/bin/bash NAME="davidbien" DJANGODIR=/home/ec2-user/davidbien SOCKFILE=/home/ec2-user/davidbien/davidbien.sock USER=ec2-user GROUP=ec2-user NUM_WORKERS=3 DJANGO_SETTINGS_MODULE=davidbien.settings DJANGO_WSGI_MODULE=davidbien.wsgi echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source ../virtual/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn # Programs meant to be run under supervisor should not daemonize themselves exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- Here's my nginx setup: upstream app_server_djangoapp { server unix:/home/ec2-user/davidbien/davidbien.sock fail_timeout=0; } server { listen 80; server_name ; access_log /var/log/nginx/guni-access.log; error_log /var/log/nginx/guni-error.log info; keepalive_timeout 52.56.193.57; # path for static files root /home/ec2-user/davidbien/davidbien/static; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://app_server_djangoapp; break; } } } When running nginx I keep getting the following error in the logs: [crit] 23465#0: *1 connect() to unix:/home/ec2-user/davidbien/davidbien.sock failed (13: Permission denied) while connecting to upstream, client: 2.96.149.96, server: 52.56.193.57, request: "GET /faviconn.ico HTTP/1.1", upstream: "http://unix:/home/ec2-user/davidbien/davidbieen.sock:/favicon.ico", host: "52.56.193.57", referrer: "http://52.56.193.57/" What is wrong with this? I believe the user I'm using is the owner …