Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django OAuth authentication against Github, without database
I want to create a Django app that does not use a database, but authenticates against Github using OAuth 2.0. The point being that anyone who belongs in our Github organization can log into the app and perform operations, which involve making changes to files in a repo in Github. Think something like the facility in the Github web application to edit files through the web browser. Since I do not need to actually check files out locally using the Github API, I was hoping to avoid having any kind of server-side state. Is there a way I can do this with Django? Thank you -
How to serve Angular2 using Django builtin webserver
how to serve Angular2 app using Django builtin webserver? I think I'm having some problems with the template and static paths from django. My django project structure looks like following: DjangoDir/ manage.py project/ settings.py urls.py app1/ app2/ static/ app2/ something.js something.css templates/ app2/ index.html urls.py views.py I have an angular2 app with following index: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Angular2</title> <base href="/"> <link href="something.css" rel="stylesheet"/> </head> <body> <app-root></app-root><script type="text/javascript" src="something.js"></script> </body> </html> I get HTTP Status 404 (Not Found) code for the something.js and something.css file. Any ideas? Here is my views.py in app2. from django.shortcuts import render # Create your views here. def index(request): return render(request, 'app2/index.html') -
How to schedule django crons?
I have a cron which I have written using django-cron: from django_cron import CronJobBase, Schedule class MyCronJob(CronJobBase): RUN_EVERY_MINS = 1 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'statuscheck.my_cron_job' def do(self): print ("hello") It works, as when the command python manage.py runcrons is run twice in a row, only one output is provided unless the 1 minute has lapsed My question is, how do i then schedule that command to be executed for example 3 times a week? Thank you -
Access LogEntry from views
I am hoping to see LogEntry contents from non-admin views but so far failed. From admin, I can see data of a user who have added actions to LogEntry via log_action method (from non-admin area). But when I tried to see it, I don't see his data. All I see are array data that is full blank values. from django.contrib.admin.models import LogEntry data=LogEntry.objects.filter(user_id=request.user.id).values('change_message',) Here i see fields such as "added","change_message" etc but all are blank. Any help? -
Delete parent object when child object is deleted in Django
class A(models.Model): name = models.CharField(max_length=128) class B(modes.Model): type_b = models.ForeignKey(A) How to delete parent object of model 'A' when I delete related child object of model 'B'. I'm deleting child object through Django admin bulk delete option -
Django form Multiple as dyanmaic checkboxes
Hoping there is a quick slick Django-esque solution to the following challenge that doesn't involve JavaScript. Currently, I have a form created that shows a Many to Many field as a simple multiple (the built in behaviour in Django) utalising the following: Forms.py: class ProfileForm(forms.ModelForm): class Meta: model = Profile exclude = ['email_address'] Template: <form method="post">{% csrf_token %} {{form}} <button class="btn" type="submit">submit</button> </form> Model: class Profile(models.Model): email_address = models.CharField(max_length = 100) subscriptions = models.ManyToManyField(Item, blank=True, null=True) However, to ease the experience for the user (and improve performance on mobile) I would like to instead show a list with checkboxes next to each. Is there an easy way to achieve this without either JavaScript or manually setting each option in the forms.py? -
Django Online Store Shopping Cart
I am doing online store and i have one question. How to do my shopping cart? Thre area two ways Through Django Sessions Create table Cart and set all informations about product and user to the table Cart Which way is more better? Any ideas? Or other ways to do it? -
How to get HTTP POST parameters in exact order in Django?
I am trying to get the POST data parameters in the exact order they are received in Django. I have this in my views.py: @require_POST @csrf_exempt def paypal_ipn_listener(request): print request.POST print request.body The data in request.POST is in QueryDict which is unordered, thus doesn't suit my needs. Trying to access request.body throws an exception: RawPostDataException: You cannot access body after reading from request's data stream I think this exception happens because of my @require_POST or @csrf_exempt decorators which perhaps call some middleware which reads POST data stream. Anyway my question is how do I get HTTP request POST data in exact order? I need to keep the order to satisfy PayPal IPN implementation requirements. -
Deleting an item button using Django deletes only the first item
So I have been building a website in DJANGO with a table of servers (IP,Owner etc..) I'm using mysql. For each item I added a button of delete and edit. But, the delete button deletes the first item always instead of the server the button next to! There is the line - I tried putting server.id, {{ server.id }}.. nothing worked. Does anyone have any idea? P.S When I ask in the confirmation do you want to delete server.ServerName.. it asks only for the name of the first server even though it's in the loop.. index.html- {% for server in posts %} <tr> <div class ="server"> <td>{{ server.ServerName }}</td> <td>{{ server.Owner }}</td> <td>{{ server.Project }}</td> <td>{{ server.Description }}</td> <td>{{ server.IP }}</td> <td>{{ server.ILO }}</td> <td>{{ server.Rack }}</td> <td>{{ server.Status }}</td> <td> </div> <button type="button" class="btn btn-primary" data-toggle="modal" href="#delete-server-{{server.id}}" data-target="#DeleteItem">Delete <span class="glyphicon glyphicon-trash" </span></button> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#DeleteItem">Edit <span class="glyphicon glyphicon-pencil" </span></button> <div id ="DeleteItem" class="modal fade" role="document"> <div class="modal-dialog" id="delete-server-{{server.id}}"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Delete Confirmation</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="{% url 'delete_post' server.id %}" method="post">{% csrf_token %} <h6>Are you sure you want to delete {{ server.ServerName }}?</h6> <input … -
Why django don't try search templates in one of app folders?
I install in Django project virtual enviroment this application https://github.com/badzong/django-xsession and for some reason django can't find template from this application. In django error page "Template-loader postmortem" in the directories list present another applications, for example django_grappelli-2.8.1-py2.7.egg, django_ckeditor-5.0.3-py2.7.egg and other, but django_xsession-0.1-py2.7.egg are absent. Used this loader: LOADERS = ( 'django.template.loaders.app_directories.Loader', ) django_xsession-0.1-py2.7.egg present in the Python Path What i do wrong? Why i get error TemplateDoesNotExist at / django_xsession/loader.html -
Django runserver stuck with performing system check with jira modules
I use the following versions in my python3 virtual environment with centos7, certifi==2017.7.27.1 chardet==3.0.4 defusedxml==0.5.0 Django==1.11.6 djangorestframework==3.7.0 idna==2.6 jira==1.0.10 oauthlib==2.0.4 pbr==3.1.1 pytz==2017.2 requests==2.18.4 requests-oauthlib==0.8.0 requests-toolbelt==0.8.0 six==1.11.0 urllib3==1.22 When I try to start the Djanogo development server it has with following point, python manage.py runserver 0.0.0.0:80 Performing system checks... Now If I do pip uninstall jira, then start the server it works fine, again when I reinstall the same issue is happening -
Authenticating Android app with Django OAuth2 Toolkit
I'm currently scouting the internet for informations on how to create an API for a web application to integrate an Android (also iOS) app. I've found a bunch of useful sites and blog posts that helped me with the API and authentication side. I decided to use Django because I'm quite familiar with Python and I learned a lot about Django rest-framework and one package called Django OAuth Toolkit for the authentication. What it's not really clear to me is the way I should build my Android app to actually log in the user and get the authentication token. I read the official Android documentation about AccountManager but I' don't understand if this would be the right way to procede. I've also found a library for Android called OkHttp OAuth2 client that seems more straightforward to use to me but, whit this one, I have trouble understanding how to save the token in a safe way. What of these two methods is the best? What do you suggest? Thank you, everyone! -
Connect To Sock file failed. Resource temporarily unavailable
I am setting up a Django server with Nginx, Gunicorn and Django. I follewed this link (https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04). My server starts working correctly as when I hit my services with Postman or Browser, I am getting response. My Nginx file looks like this server { listen 80; server_name server_ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/frt/project/project/; } location / { include proxy_params; proxy_pass http://unix:/home/frt/project/project/project.sock; } } But when I run load test on this server with JMeter, In almost 40% requests, I get "Bad Gateway" error. I look into logs and below is the error 2017/10/09 08:11:11 [error] 7777#7777: *3153 connect() to unix:/home/frt/project/project/project.sock failed (11: Resource temporarily unavailable) while connecting to upstream, client: 192.168.23.83, server: 192.168.3.217, request: "GET /api/posts/ HTTP/1.1", upstream: "http://unix:/home/frt/project/project/project.sock:/api/posts/", host: "192.168.3.217" -
Django "dictionary update sequence element #0 has length 1; 2 is required"
I am trying to make multi-page registration form to work, and I think that I am close to making it work, but I keep getting errors. I am using built-in user model and extending it with one-to-one relationship. This is models.py file: class Dadilja(models.Model): korisnik = models.OneToOneField(User) ime = models.CharField(max_length=256) prezime = models.CharField(max_length=256) datum_rođenja = models.DateField(null=True, blank=True) mjesto = models.CharField(max_length=256) mjesto_obavljanja = models.CharField(max_length=256) broj_telefona = models.CharField(max_length=20) slika_profila = models.ImageField(upload_to="slika_profila", blank=True) iskustvo = models.CharField(max_length=256) dostupna = models.CharField(max_length=256) about = models.CharField(max_length=256) broj_djece = models.PositiveIntegerField() dodatno = models.CharField(max_length=256) cijena = models.PositiveIntegerField() forms.py: class Forma1(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ("username", "email", "password") class Forma2(forms.ModelForm): datum_rođenja = forms.DateField(widget=forms.SelectDateWidget(years=reversed(range(1930,2000)))) class Meta(): model = Dadilja fields = ("ime", "prezime", "datum_rođenja", "mjesto", "mjesto_obavljanja", "broj_telefona") class Forma3(forms.ModelForm): class Meta(): model = Dadilja fields = ("slika_profila", "iskustvo", "dostupna", "about", "broj_djece", "dodatno", "cijena") and most importantly, views.py file: def dadilja_registracija_1(request): if request.method == "POST": korisnik = Forma1(request.POST) if korisnik.is_valid(): request.session['form_data_page_1'] = korisnik.cleaned_data return HttpResponseRedirect(reverse('accounts:dadilja2')) else: print(korisnik.errors) else: korisnik = Forma1() return render(request, 'accounts/dadilja1.html', {'korisnik' : korisnik}) def dadilja_registracija_2(request): def datetime_handler(self, x): if isinstance(x, datetime.date): return x.isoformat() dadilja1 = Forma2(request.POST) if request.method == "POST" and dadilja1.is_valid(): json.JSONEncoder.default = datetime_handler request.session['form_data_page_2'] = dadilja1.cleaned_data return HttpResponseRedirect(reverse('accounts:dadilja3')) else: dadilja1 … -
Querying ManyToMany relationships
I have a bunch of stations that belong in groups. Each station can be in multiple groups. This is the model (simplified): class Station(models.Model): name = models.CharField(max_length=4, blank=False, primary_key=True) def __str__(self): return "Station " + self.name class StationGroup(models.Model): name = models.CharField(max_length=100, blank=False, primary_key=True) stations = models.ManyToManyField(Station) def __str__(self): return "Station group " + self.name How can I get a list/queryset containing stations that are not in any group stations that are in N groups the intersection, union and difference of N stationGroups ? (Suggestions for better question title are welcome) -
How to keep order of POST parameters in Django test client?
I am writing a unit test for a Django view and I have this in my unit test: data_from_paypal_other_id = {'client_id': '1', 'receiver_email': 'badguy@example.com', 'amount': '1.5'} self.client.post(reverse('paypal_ipn_listener'), data=data_from_paypal_other_id) The problem is PayPal requires me to send a POST request with parameters in a specific order. Don't ask me why, see this. The Django test client I see the parameters in messed up order: --BoUnDaRyStRiNg Content-Disposition: form-data; name="receiver_email" badguy@example.com --BoUnDaRyStRiNg Content-Disposition: form-data; name="amount" 1.5 --BoUnDaRyStRiNg Content-Disposition: form-data; name="client_id" 1 --BoUnDaRyStRiNg-- Note that receiver_email jumped before client_id. My question is how do I force Django test client to keep the order of arguments? I know in python dictionaries are unordered so I have tried using OrderedDict and also a list of tuples instead of a dict but got the same result. -
Where are Django User model fields saved?
Sorry, if this is a very basic question, but I was wondering where Django User model field values like is_active are saved as I don't see them in the database. I am using a custom User model, but they must still be saved somewhere... :) models.py class MyUserManager(BaseUserManager): def create_user(self, username, email, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) self.username = username user.set_password(password) user.save(using=self._db) return user ... class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = False objects = MyUserManager() USERNAME_FIELD = 'email' ... Tables in database: Schema | Name | Type | Owner --------+------------------------+-------+------------ public | auth_group | table | xxx public | auth_group_permissions | table | xxx public | auth_permission | table | xxx public | django_admin_log | table | xxx public | django_content_type | table | xxx public | django_migrations | table | xxx public | django_session | table | xxx public | drillapp_myuser | table | xxx public | drillapp_question | table | xxx public | drillapp_story | table | xxx (10 rows) This is how the user table looks. No … -
Unable to show model data from db to template
I am unable to show data from django 3rd model(class Jenkinsjobsinformation) to template. It is possible to publish data from 1st and 2nd model(Projectname and Jenkinsjobsname).Below find below my model: model.py class Projectname(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Jenkinsjobsname(models.Model): projectname=models.ForeignKey(Projectname) jobsname = models.CharField(max_length=200) def __str__(self): return self.jobsname class Jenkinsjobsinformation(models.Model): jobinformation=models.ForeignKey(Jenkinsjobsname) build = models.IntegerField() date = models.DateField(null=True) views.py def index(request): project_name=Projectname.objects.order_by('-name')[:5] context = {'categories': project_name} return render(request,'buildstatus/index.html', context) def detail(request,projectname_id): project_name=Projectname.objects.order_by('-name')[:5] jobs=Projectname.objects.get(pk=projectname_id) context = {'jobs': jobs, 'categories':project_name} return render(request,'buildstatus/detail.html', context) def jobdetail(request,projectname_id,jobinformation_id): project_name=Projectname.objects.order_by('-name')[:5] jobs=Projectname.objects.get(pk=projectname_id) jobdetail=Jenkinsjobsname.objects.get(pk=jobinformation_id) context = {'jobs': jobs,'categories':project_name,'jobdetail':jobdetail} return render(request,'buildstatus/job_detail.html', context) urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<projectname_id>[0-9]+)/$', views.detail, name='detail'), url(r'^(?P<projectname_id>[0-9]+)/(?P<jobinformation_id>[0-9]+)/$', views.jobdetail, name='job_detail'), ] index.html {% extends "base.html" %} {% block text1 %} {% if categories %} <ul> {% for category in categories %} <li><a href ="{% url 'detail' category.id %}">{{category.name }}</a></li> {% endfor %} </ul> {% else %} <strong>There are no test categories present.</strong> {% endif %} {% endblock %} detail.html {% extends "base.html" %} {% block text1 %} {% if categories %} <ul> {% for category in categories %} <li><a href ="{% url 'detail' category.id %}">{{category.name }}</a></li> {% endfor %} </ul> {% else %} <strong>There are no test categories present.</strong> {% endif %} {% … -
Django multiple database transaction lock
I have 2 databases configured like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db1', ... }, 'db1': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db1', ... }, 'db2': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db2', ... } } Notice that default and db1 is the same database. And if I have two nested transactions like this: with transaction.atomic(): with transaction.atomic(using='db1'): ... Django wants to start two transactions in the same database and it causes OperationalError: (1205, 'Lock wait timeout exceeded; try restarting transaction'). Is there any way to avoid this? I'm using Django 1.10 and it worked well in Django 1.9. And I cant change db names and aliases in settings. -
Is it possible to call an Django Foreign Key object in success of Ajax?
Is it possible to call an Django Foreign Key object in success of Ajax ? models.py class Message(models.Model): id = models.AutoField(primary_key=True) chat = models.ForeignKey(Chat, models.CASCADE, null=True, related_name='chat') message = models.CharField(max_length=5000) date = models.DateTimeField(auto_now_add=True) views.py def message_view(request): chatid = request.GET.get('chatid', None) messages = Message.objects.filter(chat__id=chatid) message_list = list(messages.values()) data = { 'message_list': message_list } return JsonResponse(data) chatoverview.html $(document).ready(function(){ $(".btn_load_messages").click(function(){ var chatid = $(this).val(); $.ajax({ url:'/ajax/messages', data: { 'chatid': chatid }, dataType: 'json', success: function(data){ var message_list = data.message_list; var requestuser = "{{ request.user.id }}" $(".container-text2").empty(); $.each(message_list, function(index, value){ $(".container-text2"). append("<div class=text1>"+ value.message +"</div>"); }); } }); }); }); I need the chat.buyer.id. So i would do something like: $(".container-text2").append("<div class=text1>"+ value.chat.buyer.id +"</div>"); But this does not work. Is it possible to do something like this ? If yes, could you please tell me what i have to change to get it working ? -
Send CSRF Token in dropzone
I have tried to send csrf token in my AngularJS/Django app using the following code. The $rootScope.CSRFToken contains token value that is received from Cookie object. All other services are working fine with ajax but when I call the service via dropZone, using headers, it gives the error that Server responded with 403 code. This is how I'm configuring dropzone: $scope.dzOptions = { url : $scope.saveUrl, paramName : 'newCaseFiles', maxFilesize: $rootScope.maxCaseFileSize, addRemoveLinks : true, autoProcessQueue: false, uploadMultiple: true, parallelUploads: 20, headers: { 'X-CSRFToken': $rootScope.CSRFToken } }; It worked fine until CSRF mechanism was implemented in the application. Please, help. -
python - Packaging my webapp
Please I'm new to python. I want to know how to package my web application to make it downloadable and installed on a device(like facebook, whatsapp, Instagram and the like). I've searched but all I get is directing me on packaging python modules. Can anyone help please? Thanks in advance. -
Eventlet is_monkey_patched issues False
Hello I have a django app. My whole system configuration is the following: python 3, django 1.11, eventlet 0.21.0. 1) Nginx as an upstream server: upstream proj_server { server unix:///tmp/proj1.sock fail_timeout=0; server unix:///tmp/proj2.sock fail_timeout=0; } 2) Supervisor that controls workers. There is a gunicorn worker: [program:proj] command=/home/vagrant/.virtualenvs/proj/bin/gunicorn -c /vagrant/proj/proj/proj/deploy/gunicorn.small.conf.py proj.wsgi:application directory=/vagrant/proj/proj/proj/deploy user=www-data autostart=true autorestart=true stdout_logfile=/var/log/supervisor/proj.log 3) This is a gunicorn.small.conf content: bind = ["unix:///tmp/proj1.sock", "unix:///tmp/proj2.sock"] pythonpath = "/vagrant/proj/proj/proj/deploy" workers = 2 worker_class = "eventlet" worker_connections = 10 timeout = 60 graceful_timeout = 60 4) And this is proj.wsgi content: """ WSGI config for proj project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import eventlet eventlet.monkey_patch() from eventlet import wsgi import django.core.handlers.wsgi import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings") # This … -
Initial value in django form dropdown is not empty?
I have a form where I define selection criterias for report. One of the dropdowns 'building' that is auto populated from the model , should be not mandatory and have default value as empty. I can't achieve the empty part . I want first field in my dropdown in my form building = forms.IntegerField( widget=forms.Select( choices=Building.objects.all().values_list('id', 'name') ) , required=False ) in view file when I initialize the code form = PaymentRangeForm(initial = {'building': 0 }) I use crispy forms in my template but I don't think it makes any difference. {{ form|crispy}} I am not getting any error but the default is not empty it has a value of first record from the model. What I am missing? -
Deploying Django to a server
I've been studying django, and mostly django rest framework for many months now, and now have something I wish to deploy. This is my first time deploying Django to a server, but I've deployed Angular applications in the past with nginx. I've gone through so many tutorials, and nothing is working for me, I have no idea what I'm doing wrong. Oh and to be clear, my attempts have been on freshly made virtual servers, not the same server that is currently running my angular frontends. I've followed this page https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 to the letter, I get upto the part with ~/myproject/manage.py runserver 0.0.0.0:8000 but then where they show that navigating to the servers ip address on port 8000 shows an 'It worked' page, I get no response. I've also followed https://simpleisbetterthancomplex.com/tutorial/2016/10/14/how-to-deploy-to-digital-ocean.html, with the same problem. I've also followed: http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html, with the same problem, and also ran # test.py def application(env, start_response): start_response('200 OK', [('Content-Type','text/html')]) return [b"Hello World"] # python3 #return ["Hello World"] # python2 with uwsgi --http :8000 --wsgi-file test.py, and still no response. The server is with digitalocean, I've tried so many different variations of tutorials for this too, all with the same effect. Things notable that I've tried …