Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot importe module in a folder created mannually
I come from Rails and started with Django projects. I want to create a folder services (like rails services) that will contain classes that consume from an API and save the data retrieved in our database, in fact, those are jobs that are executed sometimes per day. I created a folder manually called services into app. The structure: - root - app - services - job_1.py - migrations __init__.py models.py apps.py ... I created the folder manually and added a file call job_1. The problem is that I need to import a model from job_1.py but I can't because I am getting the error : "ImportError: No module named app.models" Note that I tried to import the models from the migrations and there is no problem. Two questions : 1- It's corect to create a folder services manually? (I added the init.py) 2- Why I am getting this error? How can I solve it? -
Django Rest Framework view get_queryset is called twice
I have this ModelViewset and a ModelSerializer class GenerarFacturaViewset(viewsets.ModelViewSet): serializer_class = serializer.FacturaSerializer queryset = None def get_queryset(self): self.queryset = [] _nro = self.request.query_params.get('nro', None) venta_id = self.request.query_params.get('ventaid', None) if (venta_id is None or _nro is None): raise exceptions.ParseError("Parametros invalidos") nro = int(_nro) venta = models.Venta.objects.get(id=venta_id) if models.Factura.objects.filter(numero=nro): raise exceptions.ParseError("Ya existe una factura con ese numero") venta.generar_factura(nro) print("Factura generada con nro: ", nro) self.queryset = models.Factura.objects.filter(numero=nro) return self.queryset Then when this ModelViewset is called the first time every work correctly until the return sentence then the get_queryset method is called again. I want to know why? Other detail is that when the second exception is raised in the first get_queryset call, this is show as rest framework normal template but if it is raised in the second called, it is show in the django error template with the traceback and error messages. thanks in advance -
KeyError: 'SECRET_KEY' django migrate?
I put a secret key but appears this error KeyError: 'SECRET_KEY' this is my code of secrets.sh export SECRET_KEY='9xmh4sl%uz57f-m9mudxp)@e(rx%)oaawz_r^n-nh$rl_@!$i&' please help me -
ValueError when attempting to to use LinkColumn with django-tables2
I have been trying to debug this to no avail. When I use django-tables2's LinkColumn, I get a ValueError: File "/Users/site/New/env_qmcdb/lib/python2.7/site-packages/django/urls/resolvers.py" in _populate 217. dict(defaults, **pattern.default_kwargs), Exception Type: ValueError at / Exception Value: dictionary update sequence element #0 has length 1; 2 is required My url: url(r'^material_overview/(?P<material_id>\w+)/$', records_views.material_overview, name='material_overview') My LinkColumn: formula = tables.LinkColumn(accessor='formula',viewname='material_overview',kwargs={'material_id':A('pk')},verbose_name='Formula') I have manually entered pk ids for the url and the link works. It is only when I use the LinkColumn that it fails. I should note that I am using mongoengine with this if it makes a difference. I would appreciate any help I can get. -
what should put in config files django install?
i read this tutorial but i dont know that should put in this part https://simpleisbetterthancomplex.com/2015/11/30/starting-a-new-django-18-project.html First, remove the os import and the BASE_DIR definition and add the following imports: from decouple import config from unipath import Path import dj_database_url Define the PROJECT_DIR: PROJECT_DIR = Path(__file__).parent i put this but dont works import os from decouple import config from unipath import Path import dj_database_url PROJECT_DIR = "/home/diegonode/simple_django_skeleton/proyecto" please help me -
Python3: Loop over objects and add attributes to an array or object
I'm trying to loop through some objects and add certain attributes to an array to be sent back as JSON to the view: data = {} camera_logs = CameraLog.objects.filter(camera_id=camera_id) for log in camera_logs : setattr(data, 'celsius', log.celsius) return JsonResponse(data) I'm quite new to Python, so I'm not sure if I'm even on the right track. -
Error importing a Django proyect from windows to linux
I worked in a project using python3 and django from a WIN7 computer, now I am at home in my GNU/Linux one and I am tryng to make it work but I have some errors. I unpackage the whole thing in a folder and in that one I have installed a virtualenv with django, inside the folder I put the proyect I have, then I make python3 manage.py makemigrations and python3 manage.py migrate then python3 manage.py runserver I log in in the server and everything is there, every data, model, etc. So far works well. but then I try to run a script and got this error: mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/alex/proyectosP/ahq/11_env/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 2254, in _gcd_import File "", line 2237, in _find_and_load File "", line 2212, in _find_and_load_unlocked File "", line 321, in _call_with_frames_removed File "", line 2254, in _gcd_import File "", line 2237, in _find_and_load File "", line 2224, in _find_and_load_unlocked ImportError: No module named 'subastas' The script in question has this header import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "subastas.settings") import django django.setup() I copyed everything exact as I have in my other computer -
Django celery and celery-beat daemonizing script error
Im going to set periodic tasks with celery for what im trying to daemonize a django celery process in a test server using a script (referenced on the official website): Init-script: celery So, this is my celeryd file: # Names of nodes to start # most people will only start one node: CELERYD_NODES="indicators" # but you can also start multiple and configure settings # for each in CELERYD_OPTS (see `celery multi --help` for examples): #CELERYD_NODES="worker1 worker2 worker3" # alternatively, you can specify the number of nodes to start: #CELERYD_NODES=10 # Absolute or relative path to the 'celery' command: #CELERY_BIN="/usr/local/bin/celery" CELERY_BIN="/opt/pymis/envs/indicators/indicators_test/bin/celery" # App instance to use # comment out this line if you don't use an app #CELERY_APP="sgiprocess" # or fully qualified: CELERY_APP="indicator.tasks:app" # Where to chdir at start. CELERYD_CHDIR="/opt/pymis/reps/indicator_repository/indicator_ms/" # Extra command-line arguments to the worker CELERYD_OPTS="--time-limit=300 --concurrency=8" # %N will be replaced with the first part of the nodename. CELERYD_LOG_FILE="/var/log/celery/worker1.log" CELERYD_PID_FILE="/var/run/celery/worker1.pid" # Workers should run as an unprivileged user. # You need to create this user manually (or you can choose # a user/group combination that already exists, e.g. nobody). CELERYD_USER="celeryuser" CELERYD_GROUP="mygroup" # If enabled pid and log directories will be created if missing, # and owned by the … -
Apache not serving wsgi with non-master git branch in django project
I have a django app that I am developing using git. I have a repo which is cloned locally and on an Ubuntu remote server. I push local changes to github and then pull them to the server to implement them. I have apache set up on the server, serving the app with the wsgi file. I've done this in the past and had no trouble like this. My apache 000-default.conf file has this in it: WSGIDaemonProcess pyprocess python-path=/home/ubuntu/django-app:/home/ubuntu/ENV/lib/python2.7/site-packages WSGIScriptAlias / /home/ubuntu/django-app/wsgi.py process-group=pyprocess <Directory /home/ubuntu/django-app> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> This all worked fine, until I pulled a new, non-master branch from github. I restarted apache in order to reload the python files (which I do whenever I update the master branch), some of which are modified in the new branch. However, I get errors suggesting that apache is not using the newly updated .py files. The kicker is that when I run the dev server on :8000, everything works fine, no matter which branch I'm on. -
restrict objects on models for custom user groups
my problem is i want to restrict some objects in my models to custom group users. is there any way for that? class Ad(models.Model): submit_date = models.DateTimeField(auto_now_add=True) publish_date = models.DateTimeField(default=timezone.now) expire_date = models.DateTimeField(default=now_plus_30_days) title = models.CharField(max_length=100) description = models.TextField() for example i want to group 1 cant accsess to see the publish_date. -
Django rest framework bypass entity in nested relation
Consider these three models: class Genre(models.Model): slug = models.CharField(max_length=30, unique=True) name = models.CharField(max_length=300) class Group(models.Model): slug = models.CharField(max_length=30, unique=True) name = models.CharField(max_length=300) genre = models.ForeignKey('Genre', related_name='groups') class Album(models.Model): name = models.CharField(max_length=300) track_count = models.IntegerField() artist = models.ForeignKey('Group', related_name='albums') Now, I need this kind of DRF output: [ {'name': 'Rock', 'albums': [ {'name': 'Meteora', 'track_count': 12}, {'name': 'Master of Puppets', 'track_count': 10'} ] }, {..}, ] In other words, I need to get all of the albums in each genre, bypassing "group" model. I have achieved something similar this way: views.py class SegmentViewSet(viewsets.ModelViewSet): queryset = Genre.objects.all().annotate(Count('name')) serializer_class = GenreSerializer serializers.py class GroupSerializer(serializers.ModelSerializer): albums = AlbumSerializer(many=True, read_only=True) def to_representation(self, value): return value.products.annotate(Count('id')).values('name', 'sap_code') class Meta: model = Group fields = ('albums',) class GenreSerializer(serializers.ModelSerializer): albums = GroupSerializer(many=True, read_only=True) class Meta: model = Genre fields = ('id', 'name', 'albums') That gives me something like this: [ {'name': 'Rock', 'albums': [ [ {'name': 'Meteora', 'track_count': 12}, {...}, {...} ], [ {...}, {...}] ] } Which is albums, grouped by albums, grouped by genre. That is a nested array and I need just the albums grouped by genre in one array. I know that my solution with to_representation function is pretty dirty, but it is something … -
Django REST Framework - Responding with string without quotes?
For an assignment, I have to make a REST API that, when submitting a POST request to localhost:8080/hello I have this: @api_view(['GET']) def hello(request): if request.method == 'GET': return Response("Hello world!") But when I test it with this: res = requests.get('http://localhost:'+str(PORT)+'/hello') self.assertEqual(res.text, 'Hello world!', msg='GET on the hello resource did not execute successfully') it gives me an error, because the string res.text is being stored as "Hello World!" and it should be stored as Hello World! How would I get the Django REST framework to send the response without quotes? -
Django realtime updates with Firebase
I am currently trying to implement Firebase into my Django app with pattern 3 as indicated here (https://firebase.googleblog.com/2013/03/where-does-firebase-fit-in-your-app.html). I am trying to have Firebase detect whenever the game model starts and to refresh all the other user's pages when this is done. I am unable to find a good tutorial outlining how to do this so any tips at all would be greatly appreciated. Thanks! -
Unit testing Django models accessing str type attributes - not callable
I'm trying to write a simple unittest that tests if my fake_user's (created via FactoryBoy) username already exists. (i.e someone has already created a user w/ the same username). A simple version of the test would be as follows: # factories.py import factory class BaseUserFactory(factory.DjangoModelFactory): """A factory for creating User objects.""" username = factory.Faker('word') email = factory.lazy_attribute(lambda x: '%s@email.com' % (x.username)) class Meta: """User factory Meta attributes.""" model = models.User django_get_or_create = ('username', 'email') a simple test: #test_user.py from django.test import TestCase from django.apps import apps from . import factories class TestAccountModels(TestCase): """Testing the User models.""" users = [user.username for user in models.User.objects.all()] fake_user = factories.BaseUserFactory.create() def test_username_available(self): self.assertIn(self.fake_user.username, self.users) now for context, say my (already existing) username(s) are 'Brody' and 'Sam'. When test_username_available runs I get back: self.assertIn(self.fake_user.username, self.users) AssertionError: 'suscipit' not found in ['Sam', 'Brody'] My questions is this: I want to write a test to test for this specific error. I tried something like this: def test_clean_username(self): self.assertRaises( AssertionError, '"{0}" unexpectedly found in "{1}"'.format( self.proposed_username, self.taken_usernames, ) ) but keep getting str object is not callable (on taken_usernames); and I get that, but just cant seem to find a workaround where: proposed_username = self.fake_user.username self.taken_usernames = [self.user.username … -
Badges With Django
Good afternoon, I work with Django 1.10 and bootstrap and I need to implement badges to handle internal messages and notifications to users of the application. Who can advise me or give a light on how to implement that? I appreciate your collaboration -
Missing auto generated id in django model
I have a class and I skipped the id autogenerated definition because Django is suposed to do it for you. when I instantiate myClass and save a record I have this: instance = myClass(value1, value2, value3) instance.save() It gives me an error on value 3. I saw that if instead of the 3 values I add an integer at the start it will be added and the starting value is the ID I dont understand what I am doing wrong, from the admin interface I can add records with no problems -
Run custom code when adding to Many-To-One relation
from django.db import models class Reporter(models.Model): pass class Article(models.Model): reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) Now whenever I add an article to a reporter (like below) I want to run some custom code, what method should I override? >>> new_article = Article() >>> new_reporter = Reporter() >>> new_reporter.article_set.add(new_article) -
how to pass query strings in urls.py with ?key=value& in django
In the django docs it is noted that: Now in your time on the web you may have come across such beauties as “ME2/Sites/dirmod.asp?sid=&type=gen&mod=Core+Pages&gid=A6CD4967199A42D9B65B1B”. You will be pleased to know that Django allows us much more elegant URL patterns than that. However, I am trying to pass through query strings with this pattern in mind. How might one go about passing key=value pairs as so inside of django's urls.py Also note that this is for project using Angular and Django together. currently my angular patterns are coming out in query string I.E. http://localhost/data/?key1=value1&key2=value2 If you have any further detail on how to handle $http.post, I will take in any advice. -
Graphviz - AttributeError: object has no attribute 'partition'
I'm using graphviz with my Django models to render graphs from the following python script for each automata: alphabets = automata.alphabet_set.all() states = automata.states_set.all() transitions = automata.transition_set.all() dot = gv.Graph() for state in states: dot.node(state.state, state.state) for transition in transitions: dot.edge(transition.current_state, transition.next_state, transition.input) dot.render( automata.id + '.gv', view=True) And these are my models: class Automata(models.Model): pass class Alphabet(models.Model): alphabet = models.CharField() automata = models.ForeignKey(Automata, on_delete = models.CASCADE) class States(models.Model): state = models.CharField() automata = models.ForeignKey(Automata, on_delete = models.CASCADE) class Transition(models.Model): current_state = models.ForeignKey(States, on_delete = models.CASCADE, related_name = 'current') input = models.ForeignKey(Alphabet, on_delete = models.CASCADE) next_state = models.ForeignKey(States, on_delete = models.CASCADE, related_name = 'next') automata = models.ForeignKey(Automata, on_delete = models.CASCADE) but everytime I try to execute my script I get the following error: Traceback (most recent call last): File "make_graph.py", line 36, in <module> dot.edge(transition.current_state, transition.next_state, transition.input) File "/home/nids/automata/auto/lib/python3.5/site-packages/graphviz/dot.py", line 116, in edge tail_name = self.quote_edge(tail_name) File "/home/nids/automata/auto/lib/python3.5/site-packages/graphviz/lang.py", line 63, in quote_edge node, _, rest = identifier.partition(':') AttributeError: 'States' object has no attribute 'partition' Knowing that I have no error if I simply do: dot.edge('A', 'B', 'edge label') -
Will Django use previously-evaluated results when applying additional filters to a query set?
Let's say I need to do some work both on a set of model objects, as well as a subset of the first set: things = Thing.objects.filter(active=True) for thing in things: # (1) pass # do something with each `thing` special_things = things.filter(special=True) for thing in special_things: # (2) pass # do something more with these things My understanding is that at point (1) marked in the code above, an actual SQL query something like SELECT * FROM things_table WHERE active=1 will get executed against the database. The QuerySet documentation also says: When a QuerySet is evaluated, it typically caches its results. Now my question is, what happens at point (2) in the example Python code above? Will Django execute a second SQL query, something like SELECT * FROM things_table WHERE active=1 AND special=1? Or, will it use the already-cached results, automatically doing for me behind the scenes something like the more optimal filter(lambda d: d.special == True, things), i.e. avoiding a needless second trip to the database? -
Converting KML into Postgis- Django/Python
I am fairly new to Django and have been stuck on this for over a week. I am teaching myself how to code and trying to make a personal site with mapping data. I am trying to use the data I have pulled from a javascript map on html, which is formatted into a kml/xml string and stored in a text box. I have trouble using the mapping resources (geodjango, postgis) to take the kml string and placing it in the database. Documentation seems to be very limited and searched high and low on the internet. Here is the break down of what I have: Html: (map) Button to place kml string into text area <input name="mapdata" type="button" value="Generate KML" onclick="convert_to_kml"/> <textarea id="kmlString" style="blahblah"></textarea> Models: class JobMap(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=200) mpoly = models.GeometryCollectionField(srid=4326) objects = models.GeoManager() def __str__(self): return self.name` Views: def map_import(request): if request.method == 'POST': map_data = request.POST.get('kmlString') #Create a temp file of the string (I think it needs to be a temp file in order for ogr2ogr can read it) f = request.FILES[map_data] temp = tempfile.NamedTemporaryFile(delete=False) temp.write(f.read()) temp.close() JobMap.objects.raw('''ogr2ogr - f "PostgreSQL" PG:"host=localhost user=user dbname=database password=password" temp.name''') I want to convert all of the … -
Django admin load jquery after site is loaded
I have this small Jquery function that needs to run on the model admin page after the element is loaded onto the screen. I attempted loading it with the rest of my init scripts in the formfield (TinyMCE) for the field below it however this is not working. Script to run console.log($( "#id_dir" )) console.log($( "#id_path" )) $( "#id_dir" ) .change(function () { var str = ""; $( "#id_dir option:selected" ).each(function() { str += $( this ).text(); }); $( "#id_path" ).val(str); console.log("Change run") }) here is the result of the log on the page: n.fn.init {context: document, selector: "#id_dir"} n.fn.init {context: document, selector: "#id_path"} -
Can you have multiple admin accounts in Django each limited to specific models?
Suppose I have the following models in my django project modelA modelB modelC Now I created a superuser and the admin account (who is the super user) has access to the above three models. My question is if there is any way for me to create another admin account and limit the model of that admin to modelC ? -
RedirectView.as_view django and ulr.py
I'm trying to redirect from urls.py using RedirectView.as_view, but it doesn't work (I mean it doesn't redirect, I stay in the same page). I think the regular expressions used is right. Here is my code: from django.conf.urls import url from . import views from django.views.generic import RedirectView urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^login/(\w*)', views.login, name='login'), url(r'^logout/', views.logout, name='logout'), url(r'^index/', views.index, name='index'), url(r'^login/tw.+', RedirectView.as_view(permanent=False, url='index/')) ] I'm trying to redirect from a URL like this one: http://127.0.0.1:8000/app/login/tw?oauth_token=THETOKEN&oauth_verifier=OAUTHVERIFIER -
Django CORS issues
I'm currently developing something and running into Django CORS issues. I've followed this to try solving this issue but I don't seem to be having any luck when I want to include a whitelist in. I continuously get a "No 'Access-Control-Allow-Origin' header is present on the requested resource." when I try to do a GET request onto the database. Specifically, I'm developing an angular web app that's hosted on a different domain (AWS S3) while the Django db is on AWS EC2. The whitelisting works locally when I whitelist localhost:3000, for example, but doesn't seem to work when I whitelist the s3 domain. It does work if I set the Django to allow all but I don't want to do that for security purposes. I'm currently trying to add in some regular expressions to the domain to allow the different routes available on the website, but that still doesn't explain why localhost:3000 worked when it's more of localhost:3000/#/page/page2. My javascript code is as follows: $http({ url: "api/url", method: 'GET', withCredentials: true, headers: { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'accesstoken' } }).then((response) => { $scope.response = response; }, (data) => { $scope.response = data; }) Let me know if you need …