Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Select specific fields in Django get_object_or_404
I have a model in Django with too many fields. Ex: class MyModel(models.Model): param_1 = models.CharField(max_length=100) ... param_25 = models.CharField(max_length=100) Now I need to get the detail view based on an id. I have seen may methods like, obj = MyModel.objects.get(pk=5) obj = MyModel.objects.filter(pk=5)[0] obj = get_object_or_404(MyModel, pk=1) The last method suits the best as I can provide a 404 error without any code change. But I need only param_1 and param_2. Hence I need a query similar to, SELECT "param_1" FROM mymodel WHERE pk=1 How can this be done using get_object_or_404? Can some one help to find a solution for this? -
how to show large message ex 1Mb message size, in loggly
we have a python with django framework project which uses loggly for storing logger messages, In loggly, we are seeing only part of the message when the message size is large i.e., 1 MB. I tried with maxbytes in logger.handler config it is giving error saying unable to configure handler. {handler:{ 'syslog': { 'address': syslog_address, 'level': 'INFO', 'class': 'logging.handlers.SysLogHandler', 'formatter': 'verbose', 'facility': SysLogHandler.LOG_LOCAL0, 'maxbytes': 1024 * 64 }}} please provide how to increase message size limit in loggly. -
Jquery Validate Not Working with AngularJs/Django
Hey I am currently doing a web development project using AngularJS and Django. Usually for form error messages I use ngMessages, but I am trying out Jquery's validate plugin since it seems very straightforward. However, as straight forward as it is, I cannot seem to get it to work. I am new to Jquery so it's probably a noob mistake, but here's my code: register.html <div class="header" id="join_header"> <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h1> Join our community </h1> </div> </div> </div> </div> <div class="supporting-form"> <div class="container"> <div class="col-md-5 col-md-offset-3" data-ng-controller="RegisterController"> <div class="well"> <form role="form" id="registrationForm" name="registrationForm" novalidate data-ng-submit="vm.register(registrationForm.$valid)" class="form-horizontal"> <h4 id="regerror">{{ vm.message }}</h4> <div class="form-group"> <label for="register__username" class="control-label col-sm-4">Username:</label> <div class="col-sm-8"> <input type="text" class="form-control" id="register__username" data-ng-model="vm.username" required/> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="register__password">Password:</label> <div class="col-sm-8"> <input type="password" class="form-control" name="register__password" id="register__password" data-ng-model="vm.password" required/> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="confirm__password">Confirm Password:</label> <div class="col-sm-8"> <input type="password" class="form-control" name="confirm__password" id="confirm__password" required/> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="register__email">Email:</label> <div class="col-sm-8"> <input type="email" class="form-control" id="register__email" data-ng-model="vm.email" required/> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="register__first_name">First Name:</label> <div class="col-sm-8"> <input type="text" class="form-control" id="register__first_name" data-ng-model="vm.first_name" required/> </div> </div> <div class="form-group"> <label class="control-label col-sm-4" for="register__last_name">Last Name:</label> <div class="col-sm-8"> <input type="text" class="form-control" … -
error is not displayed in the template
I have used django allauth for user registration and login. I have used the {{ form.has_errors }} in template to show an error but the error is not displayed in the template. What might be the reason for not showing an error in the template? The code from allauth login.html(account/login.html) {% block content %} <div class="login-box"> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-6 col-md-offset-3 login-area"> <span class="error"> {% if form.has_errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} </span> <div class="panel panel-default"> <div class="panel-heading login-header">{% trans "Sign In" %}</div> <div class="panel-body"> <form class="login" method="POST" action="{% url 'account_login' %}"> {% csrf_token %} <div class="form-group form-group-lg"> <label for="emailAddress">Email address</label> <input type="email" class="form-control" id="emailAddress id_login" name="login" placeholder="Email"> </div> <div class="form-group form-group-lg"> <label for="password">Password</label> <input type="password" class="form-control" id="password id_password" name="password" placeholder="Password"> </div> <div class="form-group"> {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} </div> <button class="btn-block signin-btn btn-sm btn-primary pull-right m-t-n-xs" type="submit">{% trans "Sign In" %}</button> </form> </div> <div class="panel-footer"> <a class="button secondaryAction" href="{% url 'account_reset_password' %}">{% trans "Forgot Password?" %}</a> </div> </div> </div> </div> </div> {% endblock %} -
How to create a password field for a user model in Django?
I am completely new to Django. In my models.py, I want a User model to represent users that sign into the application. I see how I could have fields like fname, lname, email, and username, (simply add "first_name = models.CharField(max_length=50)", for example) but how would I have a password field so that users can be authenticated? Obviously it's a bad practice to store passwords in clear text. -
Scp with subprocess python with a private key
How do i get this scp command converted for python subprocess. scp -i /home/ramesh7128/Downloads/<private_key>.pem /home/ramesh7128/Downloads/testing_transfer.py <remote_add>:<remote_file_path> esp the part to include the private key path is where i am having issues. -
URL template tag causing NoReverseMatch when URL name from an include is used
With the following definitions: urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), # Homepage url(r'^$', projects.homepage, name='homepage'), url(r'^create_new_project/$', projects.create_new_project), # Project page url(r'^(?P<project_path>\w+)/', include('projects.urls')), ] projects/urls.py from . import views as projects from gpuz import views as gpuz # gpuz as a sample tool from models import views as models urlpatterns = [ url(r'^$', projects.projectpage, name='project-page'), url(r'^gpuz/$', gpuz.page), url(r'^settings/$', models.settings_new), ] I am able to resolve URLs such as localhost/myproject/ and localhost/myproject/gpuz/ but generating the URLs through templates gives me NoReverseMatch errors. Example: base.html <div class="navbar-collapse collapse "> <ul id="menu-top" class="nav navbar-nav navbar-right"> <li><a href="{% url 'homepage' %}" class="navbar-btn-home">Home</a> </li> {% if project %} <!-- NoReverseMatch --> <li><a href="{% url 'project-page' %}">{{ project.name }}</a></li> {% endif %} {% if project_tools %} {% for tool in project_tools %} <!-- Expected URL: /myproject/gpuz/ --> <li><a href="{% url 'project-page' tool.name %}" class="navbar-btn-{{tool.name}}">{{ tool.name }}</a></li> {% endfor %} <li><a href="/settings" class="navbar-btn-settings">Settings</a></li> {% endif %} </ul> </div> I am following the example here: https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#url but it doesn't seem to be working for me and I can't figure out what's wrong. I am not using reverse() anywhere in my code. -
django QueryDict only returns the last value of a list
Using django 1.8, I'm observing something strange. Here is my javascript: function form_submit(){ var form = $('#form1_id'); request = $.post($(this).attr('action'), form.serialize(), function(response){ if(response.indexOf('Success') >= 0){ alert(response); } },'text') .fail(function() { alert("Failed to save!"); }); return false; } and here are the parameters displayed in views.py print request.POST <QueryDict: {u'form_4606-name': [u''], u'form_4606-parents': [u'4603', u'2231', u'2234']}> but I cannot extract the parents: print request.POST['form_4606-parents'] 2234 Why is it just giving me the last value? I think there is something wrong with the serialization, but I just cannot figure out how to resolve this. -
Specify a path other than templates folder for placement of templates
I understand that by default the app looks into the template folder of the apps for a specific template name. What happens if I place the templates in a folder called foo ? How can i tell django to look under the foo of each folder ?. -
How the lazy function in django.utils.functional invokes the actual function and why debugging tools failed to reproduce the results?
I am trying to understand how the lazy() function works in the Django module django.utils.functional. One thing I don't understand is what decides when the actual function gets invoked. This is the script I used to test the lazy function: from django.utils.functional import lazy def func1(x, y): print("Task is executing ... ") return x + y print("===== Sec 1") lazy_func1 = lazy(func1) print("\n===== Sec 2") x = lazy_func1(3, 99878) print(type(x)) print("\n===== Sec 3") print(lazy_func1(3, 1000)) print("=====") The output of the above script is: ===== Sec 1 ===== Sec 2 <class 'django.utils.functional.lazy.<locals>.__proxy__'> ===== Sec 3 Task is executing ... 1003 ===== So x = lazy_func(3, 1000) does not invoke the function, which is expected. However, while print(type(x)) does not invoke the actual function, print(x) does. Why is it like this? Another wired thing is that when I tried use a debugging tool (pycharm debug) to follow the source code to check what is happening under the hook, some totally different outputs are generated: Connected to pydev debugger (build 162.1967.10) ===== Sec 1 ===== Sec 2 Task is executing ... Task is executing ... Task is executing ... Task is executing ... <class 'django.utils.functional.lazy.<locals>.__proxy__'> Task is executing ... Task is executing ... … -
Not getting any output in Django for BeautifulSoup
I am trying BeautifulSoup4 in Django and I parsed an XML page with it. When I try the parsing the same page in a python interpreter, it works fine. But in Django, I get an empty page. views.py: def rssfeed(request): list1=[] xmllink="https://rss.sciencedaily.com/computers_math/computer_programming.xml" soup=BeautifulSoup(urlopen(xmllink),'xml') for items in soup.find_all('items'): list1.append(items.title) context={ "list1":list1 } return render(request,'poll/rssfeed.html',context) rssfeed.html: {% if list1 %} {% for item in list1 %} <h1>{{ item }}</h1> {% endfor %} {% endif %} What is that I am doing wrong? -
django-parsley: uncaught error
I am using python 2.7 & django 1.10. I am also using django-parsley for the client side validation. On each page I have the following error in the parsley.min.js file: Uncaught Error: it is not available in the catalog The error refers to the following code segment in the parsley.min.js file: setLocale: function(a) { if ("undefined" == typeof this.catalog[a]) throw new Error(a + " is not available in the catalog"); return this.locale = a, this }, Here is a screen shot of the issue: Does anyone have suggestions as to why I have this error? I have searched SO & Google, but have no real insight. -
Start a daemon from Django server
What is the correct way to make manage.py runserver to start a specific background process (so called "daemon"), preferably before beginning serving HTTP requests. Should I edit manage.py itself or maybe edit settings.py? -
Nested router vs filters
I'm very new to API implementation from ground up and I needed some advice on what the standard or the best approach in my API structure is. Currently my implementation includes nested routers (drf-nested-routers package) such as "www.thissite.com/store/21/products/1/" Now as I dig deeper in django I've uncovered that there are filters that allow me to do the exact same operation above with a little less code like this "www.thissite.com/products/?store__id=21&id=1" My question is which one is best practice and why? -
Heroku/ Django - RuntimeError: ImportError: No module named
I'm running a Scrapy project that has a Django project as a submodule (to use the Django Model with scrapy-djangoitem). This is hosted on Heroku. When I try to do a curl request to Scrapy, it errors with: {"status": "error", "message": "ImportError: No module named config.settings.production", "node_name": "3768a585-8b10-4aae-8e55-21bd7b819f41"} The full error in the logs: 2016-09-18T19:18:50.378107+00:00 app[web.1]: 2016-09-18T19:18:50+0000 [twisted.scripts._twistd_unix.UnixAppLogger#info] reactor class: twisted.internet.epollreactor.EPollReactor. 2016-09-18T19:18:50.379587+00:00 app[web.1]: 2016-09-18T19:18:50+0000 [Launcher] Scrapyd 1.1.0 started: max_proc=32, runner='scrapyd.runner' 2016-09-18T19:18:51.260911+00:00 heroku[web.1]: State changed from starting to up 2016-09-18T19:18:56.997378+00:00 app[web.1]: 2016-09-18T19:18:56+0000 [_GenericHTTPChannelProtocol,2,10.184.200.150] Unhandled Error 2016-09-18T19:18:56.997409+00:00 app[web.1]: Traceback (most recent call last): 2016-09-18T19:18:56.997411+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/twisted/web/http.py", line 1845, in allContentReceived 2016-09-18T19:18:56.997412+00:00 app[web.1]: req.requestReceived(command, path, version) 2016-09-18T19:18:56.997412+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/twisted/web/http.py", line 766, in requestReceived 2016-09-18T19:18:56.997413+00:00 app[web.1]: self.process() 2016-09-18T19:18:56.997414+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/twisted/web/server.py", line 190, in process 2016-09-18T19:18:56.997415+00:00 app[web.1]: self.render(resrc) 2016-09-18T19:18:56.997415+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/twisted/web/server.py", line 241, in render 2016-09-18T19:18:56.997417+00:00 app[web.1]: --- <exception caught here> --- 2016-09-18T19:18:56.997416+00:00 app[web.1]: body = resrc.render(self) 2016-09-18T19:18:56.997417+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/scrapyd/webservice.py", line 17, in render 2016-09-18T19:18:56.997418+00:00 app[web.1]: return JsonResource.render(self, txrequest) 2016-09-18T19:18:56.997418+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/scrapyd/utils.py", line 19, in render 2016-09-18T19:18:56.997419+00:00 app[web.1]: r = resource.Resource.render(self, txrequest) 2016-09-18T19:18:56.997420+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/twisted/web/resource.py", line 250, in render 2016-09-18T19:18:56.997420+00:00 app[web.1]: return m(request) 2016-09-18T19:18:56.997421+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/scrapyd/webservice.py", line 33, in render_POST 2016-09-18T19:18:56.997422+00:00 app[web.1]: spiders = get_spider_list(project) 2016-09-18T19:18:56.997422+00:00 app[web.1]: … -
How to refer Django URLs in extra patterns' by their names
An example in the Django documentation says, to include extra patterns, we can use some code similar as follows: extra_patterns = [ url(r'^reports/$', credit_views.report, name='reports'), url(r'^reports/(?P<id>[0-9]+)/$', credit_views.report), url(r'^charge/$', credit_views.charge), ] urlpatterns = [ url(r'^$', main_views.homepage), url(r'^help/', include('apps.help.urls')), url(r'^credit/', include(extra_patterns)), ] But How can we refer the URL in extra_patterns by their names? It seems that the prefix is not included when referred. For example, to refer reports, the URL does not include the prefix credit/. -
ImportError: No module named bs4 in django
I am learning Django and I was working with bs4 in PyCharm on mac. I am using Python3 with Django which also has bs4 installed and it can be seen below. But when I run the project, it throws me an error saying bs4 does not exist which can be seen below. I have tried a lot of ways and it couldn't get it to work. Help -
How relate django users with policies in IAM AWS?
Im learning about AWS and im trying to create an app with the next functionality: -Customized users(inherit from django user) are created in the app, and these can have different roles: Teacher: will be able to upload files to S3. Student: Only can read from S3 So, i have to create different policies in AWS(one for Teacher and other for student). My Question is, How i can relate my users created with my app with this policies? -
My djcelery works locally but not remotely?
I have automated tasks working locally but not reomotely in my django app. I was watching a tutorial and the guy said to stop my worker. but before I did that I put my app in maintenance mode, that didn't work. then I ran heroku ps:restart that didn't work, then I ran heroku ps:stop worker which outputed Warning: The dynos in your dyno formation will be automatically restarted. then I ran heroku ps:scale worker=1 and still nothing. I remind those who are reading this that it worked locally. What am I missing? -
Using Relative URLs in Templates
I am working with book "Tango with Django".Have problem with using relative URLs. To be shortly this:<a href="{% url 'rango:add_page' rango:category.slug %}">Add a Page</a> results to this : http://127.0.0.1:8000/rango/category//add_page/ Function in rango/views.py: def add_page(request,category_name_slug): try: category = Category.objects.get(slug=category_name_slug) except Category.DoesNotExist: category = None form=PageForm() if request.method=='POST': form = PageForm(request.POST) if form.is_valid(): if category: page = form.save(commit=False) page.category = category page.views = 0 page.save() return show_category(request, category_name_slug) else: print(form.errors) context_dict = {'form': form, 'category': category} return render(request,'rango/add_page.html',context_dict) Tried to use rango namespace like : 'rango:add_page' , and <a href="/rango/category/{{ category_name_slug }}/add_page/">Add a Page</a> , and <a href="/rango/category/{{ category.slug }}/add_page/">Add a Page</a> ,but it didnt helped me. -
Session Validation and Expiration
I am currently reading about session expiration and I am curious as to how django would know if a session expired ? Currently I have read about reading and writing to sessions in Django and how to set expiration of a session but have not encountered anything on validating a session. How do I know if a session is still Valid using Django ? -
Is it possible to install a package only in current project with PIP
I am working both on Python/Django and nodejs. There are 2 commands which are very similar: npm for node pip for python npm is able to install third party package only for a selected project (in the node_modules project subfolder). npm can also install globaly the package on the system. There is an option for that. pip seems to only install globals packages. Thats mean i can not have a "pip_module" folder in my project ? Thanks -
nginx / uwsgi with django 1.9.8 - Bad gateway 502 error with upstream prematurely closed connection while reading response header from upstream?
my nginx_app.conf - server { listen 8000; #server_name access_log /var/log/tw-access.log; error_log /var/log/tw-error.log; root /var/www/djangoapp; access_log on; error_log on; location /static/ { alias /var/www/djangoapp/apptw/static/; } location / { uwsgi_pass 127.0.0.1:8800; include uwsgi_params; uwsgi_read_timeout 500; } } and my uwsgi_app.ini - # djangoapp_uwsgi.ini file [uwsgi] # Django-related settings # the base directory (full path) chdir = /var/www/djangoapp # Django's wsgi file module = djangoapp.wsgi:application # process-related settings # master master = true # maximum number of worker processes processes = 5 # the socket (use the full path to be safe socket = 127.0.0.1:8800 # ... with appropriate permissions - may be needed chmod-socket = 664 # clear environment on exit vacuum = true max-requests = 5000 uid = www-data gid = www-data enable-threads = true buffer-size = 65535 when I am opening this with server-IP:8000 it is showing 502-bad Gateway and nginx error-file showing :- upstream prematurely closed connection while reading response header from upstream, client: 223.181.31.8, server: , request: "GET / HTTP/1.1", upstream: "uwsgi://127.0.0.1:8800", host: "server-IP:8000" What should I do? please suggest. Thank you in advance... -
Unique for model instance
Django 1.10 If True, this field must be unique throughout the table (https://docs.djangoproject.com/en/1.10/ref/models/fields/#unique). But I would like to make a field unique for this instance. For example below, I want title to be unique for this particular sheet. Tried unique_together but failed. Could you help me with this? class Sheet(models.Model): title = models.CharField(max_length=100, null=False, blank=True, default="") -
Django 1.9 trouble creating and saving a user
I'm not sure why im not able to save a user. Any help will be appreciated. For this site, I've taken everything off, except the minimum in order to isolate whats going on. Here is what I have: models.py: from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User) first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.user.username forms.py: from django import forms from registration.forms import User from portal.models import UserProfile class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ('username', 'password') class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('first_name', 'last_name') views.py: from django.shortcuts import render from portal.forms import UserForm, UserProfileForm def index(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user profile.save() registered = True else: print user_form.errors, profile_form.errors else: user_form = UserForm() profile_form = UserProfileForm() context = {'user_form': user_form, 'profile_form': profile_form, 'registered': registered} return render(request, 'portal/register.html', context) register.html: {% block body_block %} <div> <h2>Test Index Page</h2> </div> <div> <h3>Register Here</h3> <form id="user_form" method="post" action="/portal/third/" enctype="multipart/form-data"> {% csrf_token …