Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to write automatic test when django-cleanup is used
Django 1.11.6 I use django-cleanup==1.0.1. That is: https://github.com/un1t/django-cleanup/tree/master/django_cleanup/testapp It works: I have tried by hand. My model: class ItemFile(ChecksumMixin, models.Model): file = models.FileField(blank=False, max_length=255, upload_to=get_item_path, verbose_name=_("file")) This django-cleanup automatically deletes old files for FileField. If I delete ItemFile instances by hand through Django admin, files on the disk are really deleted. I try to write tests for how this functionality is working in my project: class ItemTests(TestCase): def test_delete_files_on_models_instance_deletion(self): itemfile = ItemFile.objects.create(file=source_file) itemfile.delete() destination_dir = os.path.join(settings.MEDIA_ROOT,...) file_list = os.listdir(destination_dir) self.assertEqual(len(file_list), 0) The problem: this test does not delete the file. This is the direct link to django-cleanup handlers: https://github.com/un1t/django-cleanup/blob/master/django_cleanup/handlers.py It uses signals: post_delete etc. Could you tell me whether this signal will intercept the fork flow in case of my test? Maybe the point is that signals are just ignored in this case. If I am right, how could I test this functionality? -
importerror: No module named django : Sublime Text & Atom
I want to deploy my Django project in Mac OS X environment.I'm using: sublime text3 python3.6 I did below command in terminal. >>> import django >>> django.VERSION (1, 11, 7, 'final', 0) But, when I did this command on sublime text 3, I was getting below error. import django django.VERSION Traceback (most recent call last): File "/Users/xxxxxxx/xxx.py", line 1, in <module> import django ModuleNotFoundError: No module named 'django' [Finished in 1.2s with exit code 1] [cmd:['/Library/Frameworks/Python.framework/Versions/3.6/bin/python3', '-u','/Users/xxxxxxx/bbb.py']] [dir:/Users/xxxxxxx] [path:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin] I did above command in Atom, but I was getting nearly error, why? please help me. -
Loading html template using django fails
The following is my folder structure geoff settings.py urls.py //using this wsgi.py homepage migrations->folder _init_.py .....others here views.py index.html In my geoff urls //root url from homepage import views as homepage urlpatterns = [ url(r'^$', homepage.home, name = 'homepage') ] NOw the homepage views.py def home(request): template = loader.get_template('index.html') context = RequestContext(request, { 'latest_poll_list': "new", }) return HttpResponse(template.render(context)) The above throws an error TemplateDoesNotExist at homepage.html -
sending json data frome nodejs to django by redis
We are scaling our startup, we have a djangorest api that continously recieves json data from nodejs backend on every request from client. How do i implement this effectively. note:on every request my nodejs backend gets jsondata that should be updated in django api, and if your answer is redis why it is better than serverside api calls can anyone help? -
with proper path also django-admin command is not recognized
I have kept anaconda(python) in django folder and have added path using setx command. Even when I am running which python and which conda commands in cmd prompt,those are running fine. But "django-admin proj website" command is not recognized snapshot of path variable- C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\RSA SecurID Token Common;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\ESCRIBA\composer\bin\;C:\Program Files (x86)\Sennheiser\SoftphoneSDK\;C:\Program Files\Intel\WiFi\bin\;C:\Windows\System32;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\WebEx\Productivity Tools;C:\android-sdk\tools\;C:\android-sdk\platform-tools\;D:\Appium\node_modules\appium\bin\;C:\Program Files (x86)\SafeCom\SafeComPrintClient;C:\Program Files\Git\cmd;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Java\jdk1.8.0_144\bin;C:\extra softwares\apache-ant-1.10.1\bin;C:\Users\robhanda\django;C:\Users\robhanda\django\Library\mingw-w64\bin;C:\Users\robhanda\django\Library\usr\bin;C:\Users\robhanda\django\Library\bin;C:\Users\robhanda\django\Scripts;C:\Users\robhanda\django\Scripts;C:\Users\robhanda\django -
Django-registration redirect after login ( {{next}} )
I'm using django-registration to user login in on my website. I need to redirect user to my custom page. As far as I understand all views and forms are built in, so I can't custom them.I need to change "next" variable to redirect me to another page. I've tried: <input type="hidden" name="next" value="{% url 'orders' %}"> This code redirects me to this page, using url's name, but django recognized user as not authenticated(not logged in) Any examples, and advices will be usefull. Thx. -
How `TemplateView` populate context with kwargs?
Django documentation specifies 'TemplateView' in BaseView It says: TemplateView Renders a given template, with the context containing parameters captured in the URL. and Context is pulated (through ContextMixin) with the keyword arguments captured from the URL pattern that served the view. "TemplateView" captures request in URL,this is what I can interpret. Nevertheless,parameters are usually grabbed from database to bond context? How can 'TemplateView' fetch them form a captured URL? -
How to test content of a Django email?
I'm new to Django and am trying to use unittest to check if there's some text in an outbound email: class test_send_daily_email(TestCase): def test_success(self): self.assertIn(mail.outbox[0].body, "\nMy email's contents\n") However, I'm having an issue with mail.outbox[0].body. It will output My email&#39s contents and won't match the test text. I've attempted a few different fixes with no luck: str(mail.outbox[0].body).rstrip() - returns an idential string str(mail.outbox[0].body).decode('utf-8') - no attribute decode Apologies, I know this must be a trivial task. In Rails I would use something like Nokogiri to parse the text. What's the right way to parse this in Django? I wasn't able to find instructions on this in the documentation. -
mocking - django rest fbv request and the response inside it
I have 3 players. 1. client : Any mobile devices 2. poink: Django server 3. platform: Another server The mechanic is 1. client POST to poinkt 2. poink GET to platform 3. platform response back to poink 4. poink responses back to client views.py https://gist.github.com/elcolie/111fde80317e96523a34bb297e5ccf25 tests.py https://gist.github.com/elcolie/565b458716dbf5358d2ad7ba1ff2ee6b output.txt https://gist.github.com/elcolie/9a93d5fc5237b403b4d1d2c8ee3c352e Goal: I want to run integration test on this endpoint, but I do not want to shoot the real endpoint Reads: python mock Requests and the response Python mock, django and requests mocking functions using python mock http://engineroom.trackmaven.com/blog/real-life-mocking/ Problem: It is not mock my object. It raises the error you can see from output.txt -
how to pass value to the url in django while event occurs
i'm trying to send value to the url, whenever event occurs it show error that the Forbidden (CSRF token missing or incorrect.): /mapreq [03/Nov/2017 11:08:27] "POST /mapreq HTTP/1.1" 403 2502 this is script <script> $(document).ready(function () { $('path').mouseup(function () { document.getElementById('state').innerHTML = $(this).attr('aria-label'); var state_lbl = document.getElementById('state').innerHTML = $(this).attr('aria-label'); loadstate(state_lbl); }) }); function loadstate(state_lal) { $.ajax({ type: "POST", url: "mapreq", data: {'state': state_lal} }); } </script> -
Python django cannot import name views
Ive setup django and am setting up my urls like from django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^home/$', views.homepage), ] The above always produces an error cannot import name views PROJECT STRUCTURE geoff settings.py urls.py //using this wsgi.py homepage migrations->folder _init_.py .....others here views.py -
GCS with GKE, 403 Insufficient permission for writing into GCS bucket
Currently I'm trying to write files into Google Cloud Storage bucket. For this, I have used django-storages package. I have deployed my code and I get into the running container through kubernetes kubectl utility to check the working of GCS bucket. $ kubectl exec -it foo-pod -c foo-container --namespace=testing python manage.py shell I can able to read the bucket but if I try to write into the bucket, it shows the below traceback. >>> from django.core.files.storage import default_storage >>> f = default_storage.open('storage_test', 'w') >>> f.write('hi') 2 >>> f.close() Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/google/cloud/storage/blob.py", line 946, in upload_from_file client, file_obj, content_type, size, num_retries) File "/usr/local/lib/python3.6/site-packages/google/cloud/storage/blob.py", line 867, in _do_upload client, stream, content_type, size, num_retries) File "/usr/local/lib/python3.6/site-packages/google/cloud/storage/blob.py", line 700, in _do_multipart_upload transport, data, object_metadata, content_type) File "/usr/local/lib/python3.6/site-packages/google/resumable_media/requests/upload.py", line 98, in transmit self._process_response(result) File "/usr/local/lib/python3.6/site-packages/google/resumable_media/_upload.py", line 110, in _process_response response, (http_client.OK,), self._get_status_code) File "/usr/local/lib/python3.6/site-packages/google/resumable_media/_helpers.py", line 93, in require_status_code status_code, u'Expected one of', *status_codes) google.resumable_media.common.InvalidResponse: ('Request failed with status code', 403, 'Expected one of', <HTTPStatus.OK: 200>) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/storages/backends/gcloud.py", line 75, in close self.blob.upload_from_file(self.file, content_type=self.mime_type) File "/usr/local/lib/python3.6/site-packages/google/cloud/storage/blob.py", line 949, in upload_from_file _raise_from_invalid_response(exc) File … -
Apply conditions in Ajax success Method on received data from Django's view
I'm working on a Django project in which I need to handle a form via ajax.I'm sending ajax request to Django view and getting back the response in JSON format, now I need to apply if-else conditions on that data but these conditions are not working, always run the first condition in any case. Here's my code: Django's view: auth = getauth() service = discovery.build('cloudbilling', 'v1', http=auth, cache_discovery=False) name = 'projects/' + projectName billing_request = service.projects().getBillingInfo(name=name,) billing_response = billing_request.execute() data = billing_response print(json.dumps(data)) if 'billingAccountName' in data: b_response = data b_response['msg'] = True return HttpResponse(json.dumps(b_response), content_type='application/json') else: b = {} b['msg'] = False return HttpResponse(json.dumps(b), content_type='application/json') Here's my ajax code: $(document).on('submit', '#projectForm', function (e) { var message; e.preventDefault(); $.ajax({ url: '{% url 'users:selectProject' %}', type: 'POST', data:{ project_id:$('#project').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, dataType: 'json', success:function (data) { message = data.msg; console.log(message); if(data.msg = 'false'){ console.log('Message is False'); $('#message').addClass('show'); }else if(data.msg = 'true') { console.log('Message is True'); $('#message2').addClass('show'); $('#enableApi').prop('disabled', false); $('#project_btn').prop('disabled', true); } } }); }) It always display 'Message is False' even if console.log('message') display true. what am I doing wrong? Help me, please! Thanks in Advance! -
Grab the instance of an class_based_view
Django documentation specify as_view method in class-based-views as_view() class method creates an instance of the class and calls its dispatch() method. I attept to print the instance. For illustration: # urls.py from django.conf.urls import url from myapp.views import MyView urlpatterns = [ url(r'^about/$', MyView.as_view()), ] #views.py from django.http import HttpResponse from django.views import View class MyView(View): def get(self, request): # <view logic> return HttpResponse('result') I add print statement to views.py class MyView(View): print(self) def get(self, request): # <view logic> return HttpResponse('result') It reports NameError How to fetch the instance created by class 'View' -
New Relic on AWS lambda not reading its config file
I'm using zappa to deploy a python/django wsgi app to AWS API Gateway and Lambda. I have all of these in my environment: NEW_RELIC_CONFIG_FILE: /var/task/newrelic.ini NEW_RELIC_LICENSE_KEY: redacted NEW_RELIC_ENVIRONMENT: dev-zappa NEW_RELIC_STARTUP_DEBUG: "on" NEW_RELIC_ENABLED: "on" I'm doing "manual agent start" in my wsgi.py as documented: import newrelic.agent # Will collect NEW_RELIC_CONFIG_FILE and NEW_RELIC_ENVIRONMENT from the environment # Dear god why??!?! # NB: Looks like this IS what makes it go newrelic.agent.global_settings().enabled = True newrelic.agent.initialize('/var/task/newrelic.ini', 'dev-zappa', log_file='stderr', log_level=logging.DEBBUG) I'm not using @newrelic.agent.wsgi_application since django should be auto-magically detected I've added a middleware to shutdown the agent before the lambda gets frozen, but the logging suggests that only the first request is being sent to New Relic. Without the shutdown, I get no logging from the New Relic agent, and there are no events in APM. class NewRelicShutdownMiddleware(MiddlewareMixin): """Simple middleware that shutsdown the NR agent at the end of a request""" def process_request(self, request): pass # really wait for the agent to register with collector # Enabling this causes more log messages about starting data samplers, but only on the first request # newrelic.agent.register_application(timeout=10) def process_response(self, request, response): newrelic.agent.shutdown_agent(timeout=2.5) return response def process_exception(self, request, exception): pass newrelic.agent.shutdown_agent(timeout=2.5) In my newrelic.ini I have the following, … -
Django with apache wsgi
I am facing a weired scenerio. I have some initialize api in which i create some data and assign that to some variable and keep persist through all request. So that every request use that data and return some result. In simple django app it's working fine but when i configure it to wsgi apache then the value not persist in-memory for that variable for the subsequent requests. Please help for that that. Thanks -
Rendering templates with Django REST Framework
Right now I'm helping a friend out with his site that's built with Django REST Framework. I'm not really familiar with it so when I opened the module that contained the views I was confused as to where I need to load the template for the view: class ProfileView(APIView): permission_classes = [IsAuthenticated] def get(self, request): serialized = UserProfileSer(instance=request.user) return Response(serialized.data) def post(self, request): serialized = UserProfileSer(instance=request.user, data=request.data, partial=True) if serialized.is_valid(): serialized.save() return Response(serialized.data) return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) I'm used to doing return render(request, 'some_template.html', context) I know what serializing does basically but I don't know how to use it to load a template or if I'm supposed to. Sorry -
ImportError: Import by filename is not supported. in urls
When I runserver, I get error, and the traceback is bellow: Unhandled exception in thread started by <function wrapper at 0x106a75050> Traceback (most recent call last): File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) ...... File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/luowensheng/Desktop/demo_project/Python/website/website/urls.py", line 26, in <module> url(r'^api/companies/', include("companies/api/urls")), File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/conf/urls/__init__.py", line 50, in include urlconf_module = import_module(urlconf_module) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: Import by filename is not supported. And my settings.py's urlpatterns: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^test/', music_view.test), url(r'^musics/(?P<album_id>\d+)/', music_view.DetailView.as_view(), name="detail"), url(r'^musics/', music_view.IndexView.as_view()), url(r'^api/companies/', include("companies/api/urls")), ] My companies app's api urls.py: from django.conf.urls import url from django.conf.urls import include from .views import ( StockListView, ) urlpatterns = [ url(r'^stocks/', StockListView.as_view(), name='stock_list'), ] The project directories: -
Pivot query set by variable in Django
I get a result set of objects in a given relationship. I would like to regroup them by another parameter. Is there an easy way to do this? I fe Structure: class Domain(models.Model): name = models.CharField(max_length=250) class MetaObject(models.Model): name = models.CharField(max_length=250) object_type = models.ForeignKey('Type') domain = models.ForeignKey('Domain', models.DO_NOTHING, blank=True, null=True) class Type(models.Model): name = models.CharField(max_length=250) Pseudocode sample: for dom in Domain.objects.all(): for mo in dom.metaobject_set.all(): print mo + ' ' + mo.object_type What I would like is to pivot my data so instead of getting Domain 1 object 1, type 1 object 2, type 1 object 3, type 2 I instead would like a result set I can work with in a template that looks like the following Domain 1 Type 1 object 1 object 2 Type 2 object 3 I feel like what I otherwise need to do is get all the distinct types for a set of objects in a specified domain and then iterate through those. I can't start with Types at the top as I want them to be per domain. -
How to understand 'context' in Django?
Django documentation define 'context' as: Context:A dict to be used as the template’s context for rendering. MB defines it as: the parts of a discourse that surround a word or passage and can throw light on its meaning They contradict to each other. Take an instance to explain my question : In views.py context = {key:value} render(request, template_name, context) in template <p> The parts of a discourse that surround a word {{ key }} and can throw lights on its meaning.<\p> Literallly, the 'context' is the parts outside the curly bracket not the parts inside to be filled in. Now, django's context is the part within bracket. How to perceive the definition of context in Django? -
How to protect Django's views functions from directly calling through browser url
I want to protect my functions from directly calling through browser url. May be it is possible through CSRF. But I am not able to do it. In front end side I am using ajax to call this function. So, the call should only be possible through ajax but not directly from browser url. My javascript code is function getData(table,id){ data = [] $.ajax({ type: "POST", url: "getData", dataType:'json', data:{'tableName':table}, success: function(result) { for(var i=0;i<result.length;i++){ for (var key in result[i]){ val = result[i][key] if (data.indexOf(val)==-1){ data.push(val) } } } $( "#"+id ).autocomplete({ source: data }); } }); } so I am calling this function in javascript. In urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^getData', views.getData, name='getData'), ] In Views.py def getData(request): tableName = request.POST.get('tableName') tableName = 'colleges' cursor = connection.cursor() query = "select * from "+tableName cursor.execute(query) columnDesc = cursor.description result=[dict(zip([col[0] for col in columnDesc], row)) for row in cursor.fetchall()] return HttpResponse(json.dumps(result), content_type="application/json") So, when i am calling through web browser url directly like... http://localhost/shikshapp/getData I am getting response from my views and i am able to see the data.. So, how can i protect this kind of call.. when the token is not … -
Django : How to pre-populate one model when other model data is saved to it?
I have 3 model which is known as supplier, supplierBankAccount and supplier address both are connected by foreign key is there any way to enter the data into these 3 at the same time or how to pre populate the oter two models while entering data into supplier model supplier model class Supplier(models.Model): name = models.CharField(max_length=500, blank=False) merchant = models.CharField(max_length=300, blank=True, null=False) phone = models.CharField(max_length=25, blank=False, null=False) alternate_phone = models.CharField(max_length=25, blank=True, null=True, default='') website = models.URLField(blank=True, null=True, default='') email = models.EmailField(blank=False, max_length=500) tin_number = models.CharField(max_length=100, blank=True, null=True) slug = AutoSlugField(populate_from='name') def __str__(self): return str(self.name) Supplier Address Model class SupplierAddress(models.Model): supplier = models.ForeignKey('Supplier', on_delete=models.CASCADE) street_address_1 = models.CharField(max_length=50, blank=False) street_address_2 = models.CharField(max_length=50, blank=True) city = models.CharField(max_length=50, blank=False) state = models.CharField(max_length=50, blank=False) pin_code = models.IntegerField() country = CountryField() def __str__(self): return str(self.supplier) Supplier Bank Details class SupplierBankAccount(models.Model): supplier = models.ForeignKey('Supplier', on_delete=models.CASCADE,default='') bank_name = models.CharField(max_length=500,blank=False, null=False) branch_address = models.TextField(max_length=2000, blank=False, null=True) account_holder_name = models.CharField(max_length=500,blank=False, null=False) ifsc = models.CharField(max_length=200, blank=False, null=False) account_number = models.CharField(max_length=200, blank=False, null=False) bank_code = models.CharField(max_length=200, blank=False, null=False) branch_code = models.CharField(max_length=200, blank=False, null=False) location = CountryField() additional_info = models.TextField(max_length=1000, blank=True, null=True) def __str__(self): return str(self.supplier) -
I Deleted all migrations and re created database but "Import Error : No module named 'django.db.migrations"
I am currently using Django 1.10.7 and Python 3.5. I think I seriously screwed everything up in my django project. I wanted to wipe my MySQL database, so I created another db but I was reading that I need to delete all migrations in my database(so I deleted the db and created another with a different name) and deleted the migration files in my app. I followed a guide with said to run in terminal: find . -path "*/migrations/*.py" -not -name "__init__.py" -delete find . -path "*/migrations/*.pyc" -delete After this, when I try to run makemigrations, I get error: "ImportError: no module named 'django.db.migrations.exceptions'. I couldn't find anyone else with this problem and honestly am about to literally create an entirely new virtualenv and set up everything again from scratch. -
Django 3 or more levels of Dropdown Menu Filter
**Hi, I am trying to make a webpage where I can register a pre-defined(in Admin area) Product and associate it to Category and Subcategory, using a dropdown menu, that in each iteration filters the subsequent and show only the items associated with the previous. Example: I want to register a Product called "Tablet" associated with Subcategory "Mobile Devices" and this subcategory is associated with Category "Electronic". So, in order to do this, the webpage will show Category to be selected, then after selecting it as electronic, will only show as subcategory "Mobile Devices" and any other under the same category. After selecting the Subcategory, it will filter the next menu Product, to show only Product under subcategory "Mobile Devices" such as Tablet, Cellphone etc. Here is my model.py** class Category(models.Model): company_name = models.CharField(max_length=100) def __str__(self): return self.company_name class Subcategory(models.Model): category = models.ForeignKey(Category) name = models.CharField(max_length=100) def category_name(self): return self.category.company_name def __str__(self): return self.name class Product(models.Model): subcategory = models.ForeignKey(Subcategory) description = models.CharField(max_length=100) def subcategory_name(self): return self.subcategory.name def category(self): return self.subcategory.category.company_name def __str__(self): return self.description **Here is my view.py** def regsubcategory(request): if request.method == 'POST': subcategory_form = RegSubcategoryForm(data=request.POST) if subcategory_form.is_valid(): cdata = subcategory_form.cleaned_data.get ddata = subcategory_form.cleaned_data.get subcategory_selected = Subcategory.objects.filter(name=cdata('subcategory_select')) product_selected = Product.objects.filter(name=ddata('product_select')) … -
The definition of `context` contradicts to its original meaning
I am confused with definition of 'context' in Django for months. In Django documentation: Context:A dict to be used as the template’s context for rendering. Oxford definition: The parts of something written or spoken that immediately precede and follow a word or passage and clarify its meaning. the data from a view's dict is filled to blank of template which contradict to context's original meaning. Take an instance to explain my question : In views.py context = {key:value} render(request, template_name, context) in template <p> The parts of a discourse that surround a word {{ key }} and can throw lights on its meaning.<\p> Literallly, the 'context' is the parts outside the curly bracket not the parts inside to be filled in. Now,in django,context is the part within bracket. Or, that's it, just accept it for granted. How to perceive the definition of context in Django?