Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which permission management library to choose: django-guardian or django-rules?
I need to use per-object permission management for my Django project. I stumbled upon two permission management libraries: django-guardian and django-rules. Which of those libraries fits better for a scalable project? What advantages and disadvantages has each of those libraries? -
django.contrib.auth.authenticate fails
authenticate() is not working for me. I have looked at the numerous other related questions but I haven't been able to get things working. The request comes in as: b'{"email":"test@test.test","password":"test"}' class LoginView(views.APIView): def post(self, request): data = json.loads(request.body.decode('utf-8')) email = data.get('email', None) password = data.get('password', None) account = authenticate(email=email, password=password) but authenticate() returns as None. The account definitely exists. Any idea what could be causing this? -
How does Gunicorn collect static?
I'm trying to use gunicorn to serve static files before configuring nginx as reverse proxy and I got a little bit confused. When I run my applications it seems like gunicorn is not able to find the static folder into the application. I have the following script to run my Django application. #!/bin/bash # Start with development server # echo Start server. # python manage.py runserver 0.0.0.0:8000 # python manage.py collectstatic --noinput # Collect static files # # Prepare log files and start outputting logs to stdout touch /srv/logs/gunicorn.log touch /srv/logs/access.log tail -n 0 -f /srv/logs/*.log & # # Start Gunicorn processes echo Starting Gunicorn. exec gunicorn django_project.wsgi:application \ --name ds4dems \ --bind 0.0.0.0:8000 \ --workers 3 \ --log-level=info \ --log-file=/srv/logs/gunicorn.log \ --access-logfile=/srv/logs/access.log \ "$@" The result is that style and images are not collected from main_app static folder. Folder structure is the following. django_project ---- django_project ---- main_app -------- static Following I tried to run the same application with development server and the statics are collected. Then I rerun with Gunicorn and styles and images are served to the browser without errors. What exactly is going on? Does it have to do with this? Is the only available option … -
Bootstrap 3 Tabs and Django Forms
I'm building something similar to the tabbed structure in this question. I have a set of students, and I want tabs inside a modal that pull up a form to allow me to select some of them to be members of the Section object. I have the tabs, and have a form that filters by grade, but I can't get the grade variable into the form to provide the filtering when I click the tab. If I were reloading the page, I could figure that out, or even if I created 12 different views (one for each grade), and called them separately, but that seems like an awful way to do it. How do I render the form upon tab switching, while passing the name of the tab (the grade) to the form? Everything works perfectly, as long as I hard-code the grade info into the form. forms.py class RosterAddForm(forms.ModelForm): class Meta: model = Section fields = ['students'] def __init__(self, *args, **kwargs): details = kwargs.pop('details',None) this_section = details['this_section'] roster = this_section.students.all() super(RosterAddForm, self).__init__(*args, **kwargs) self.fields['students'].widget = forms.CheckboxSelectMultiple() try: self.fields['students'].queryset = Student.objects.filter(Grade="11") this hard-coding is the issue: need this to be via selected tab self.fields['students'].initial = roster except: pass views.py ... … -
Correctly exhibiting date from datapicker
I've created a datapicker to allow user to choose date in a date field. The problem is that I'm cannot change the format date is shown after the user pick date in the calendar. What is shown is MM/DD/YYYY and what I want is YYYY-MM-DD. I tried already this and this solution, without success. forms.py project_expiration = forms.DateField(required=False, widget=forms.TextInput(attrs={'class':'datepicker'})) template <script type="text/javascript"> $(function() { $( ".datepicker" ).datepicker({ changeMonth: true, changeYear: true, format: 'yy-mm-dd', minDate: new Date(), }); }); </script> -
Django update api
I ma creating a user profile update api via django: in urls: url(r'^/api/users/(?P<user_id>[0-9]+)$', UserView.as_view(), name='user_profile'), And my view: def patch(self, request, user_id): # logging.info('user Id: %s' % user_id) logging.info('in patch...') user = User.objects.get(id=2) serializer = UserSerializer(user, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_200_OK) return Response(status=status.HTTP_400_BAD_REQUEST) why patch def not called at all?! (I get 504 method not allowed) my request is: patch > http://localhost:8000/api/users/2 When i'm deleting the user_id argument in view, it works, but i need to get the user id in path. -
Docker container with Newrelic Python agent and Supervisord is not sending data
I have a dockerised Django app in uwsgi running using supervisord and I am trying to monitor the app using Newrelic APM. New Relic Python agent installation commands are written inside Dockerfile and in wsgi.py,the below code is included. import newrelic.agent<br/> newrelic.agent.initialize('/opt/testapp/newrelic.ini') My supervisord.conf file: [program:newrelic]<br> command=newrelic-admin run-program uwsgi --thunder-lock --ini /opt/testapp/uwsgi.ini --protocol http<br> autostart=true<br> autorestart=true<br> redirect_stderr=true Below is my Dockerfile command to copy supervisord conf file and run supervisord COPY config/supervisord-newrelic.conf /etc/supervisor/conf.d/supervisord.conf <br> CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"] After running docker-compose up command, the app gets started and running without any issues, App name is listed in New Relic APM dashboard but not showing any data in my newrelic APM dashboard. -
Python/ Django- How to change what information is displayed in a template?
I am working on a project that has been written in Python/ Django, and on one of the webpages, there is a table displaying some information about objects in a database. The table is displayed in a 'tabbed content' elements, and each tab displays a different table. The information displayed in each table varies (i.e. the table has different columns) depending on the type of objects that it is displaying. I want to remove one of the columns from one table in this 'tabbed content' element. The view that returns the URL for this webpage is defined with: def report_ccis(request, project_id): """ CCI items styled for pdf """ print "report_ccis() called in costing.views (1463) " project = Project.objects.get(id=project_id) budget = get_current_budget(project_id) cci_total_exc = budget.cci_total_exc_vat_final cci_grouped_items = budget.cci_items.all().order_by('project_room', 'name') context = { 'project': project, 'cci_total_exc': cci_total_exc, 'cci_grouped_items': cci_grouped_items, 'webview': 1, } try: context['current_budget'] = project.budget_versions.get(current_marker=1) #For option name/date on top of pdfs except ObjectDoesNotExist: pass if request.GET.get('stage') == 'pd': print "request.GET('stage') == 'pd' " """ Render post deposit homepage """ context['html'] = render_to_string('costing/report2_ccis.html', context) print "'render_to_sting() called with parameter: costing/report2_ccis.html " context['active_tab'] = '4' print "render() called with parameter: costing/reports_post_deposit.html " return render(request, 'costing/reports_post_deposit.html', context) else: print "request.GET('stage') != 'pd' " … -
How to display django-thumbnail image from django-ckeditor?
i used django ckeditor for uploading images in the admin panel but i want to know how to display thumbnail image from the media file which saved by django-ckeditor? saving of images from ckeditor is:-Path media/ uploads/year/month/day---|filename.jpg |fil |filename_thumb.jpg -
How can I track the Django website inizialization process?
I write in my browser the domain name of my website developed with Django in my local machine: from now on, how can I track all the files and all the classes/functions/objects called until the web page is returned? -
Django: return 405 for OPTIONS http requests
If a http clients sends an OPTIONS http request to our django site, django returns a 404 (not found) instead of 405 (method not allowed). Example: We provide a URL http://.../foo/download.csv web client (MS office) opens above URL and tries to access (for reasons I really don't know) http://.../foo/ with an http OPTIONS request. Up to now django return 404 since the above URL does not exist (even for GET requests). I guess I could solve this by writing a custom middleware. But this feels too complicated. All OPTIONS requests should get a 405. It should not matter if the URL would be accessible via GET or POST. How to solve the django way? -
Can i Deploy django project without any webhost eg. heroku , pythonanywhere etc etc
I have created a dynamic web page using HTML5 Css3 JS And django. I have already bought a domain name. Now i want to deploy my django project, but dont want to use any web host like heroku aws pythonanywhere etc. All I could find on the web is how to configure apache and mod_wsgi to serve the files. Is it possible to create a web hosting from my home ? If yes how ? Using ubuntu server, apache & mod_wsgi or any other technology? P.S. I dont want to use any web hosting company -
The Tour of Heroes to Django
I have passed TOUR OF HEROES, and I try to integrate code from that tutorial to Django. Now all my Angular project just bunch of static files and by Django I can deliver that files to the client. I tried just copy all files and place them in my /static directory. localhost:8000/static/index.html, localhost:8000/static/app/app.module.ts and so on. When I try to open index.html I can see only : Loading AppComponent content here ... And errors in console: shim.min.js:1 Uncaught SyntaxError: Unexpected token < zone.js:1 Uncaught SyntaxError: Unexpected token < Reflect.js:1 Uncaught SyntaxError: Unexpected token < system.src.js:1 Uncaught SyntaxError: Unexpected token < systemjs.config.js:1 Uncaught SyntaxError: Unexpected token < index.html:19 Uncaught ReferenceError: System is not defined(anonymous function) @ index.html:19 index.html:8 Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:8000/styles.css". By last error ... with MIME type text/html: "http://localhost:8000/styles.css" may be problem with default path where angular take other files, in that case how can I change base path to be /static/? I will really appreciate if somebody can clarify all that should be done to transfer app to Django, and also how reduce enormous number of angular node_module files to be only one file. -
Multi tenant django application using URL mappings instead of domain mappings
In django, most multi-tenant implementations (modules) are mapping hosts onto views. e.g. mapping host/URL -> django view using postgress schema's: customer1.myapp.com/view1/arg1 -> myapp.view1(arg1) using schema 'customer1' customer2.myapp.com/view1/arg1 -> myapp.view1(arg1) using schema 'customer2' customer3.myapp.com/view1/arg1 -> myapp.view1(arg1) using schema 'customer3' Since my PaaS (Pythonanywhere) is not supporting wildcard domains (*.myapp.com), I am trying to set up a multi-tenant application using URL mapping: e.g. mapping URL -> django view myapp.com/customer1/view1/arg -> myapp.view1(arg1) passing implicit parameter tenant='customer1' myapp.com/customer2/view1/arg -> myapp.view1(arg1) passing implicit parameter tenant='customer2' myapp.com/customer3/view1/arg -> myapp.view1(arg1) passing implicit parameter tenant='customer3' Here some middleware should take care of passing the tenant parameter to the view and filtering query results for objects applicable to the selected tenant. e.g. https://django-tenant-schemas.readthedocs.io/en/latest/ But question here is: How to do this -which package can handle this- for URL mapping instead of host mapping? Note: django-multitenants mentions "Supports url patterns as well as sub-domains" but not clear how to do this... https://pypi.python.org/pypi/django-multitenants -
Django CMS: Menu Title field
I'm using Django CMS 3.4.1 . Is there any way I can replace Menu Title CharField for a TextField (in order to support linebreaks)? -
Python Count Files in Folders
I have a backup folder that contains backup folders with data for different months of the year and i want to loop through all folders and return the total number of backup data for last 30 days,60 days and one year ago. Here is my folder. Parent folder name is Backup and sub folders names are 01022016, 02062016, 03052016, 06092016 etc. Each folder is named with the data the backup occurred. Here is my sample code import os from datetime import datetime, timedelta count = 0 today_date = datetime.today() date_ranges = [ ('month', today_date - timedelta(days=30)), ('3 months', today_date - timedelta(days=90)), ('year', today_date - timedelta(days=365)) ] for path, dirs, files in os.walk("data"): for items in files: if items != ".DS_Store": count += 1 print "The Total Number of Processed Data is", count This code actually returns the total number of data for each subfolder but when trying to return just the data for specific data interval like last 30days, 60 days and one year i am getting all kinds of errors. What can i do to get the desired output? -
Django Rest Framework JWT: Cant change JWT_EXPIRATION_DELTA
Im using Django 1.10 and Angular2 2.1.1 to build a web app. Im using Javascript Web Tokens (JWT) implemented with djangorestframework-jwt==1.8 on server and "angular2-jwt": "0.1.24", on client. My JWT settings: from datetime import timedelta JWT_AUTH = { 'JWT_EXPIRATION_DELTA': timedelta(seconds=600), 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': timedelta(days=7), } Problem: The token received from the server has a 1 minute expiration delta (default should be 300 seconds, eg. 5 minutes). The JWT_AUTH settings does not have any influence on the behavior. I've followed the instructions and documentation, but nothing seems to work. Any help is deeply appreciated. -
Create Object if not exist using atomic() Djnago
with atomic('core'): obj_qs = Demo.objects.filter(field_a=a, field_b=b) if obj_qs.count() > 0: raise ValidationError(detail="duplicate not allowed") demo = Demo( field_a= some_value , fields_b = other_value ) demo.save() return demo I try make sure that duplicate objects not created , but even if it in atomic function the validation is failed and duplicate values create that mean i got 2 demo object that contain field_a and field_2 with same values any ideas ?? -
Pros and Cons of Django settings module
I am developing a web-sites. Few days ago I got an advice to split my project's settings on few parts. First part would be a text config (yaml/json), then this text config would be loaded to the project_settings.py with globals(). My colleagues divided on two camps. As I said, first part wants to split the settings. The second part wants to save standard django settings module Can you provide some advantages/disadvantages of these two methods? -
whenever i click on submit,a new python get created but my program not get worked
index.html <form action="index.py" method="post"> First Name: <input type="text" name="fname"><br /> Last Name: <input type="text" name="lname" /> <input type="submit" value="Submit" /> </form> index.py import cgi, cgitb form = cgi.FieldStorage() firstname = form.getvalue('fname') lastname = form.getvalue('lname') print("Hello "+firstname+" "+lastname) print("Content-type:text/html\r\n\r\n") print("<html>") print("<head>") print("<title>Hello - Second CGI Program</title>") print("</head>") print("<body>") print("<h2>Hello %s %s</h2>" % (firstname, lastname)) print("</body>") print("</html>") My directory structure are as follows : Both files are in test directory. project name/test/index.html projectname/test/index.py -
Django REST Framework nested routes without PK
I want to implement routes like this: /items - list of all items. /items/types - list of all item types I was looking at drf-nester-routs, but nested urls expect {pk} to be passed. Is there any good way to achieve what i want? -
Implement something like admob in mobile app but with your own banner
I want to implement something like admob for our app , i'm a django developer and it's easy for me implementing server side app But in mobile app I have some problem . for these problem i want to some service provider for advertising in my app with my banners . if you know something like these plese tell us to Reinventing wheel . Thanks . -
Signout is not working in Django
I have tried to call the signout url from template then redirect to home page. profile.html: <li><a data-hover="Logout" href="{% url 'signout' %}">Logout</a></li> urls.py: urlpatterns = [ url(r'^$', views.login, name='login'), url(r'^ajax/validate_username/$', views.validate_username, name='validate_username'), url(r'^signout$', views.signout, name='signout'), ] views.py: def signout(request): if request.user.is_authenticated(): logout(request) return HttpResponsePermanentRedirect('/') else: return HttpResponsePermanentRedirect('/') Sometimes signout functionality is not working, while clicking the logout menu(The function signout is calling). -
Get process Id of a function, not process of what is running my Django server
I am currently using psutil to do... p = psutil.Process(pid) p.kill() ...In an attempt to kill the process of one function (that I thought I was getting the pid of with): os.getpid() ...Though this kills my entire manage.py runserver command and I have to restart the server. Does anyone know what I can do here? -
Django: Calling a view from a static html page
This is my static html page: <a href="{% url 'studyup/login' %}"><button class="w3-btn w3-light-green w3-large w3-ripple w3-text-shadow">Login</button></a> I'm trying to call a view with url: studyup/login How to do so?