Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to deal with "one-off" data in Django
I am looking for input, ideas or suggestions. I am wrestling a little with how to handle "one-off" data in Django. How do you handle one-off data in Django? I mean for data or content that doesn’t require an app – such as perhaps a logo, an address or company info like VAT number etc. Perhaps I am asking if there is a clever way of mimicking data files in static generators like Hugo or Jekyll? How do you deal with stuff like this? -
get selected value from select form to pass value in url Django
I am using django 1.9.2. I have HTML form like this: <select class="form-control" style="width:50%;" id='selectedTask' name ='selectedTask' onchange='populateProject(this.id,"selectedProject")'> <option value="-1" >Select your Task</option> {% for task in all_tasks %} <option value="{{task.task_id}}">{{task.task_name}}</option> {% endfor %} </select> <a href="{% url 'projects:edit_task' selectedTaskId %}"> &nbsp;&nbsp;<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> </a> How I can send selectedtaskId, when click edit link through href? Thanks Shaon -
Django model building for monitoring system (IoT)
I am building an IoT project with devices that will capture climate data (like weather stations). I am using Django for the server-side functions and data management, and django-rest-framework for communication with the devices. My problem is with building the models. Here are my models.py: class Devices(models.Model): deviceid = models.CharField(max_length=100) devicesecretid = models.CharField(max_length=100) longitude = models.DecimalField(max_digits=20, decimal_places=16) latitude = models.DecimalField(max_digits=20, decimal_places=16) def __str__(self): return self.type + ' - ' + self.deviceid class DeviceData(models.Model): device = models.ForeignKey(Devices, on_delete=models.CASCADE) requestid = models.PositiveIntegerField() temperature = models.DecimalField(max_digits=5, decimal_places=2) humidity = models.DecimalField(max_digits=5, decimal_places=2) rain = models.DecimalField(max_digits=5, decimal_places=2) sunlight = models.DecimalField(max_digits=5, decimal_places=2) battery = models.DecimalField(max_digits=5, decimal_places=2) co2 = models.DecimalField(max_digits=5, decimal_places=2) added = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.requestid) + ' - ' + str(self.added) With my existing code I am building 2 tables (please correct if I am wrong), one which will contain all the weather stations (id, secretid, longitude, latitude) and the other one all the data captured by all of them. Let's assume that we have 10,000 working weather stations that will send data every 15 minutes. This will mean that after a year, our tables will look like that: -Devices: 10,000 rows because there are 10,000 devices -DeviceData: 350,400,000 rows because there are 10,000 … -
Django Facebook Graph API insert data in database
I've created a python script to load information about Facebook events (with the Facebook Python SDK). I want to create a button in Django Admin, with which I can execute the script, to insert the data in my MySQL Database. But how can I create a MySQL Query in the python script to insert the data? I've tried it with Event.objects.create(name=.., description=..) Event is the name of my module and I've imported it with: from models import Event But when I execute my script with "python3 script.py" the console prints the following error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Thanks for your help! -
Detecting the website the user has visited from
I need to detect where a user has visited from when landing on the signup page to my web application. I'm adding a referral to the signup form and at the the moment it's only one external website that will be pushing traffic through to my website.(More site to be added at a later date). The obvious solution would be to add a dropdown asking "Where did you hear about us?" which may be the route i go down. However, i'd like to be a little cleverer than that. I know the URL in which they are visiting from, i can also ask to pass parameters if that would help. I'm currently using {{ request.META.HTTP_REFERER }}inside the template as test, which seems to find for detecting the previous page visited on my local website. However, it's hard to test at this stage. Also, the session could be lost due to numerous reasons see here Are these my only two options? Has anyone else done something like this before? Ideally i'd like the dropdown to auto populate based on the external site the user has come from. The end goal is target those people with specific emails based on the original … -
How to implement real time code editor & compiler with Django REST framework?
I want to implement real-time code editor & compiler(Python) where peer-to-peer communication is possible (something like CoderPad is providing). I want to use Django for this task. Please help me out with this. -
Django REST Framework - Filtering against the URL
I am using the Django REST Framework toolkit with Django 1.11 and I am trying to filter the results against the url. Here is my setup: models.py: from django.db import models class Package(models.Model): name = models.CharField(max_length=255, unique=True) def __str__(self): return self.name serializers.py: from rest_framework import serializers from .models import Package class PackageSerializer(serializers.ModelSerializer): class Meta: model = Package fields = ('name',) views.py: from rest_framework import viewsets from .models import Package from .serializers import PackageSerializer class PackageViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = PackageSerializer queryset = Package.objects.all() urls.py from django.conf.urls import url, include from django.contrib import admin from rest_framework import routers router = routers.DefaultRouter() router.register(r'package', views.PackageViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/v1/', include(router.urls)), ] Currently when I use this I can filter the results by the id field: http://127.0.0.1:8000/api/v1/package/1/ I am hoping to filter the results by the name field of my package model instead by using this: http://127.0.0.1:8000/api/v1/package/basic/ How would I be able to accomplish this? -
Running pylint with pylint_django throws error
Installed pylint with pip. Installed pylint-django with pip. When pylint is invoked with pylint --load-plugins pylint_django /projectsource throws the following erros Traceback (most recent call last): File "../bin/pylint", line 11, in sys.exit(run_pylint()) File "../lib/python3.6/site-packages/pylint/init.py", line 16, in run_pylint Run(sys.argv[1:]) File "../lib/python3.6/site-packages/pylint/lint.py", line 1268, in init linter.load_plugin_modules(self._plugins) File "../lib/python3.6/site-packages/pylint/lint.py", line 495, in load_plugin_modules module.register(self) File "../lib/python3.6/site-packages/pylint_django/plugin.py", line 22, in register start = name_checker.config.const_rgx.pattern[:-2] AttributeError: 'NoneType' object has no attribute 'pattern' Please help! -
Travis CI Deploy by SSH Script/Hosts issue
I have a django site which I would like to deploy to a Digital Ocean server everytime a branch is merged to master. I have it mostly working and have followed this tutorial. .travis.yml language: python python: - '2.7' env: - DJANGO_VERSION=1.10.3 addons: ssh_known_hosts: mywebsite.com git: depth: false before_install: - openssl aes-256-cbc -K *removed encryption details* -in travis_rsa.enc -out travis_rsa -d - chmod 600 travis_rsa install: - pip install -r backend/requirements.txt - pip install -q Django==$DJANGO_VERSION before_script: - cp backend/local.env backend/.env script: python manage.py test deploy: skip_cleanup: true provider: script script: "./travis-deploy.sh" on: all_branches: true travis-deploy.sh - runs when the travis 'deploy' task calls it #!/bin/bash # print outputs and exit on first failure set -xe if [ $TRAVIS_BRANCH == "master" ] ; then # setup ssh agent, git config and remote echo -e "Host mywebsite.com\n\tStrictHostKeyChecking no\n" >> ~/.ssh/config eval "$(ssh-agent -s)" ssh-add travis_rsa git remote add deploy "travis@mywebsite.com:/home/dean/se_dockets" git config user.name "Travis CI" git config user.email "travis@mywebsite.com" git add . git status # debug git commit -m "Deploy compressed files" git push -f deploy HEAD:master echo "Git Push Done" ssh -i travis_rsa -o UserKnownHostsFile=/dev/null travis@mywebsite.com 'cd /home/dean/se_dockets/backend; echo hello; ./on_update.sh' else echo "No deploy script for branch '$TRAVIS_BRANCH'" fi … -
User logged out mid-test
I'm testing a Django UpdateView but for some reason my user is logged out mid-test: def test_edit_user(self): response = self.client.login(email=USERNAME, password=PASSWORD) self.assertTrue(response) response = self.client.get(reverse('user-edit', kwargs={'slug': 'aaa'})) self.assertEqual(response.status_code, 200) response = self.client.post(reverse('user-edit', kwargs={'slug': 'aaa'}), {'email': 'jane.bond@gmail.com', 'first_name': 'James', 'last_name': 'Bond', 'password': 'qqq'}) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, reverse('user-list')) response = self.client.get(reverse('user-edit', kwargs={'slug': 'aaa'})) self.assertEqual(response.status_code, 302) self.assertIn(b'jane.bond@gmail.com', response.content) user = User.objects.filter(email='jane.bond@gmail.com')[0] self.assertEqual(user.email, 'jane.bond@gmail.com') I use the standard class-based views and all my views inherit from LoginRequiredMixin along with the expected Django parent views. My problem is that when I get to the second instance of response = self.client.get(reverse('user-edit', kwargs={'slug': 'aaa'})), it sends my request to the login url, indicating that the user has been logged out. Mid test. Which is very confusing. Help? -
how to fix 500 error nginx django?
How to fix 500 error last line into file "nginx-error.log" 2017/12/18 16:30:06 [crit] 27927#27927: *25 connect() to unix:/webapps/theband/run/gunicorn.sock failed (2: No such fil$/ HTTP/1.1", upstream: "http://unix:/webapps/theband/run/gunicorn.sock:/", host: "207.154.232.99" Everything was fine, until the last commit (but the commit was only cosmetic in nature) The new commit, carried in itself such changes: 1) added views.py to the root of the program, to create a view for the handler 404 and 500 errors. 2) added the following lines to the URL: from django.conf.urls import include, url, handler404, handler500 from .views import error_404, error_500 -- into views was that { from django.shortcuts import render def error_404(request): return render(request,'error_404.html') def error_500(request): return render(request,'error_500.html') } also in urls.py was this: handler404 = error_404 handler500 = error_500 3)then a'll minify js file in one line, remove from main.css navbar css codes, to add into base.html, for optimized code, (first screen load head) then full css and js file oading while you look header 4) i'll add 404 and 500 html files to templates folder that's it! __ (((after the comit had an error 404)) after updating the nginx configuration file to register the correct path for errors 404 and 500, everything restarted nginx and everything became … -
Invalid field name(s) given in select_related: 'target'. (Can't use GenericForeignKey as a field)
How do we use GenericForeignKey in Model? class Like(models.Model, Activity): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) # user can like any type of object content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() target = GenericForeignKey('content_type', 'object_id') created_at = models.DateTimeField(auto_now=False, auto_now_add=True) objects = LikeManager() @classmethod def activity_related_models(cls): return ['user', 'target'] // I can't call target field name. Invalid field name(s) given in select_related: 'target'. Choices are: user, content_type Interesting thing is Like.objects.first().target returns correct 'targeted' component. How do we use GenericForeignKey in Model? I have to set target to point to the right instance. -
Why is Django request.POST always empty using PATCH or PUT requests?
I have a simple class-based view: class MyView(View): def patch<or put for example>(self, request, pk): form = ParentUpdateForm(request.POST) if not form.is_valid(): return HttpResponse(json.dumps(form.errors), status=422) return HttpResponse() I try to send multipart/form-data to a server but request.POST contains <QueryDict: {}>. When I change def patch to def post everything works just fine! According to my search in the web request.POST shouldn't be empty. Any help would be appreciated! -
no foreign or candidate key data model issue
I'm attempting to get my data model correct, but I keep getting errors the model doesn't exist depending on the order of the models or a SQL error stating there is no foreign or candidate key in the table. I'm struggling to get the User tables coid field to relate to my FacilityDimension model on coid, it keeps trying to relate on formattedusername. I've tried using ForeignKey instead of OneToOneField. I've also tried using relatedname =. I've simplified all models and removed fields that aren't key fields. I'm working with an existing data set except for the User table and QVFormAccessRequest. This is the Custom User table: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=7, unique=True) formattedusername = models.CharField(max_length=11, unique=True, primary_key = True) coid = models.CharField(max_length=5) USERNAME_FIELD = 'username' class Meta: app_label = 'accounts' db_table = "user" def save(self, *args, **kwargs): self.formattedusername = '{domain}\{username}'.format( domain='HCA', username=self.username) super(User, self).save(*args, **kwargs); def get_short_name(self): return self.username # REQUIRED_FIELDS = "username" def __str__(self): return '%s - %s %s' % (self.username, self.first_name, self.last_name) Here is my Facility Model: class FacilityDimension(models.Model): coid = models.CharField(db_column='Coid',primary_key=True, serialize=False, max_length=5) # Field name made lowercase. class Meta: managed = False db_table = 'Facility_Dimension' Request Model: class QVFormAccessRequest(models.Model): ntname = models.OneToOneField(settings.AUTH_USER_MODEL, max_length=11) coid … -
How to custom django-tables2 template for a specific page ?
I'm using django-tables2 to render my data in tables in the template.. everything is rendered fine with pagination.. The Designer of our company wants to change the Display of data into blocks instead of simple table. the following picture may explain more. I Want to ask if I can use Django tables2 in this case ..since I don't want to loose the pagination Is it possible to custom the django_tables2/table.html file to only fit this case (because I'm using django-tables2 in many other pages in the project)? Any other ideas may be helpful. Thanks in advance :) -
How to write test case for below code in Django, python?
I need to write test cases for python scripts being developed for a web application. The framework is Django framework. I followed many websites, and did research about how to write test cases. But thing is that, if suppose I need to write a test case for a particular feature, example: not entire module- particular lines of codes in a module, how do I need to test that code? I am confused about this thing. THere are many tools, and many ways of writing tests, but I am confused where I need to start. Could you suggest me the best way of learning and implementing tests. For an example, one my task for writing tests is written below: Sorted rating filter for category in search_results: for r in category: name_id = r["name_id"] obj = get_element(name_id) rating_sorting = get_review_average(obj) r['rating_sorting'] = rating_sorting return render(request, 'XXXapp/search.html', {'result': search_results, 'type': search_type, }) The backend code is written for sorting a particular feature. Now I need to write test case for this. -
passing an event with ajax post to view with csrf token
I have been browsing a lot on the topic and despite all the similar solved questions I am having trouble solving this one. I am trying to pass a simple click event to a view with the following ajax post: $('#continue').click(function() { // var csrftoken = getCookie('csrftoken'); $.ajax({ url: window.location.pathname, method: 'POST', info: 'ReadLSL', data: {csrfmiddlewaretoken: getCookie('csrftoken')}, success: function (data) {console.log("Acc Data is being saved to DB");} }); }); // GET CSRF COOKIE _________________________________________________________________________________ function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } but I keep having a 405 Method Not Allowed error. -
Javascript included in base.html doesn't work in extending template
I have the following project file structure: In base.html, I'm importing some JS that is meant to add an onclick event to the button in the html file: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Default Title{% endblock %}</title> <link rel="stylesheet" href="{% static 'css/workoutcal.css' %}"> </head> <body> {% block userwidget %} <button type="button" id="logoutbutton">Logout</button> {% endblock %} {% block content %}{% endblock %} {% block footer %}{% endblock %} <script type="text/javascript" src="{% static "js/base.js" %}"></script> </body> </html> base.js: logoutbutton = document.getElementById("logoutbutton"); logoutbutton.onclick = logout; function logout(){ window.location = "/workoutcal/logout"; } Then, in calendar.html: {% extends "workout/base.html" %} {% block title %}{{ title }}{% endblock %} The button shows up in the browser, but when I click it, nothing happens. From the browser console I get these errors: GET http://localhost:8000/static/js/base.js net::ERR_ABORTED localhost/:359 GET http://localhost:8000/static/js/base.js 404 (Not Found) Sto the static files are obviously not found. Am I doing something wrong? -
How to change the option values with django-autocomplete-light?
I use django-autocomplete-light in a fairly standard way, simply following the tutorial on http://django-autocomplete-light.readthedocs.io/en/master/tutorial.html. Whenever I use the Select2 widget, however, the values of the options are automatically the primary keys of the model instances. Is there a way to use set the value to another field of the model? -
Django social auth how to access authenticated user data in template
I have implemented django social auth in my project which is working fine, Now i want to display authenticated user's data in header template. what is the proper way to do that? One way i think might be context_processors but how can i access "extra_data" in social responce, like gender and phone? -
"OSError: mysql_config not found" when trying to "pip install mysqlclient" - Django
I'm relatively new to Django, and Web Development in general. I am trying to pip install mysqlclient in my virtualenv -p python3 to hook up Django 2.0 to mySQL. However, I'm getting this error: Collecting mysqlclient Using cached mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/43/md5vpqrx0mx8627sq04slbz00000gn/T/pip-build-l8ea3vja/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/private/var/folders/43/md5vpqrx0mx8627sq04slbz00000gn/T/pip-build-l8ea3vja/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/private/var/folders/43/md5vpqrx0mx8627sq04slbz00000gn/T/pip-build-l8ea3vja/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/43/md5vpqrx0mx8627sq04slbz00000gn/T/pip-build-l8ea3vja/mysqlclient/ I have looked around for answers for hours, and yes, I have checked out this and this but nothing seems to be working. Any help would be much appreciated! -
Unable to install Django in my mac - Command "python setup.py egg_info" failed with error code 1
I tried to install Django using sudo pip install Django command. It has downloaded but got stuck to error - Command "python setup.py egg_info" failed with error code 1. Terminal I've installed Python 3.6.3, but pip still pointing to Python 2.7, is above issue occurs because of pip not pointing to python 3.6.3? Terminal -
custom django form template (in bootstrap)
I would like to customize my django forms. For example, in my code I have working hour settings which I like to produce like this format: mon_start mon_end tue_start tue_end .... but instead it creates a form mon_start mon_end tue_start tue_end .... Here is a view of the output that I dont want https://imgur.com/a/cPxTW Below are my code: forms.py class CompanyWorkingHoursSettingsForm(forms.ModelForm): mon_start = forms.TimeField() mon_end = forms.TimeField() tue_start = forms.TimeField() tue_end = forms.TimeField() class Meta: model = Workinghours fields = ("mon_start","mon_end","tue_start","tue_end") workinghourssettings.html {% extends 'project/base.html' %} {% load bootstrap3 %} {% block page %} <div class="col-lg-12"> <div class="panel"> <div class="panel-heading bg-blue"> <h4 class="panel-title text-center text-white"> Working Hours Settings </h4> </div> <div class="panel-body"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form company_workinghourssettings_form %} <button type="submit" class="btn btn-pink">Update</button> </form> </div> </div> </div> {% endblock %} How do i produce a custom arranged form for my form fields above ? (in bootstrap) -
TypeError: export_users_xls() missing 1 required positional argument: 'request'
when I am trying to run i got this error File "/home/normsoftware/WORK/JVB/healthtracker/quicklook/urls.py", line 39, in <module> url(r'^users/print$',views.export_users_xls(),name="Exceldata"), TypeError: export_users_xls() missing 1 required positional argument: 'request' views.py def export_users_xls(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="users.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Users') # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['first', 'last',] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = Registration.objects.all().values_list('first', 'last') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response all line indentations are correct urls.py url(r'^users/print$',views.export_users_xls(),name="Exceldata"), -
Database Value in PDF Django
How can i display my data in database and export it to pdf -Django? my x variable is getting all the data in my database, i guess? someone help me how can i display all data and export it to pdf file. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="WishList.pdf"' buffer = BytesIO() # Create the PDF object, using the BytesIO object as its "file." p = canvas.Canvas(buffer) x = Item.objects.all() p.drawString(100, 100,x) p.drawString(200,300,"bills") # Close the PDF object cleanly. p.showPage() p.save() # Get the value of the BytesIO buffer and write it to the response. pdf = buffer.getvalue() buffer.close() response.write(pdf) return response