Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: type object 'Mock' has no attribute 'MagicMock', testing django file field [on hold]
I'm trying to test a django model that contains a file field. I am using mock in order to create the file for testing. I need to use Mock.MagicMock so the I don't get the TypeError: 'Mock' object is not iterable error from django when it saves the file. from django.core.files import File as django_file from django.test import TestCase import lorem from unittest.mock import Mock from .models import ProfileUser class ProfileModelTests(TestCase): @classmethod def setUpTestData(cls): mock_resume = Mock.MagicMock(spec=django_file, name='resume') mock_resume.name = 'resume.pdf' for i in range(5): ProfileUser.objects.create( name='test name%s' % i, title='title', cell_phone='(555)555-5555', office_phone='(555)555-5555', email='testuser%s@test.com' % i, about_me=lorem.paragraph, resume=mock_resume, facebook_profile_link='https://www.facebook.com/testuser%s' % i, twitter_profile_link='https://www.twitter.com/testuser%s' % i, linkedin_profile_link='https://www.linkedin.com/testuser%s' % i, github_profile_link='https://www.github.com/testuser%s' % i, google_plus_profile_link='https://plus.google.com/+testuser%s' % i, stackoverflow_profile_link='https://stackoverflow.com/users/testuser%s' % i ) def test_model_creation(self): all_profiles = ProfileUser.objects.all() self.assertEqual(len(all_profiles), 5) -
Apps not loaded yet when using actstream django
So i'm trying to create an application for user interaction with stream_django. So far everything was going well until I got error: 'User model not registered. Please register model with actstream.registry'. So after searching for some time, I modified my apps.py to be like this: The project is called reviews # -*- coding: utf-8 -*- from __future__ import unicode_literals import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "reviews.settings") os.environ["DJANGO_SETTINGS_MODULE"] = "reviews.settings" django.setup() from django.apps import AppConfig from django.contrib.auth.models import User class MyappConfig(AppConfig): name = 'myapp' def ready(self): from actstream import registry registry.register(User,self.get_model('Post'),self.get_model('UserProfile')) But now I'm getting error: 'AppRegistryNotReady("Apps aren't loaded yet")' I'm not sure what to do anymore, any help is appreciated. -
Django: Issue with cross-app ModelChoiceField returning an integrity error
Good afternoon -- I'm still feeling myself around Python and Django and I'm running into a question that I can't seem to figure out. I've created a Project with multiple apps in it and I'm trying to centralize repeated data. What I'm trying to is have a county that is in the Clients app work in the same capacity as what's in the Calllog app. Here's what I have: clients/models.py class County (models.Model): county = models.AutoField(primary_key=True) county_name = models.CharField(max_length=200, null=False) state = models.ForeignKey(State, default=26) avenues_support = models.BooleanField(default=0) def __str__(self): return self.county_name calllog/models.py from clients.models import County class CallLog(models.Model): county_of_incident = models.ForeignKey(County, null=False, related_name='call_log_county_of_incident') calllog/forms.py from clients.models import County class Call_Log_Create(forms.ModelForm): county_of_incident = forms.ModelChoiceField(queryset=County.objects.filter(avenues_support=1), required=True) In the form, the dropdown box for County of Incident populates with the counties in the database. After selecting the county and hitting submit, I get an IntegrityError (1048, "Column 'county_of_incident_id' cannot be null") I'm not sure what's causing this issue and have been stuck on it for a couple of days. Any help would be appreciated. -
Developing Django with Docker
I am trying to create myself a development environment for a Django web app using Docker. My question is how should I set it up for development? I've created a Dockerfile which uses the Django dev server and db, is that good? Or should I use separate container with dedicated web and db servers? How should I create new migrations? Let's say I'm mounting the code into the container using -v, changes to models requires creating new migrations, so, should I make the mount writable and use create migrations from within the container? What other options are there? I'm thinking about adding a RUN instruction to the Dockerfile which will apply the migrations in order to use cache when the migrations haven't changed. Is this a good practice? -
Language selection from dropdown
I could use this code: mytemplate.html: <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <select name="language"> {% get_current_language as LANGUAGE_CODE %} <option value='it' {% if 'it' == LANGUAGE_CODE %} selected{% endif %}> Italiano</option> <option value='en' {% if 'en' == LANGUAGE_CODE %} selected{% endif %}> English</option> </select> <input type="submit" value="Go" /> </form> It works translating my page without changing the url. But I don't like how it look, I prefer a dropdown menù (it look better in my toolbar, also I can add images). I tried many things until I found this: <a class='dropdown-toggle' data-toggle='dropdown' role='button' aria-expanded='false'>Lingua<span class='caret'></span></a> <ul class='dropdown-menu' role='menu'> <li><a href="/it{{ request.get_full_path }}" class='language' lang='it'><img width='16' height='12' src="{% static 'icons/italian.png' %}" alt='Italiano' /> Italiano</a></li> <li><a href="/en{{ request.get_full_path }}" class='language' lang='en'><img width='16' height='12' src="{% static 'icons/english.png' %}" alt='English' /> English</a></li> </ul> but this add a prefix to my url (it/ or en/) and my url haven't prefix, so it gives page not found 404. Is there a way to use the standard django view with a dropdown menù? -
Unsupported media type Django API
I'm new T Django and my project is in REST when i'm using postman to check URLs it's make this error "detail": "Unsupported media type \"multipart/form-data; boundary=----WebKitFormBoundaryAU1ShXHTHrfcQr61\" in request." please help me to undrestand what is the problem and say in details. -
If foreign key does not exist create it. Django framework
Imagine you have a table A which has a foreign key pointing to other table B, but in that B table there is no such key. What should you do if you want to achieve this functionality - add the key in the table B if the key does not exist? Are there any serious concerns about performance issues? -
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?