Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Memcached not working beyond scope(?)
I cannot seem to find any instances of memcached seemingly having some sort of scope, but that is what seems to be happening to me right now. In my views.py, I have a value stored in memcached auto increment every time the page loads. I know this is working because after about 30 reloads, it is at about 30. However, if I try to access this variable from python manage.py shell, for example, the value stored there does not work. Furthermore, any values I store in that shell will persist only while that shell is running. Here is what I am doing in the shell: from django.conf import settings from django.core.cache import cache > cache.get('my_incr_key') # This auto-increments in views.py None > cache.get('my_new_key') None > cache.set('my_new_key', 12, None) > cache.get('my_new_key') 12 The problem is, if I exit the shell, then run this again, the same exact thing will happen: most notably, getting my_new_key will still return None. That I cannot see the value stored in my_incr_key suggests to me that there is a scope issue at play. This is driving me absolutely nuts! Is there such a thing as scope for memcached? Is that what is at play here? How … -
how to implement search and sorting function in Django table
I know that there are Django-datatable, django_tables2, and even django_filter to perform search and sorting to the table. But is there any easy way to perform search and sorting for each column in Django table ? I have tried using Django-datatable, django_tables2 and even django_filter, but none of them work. I have attached my code for the template. I am rendering two different tables using the code below, one is with action and status column while the other is without these two columns. {% if some %} <table id="example" class="display" cellspacing="0" width="100%" border="1.5px"> <tr align="center"> <th style="font-family: Calibri" > Student ID </th> <th style="font-family: Calibri" > Student Name </th> <th style="font-family: Calibri" > Start Date </th> <th style="font-family: Calibri" > End Date </th> <th style="font-family: Calibri" > Action </th> <th style="font-family: Calibri" > Status </th> </tr> {% for item in query_results %} <tr align="center"> <td style="font-family: Calibri" > {{item.studentID}} </td> <td style="font-family: Calibri" > {{item.studentName}} </td> <td style="font-family: Calibri" > {{item.startDate|date:'d-m-Y'}} </td> <td style="font-family: Calibri" > {{item.endDate|date:'d-m-Y'}} </td> <td style="font-family: Calibri" > {% if item.status == 'Approved' %} {% else %} <a href="{% url 'timesheet:edit' id=item.id status='a' %}"><button onclick="alert('timesheet accepted')">Approve</button></a> <a href="{% url 'timesheet:edit' id=item.id status='d' %}"><button onclick="alert('timesheet denied')")>Deny</button></a> {% … -
Django. How to compare expired_date to datetime.now()
I am using django to build an appointment web. I want to compare every appointments time to DateTime.now(), so the appointment can expire 2 hours before DateTime.now(). For example, suppose there is an appointment with a time of "11/07/2017, 7 PM". It should be expired at "11/07/2017 5 PM". Users have to book the appointment at least 2 hours earlier than the appointments time. -
Factory Boy - inherit strategy for SubFactory
I'm trying to create a Django model instance using "build" strategy (e.g. create in-memory objects and do NOT commit it to the database). The model has a foreign key to another Django model - Survey, so I was hoping to use SubFactory to instantiate that model: class SurveyInvitation(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) . class SurveyInvitationFactory(factory.DjangoModelFactory): class Meta: model = models.SurveyInvitation survey = factory.SubFactory(SurveyFactory) When I call the build function: survey_invitation = SurveyInvitationFactory.build() it does create an instance of SurveyInvitation model in memory, but it apparently creates a saved instance of Survey model (using a "create" strategy, I suppose). Is it possible to tell Factory boy to propagate the strategy I choose to subfactories? -
Django paginator not providing content on next page
I use Django paginator to break my search results to few pages from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger In my view I perform the search based on the output from the form @login_required def payment_range_list(request): #import pdb; pdb.set_trace() title = 'payment list' #import pdb; pdb.set_trace() if request.method == "POST": form = PaymentRangeForm(request.POST) #import pdb; pdb.set_trace() if form.is_valid(): start_date = form.cleaned_data['start_date'] end_date = form.cleaned_data['end_date'] building = form.cleaned_data['building'] payment_list = LeasePaymentFilter(request.GET, queryset=LeasePayment.objects.filter(payment_date__range=[start_date, end_date],lease__unit__building = building )) paginator = Paginator(payment_list, 25) # Show 25 contacts per page page = request.GET.get('page') try: payment_page = paginator.page(page) except PageNotAnInteger: payment_page = paginator.page(1) except EmptyPage: payment_page = paginator.page(paginator.num_pages) else: payment_list = None payment_page = None start_date = None end_date = None building = None else: payment_list = None payment_page = None start_date = None end_date = None building = None #form = PaymentRangeForm() form = PaymentRangeForm(initial = {'building': 0 }) return render(request,'payment/payment_range.html', {'form':form, 'payment': payment_list,'page_payment':payment_page, 'start_date':start_date, 'end_date':end_date, 'building':building }) On the top of the page I have a form that I use for search and 2nd part is used to display the results. {% extends "rent_base.html" %} {% load crispy_forms_tags %} {% block title %} Lease List {% endblock title %} {% block content %} <div class="container-fluid"> … -
How do I prefetch all objects in a database with Django ORM?
I need to migrate a large amount of data from another database, and it's running very slowly because I have to constantly check if the object already exists so I don't have duplicates. Is it possible to have a queryset which prefetches all objects? Kind of like Asset.objects.prefetch_all(). I don't think I can use prefetch_related for this since it only prefetches related objects. -
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.