Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django mai sending error
In my Django website I have a contact form.If the contact form is submitted there need to be send an email to user and admin.When DEBUG is True the email was send. But when DEBUG is False it won'send mail. Here I using DJango mail. -
Difference between tests and interactive shell: files deleted only in the shell
Django 1.11.7 django_cleanup 1.0.1 Django-cleanup deleteы old files on model instance deletion etc. Model: class FileModel(models.Model): file = models.FileField() Currently in MEDIA_ROOT there is a file cache.txt. Just a file. We'll use it in tests. Let's create an instance in the shell: from django.core.files import File file = File(open('/home/michael/PycharmProjects/experiment/media/cache.txt', 'r')) fm = FileModel.objects.create(file=file) In MEDIA_ROOT cache_JO2jFJC.txt appears. Delete it in the shell: fm.delete() (1, {'files.FileModel': 1}) In MEDIA_ROOT cache_JO2jFJC.txt has been deleted. Now there is only cache.txt in MEDIA_ROOT directory. Thefore, django-cleanup works correctly. Let's do the same in a test. And there is a breakpoint put there (have a look at the comment below). class FileTest(TestCase): def test_create_delete(self): file = File(open('/home/michael/PycharmProjects/experiment/media/cache.txt', 'r')) fm = FileModel.objects.create(file=file) fm.delete() # Breakpoint pass At the breakpoint we stop and look around. Aha, the file cache_D9IuGrI.txt appeared in MEDIA_ROOT. Resume. Well, the file is here. It is not deleted. Here is a link to the app: https://github.com/un1t/django-cleanup Direct link to handlers: https://github.com/un1t/django-clean...up/handlers.py Well, handlers listen to signals. Seems logical. How can it be that files are deleted in interactive shell but not in tests? -
Django-mptt admin get child categories
I have next models in my Django project: class Category(MPTTModel): title_of_category = models.CharField(max_length=50, unique=True, verbose_name='Subcategory', default='') parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, default='', verbose_name='Category') class Product(models.Model): category = models.ForeignKey(Category, verbose_name='Category', default='') title = models.CharField(max_length=200, verbose_name='Title of product', default='') Also admin: class CategoryAdmin(DjangoMpttAdmin): list_display = ('title_of_category',) list_filter = ('title_of_category',) admin.site.register(Category, CategoryAdmin) @admin.register(Product) class ProductsAdmin(admin.ModelAdmin): list_display = ('title', ) I would like to show in my admin panel only child category(category without children) in ForeignKey. How can I filter category in admin? -
ManytoMany field in Django admin not appearing
I have a Product model, an Image Model and a Category Model. A Product can have multiple Images(Foreign Key) and a Product can be in multiple Categories a Category can contain multiple Products. A Category can have multiple subcategories(key to itself). class Category(MetaData): parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category', on_delete=models.CASCADE) class ProductMetaData): categories = models.ManyToManyField(Category) class ProductImage(models.Model): product = models.ForeignKey(Product, related_name='image', on_delete=models.CASCADE) In Product Django Admin: class ProductDocumentInline(admin.TabularInline): model = ProductDocument class ProductAdmin(MetaData): inlines = [ProductImageInline] fieldsets = ( ('Product Data', { 'fields': ('name', 'short_description', 'description') }), ('SEO', { 'classes': ('collapse',), 'fields': ('meta_title', 'meta_description', 'slug', 'canonical') }), ('MetaData', { 'classes': ('collapse',), 'fields': (('created_at', 'created_by'), ('updated_at', 'updated_by')) }), ) readonly_fields = ('created_at', 'updated_at', 'created_by', 'updated_by') list_display = ('name', 'updated_at') ordering = ('-updated_at',) search_fields = ('name',) admin.site.register(Product, ProductAdmin) admin.site.register(ProductImage) Issues: If I don't customize fieldsets (grouped, ordered) the Categories appear like default in the middle of the form. If there are customized as in my example they don't appear. If they don't appear Products without Categories can be created and I don't want that. I want a product to have at least one category. Now the inline Images appear below all Product fields. I want the Categories to appear first, then … -
Two ModelMultipleChoiceField in one form
When I'm putting two ModelMultipleChoiceField in one form, i have this view: View here As you see, first field is nice, but second is ugly. There are same code (just different data, but even when I duplicate same first field, there are also ugly view of second field). What can be wrong? Code: self.fields['members'] = make_field('Members', members, User.objects.order_by('username')) self.fields['buckets'] = make_field('Buckets', buckets, Buckets.objects.order_by('name'), False) def make_field(label, initial, choices, multi=True): if multi: field = forms.models.ModelMultipleChoiceField(choices, required=False) field.initial_objs = initial field.initial = [ obj.pk for obj in initial ] field.label = label else: field = forms.models.ModelMultipleChoiceField(choices, required=False) field.initial_objs = initial field.initial = [ obj for obj in initial[0].all() ] field.label = label -
How to set session not to expire on browser close in django?
How to set session not to expire on browser close in django? I creates cookie with expiry days 1. In setting.py-> SESSION_EXPIRE_AT_BROWSER_CLOSE = False and SESSION_COOKIE_AGE = 1440 * 60 . When i logged in cookies are created . but the attribute Expires for cookie is ->When the browsing session ends. and sessionid cookies expires on (1 day time)24hours. when i close tab and reopen it , it keeps session continuous. but when i close browser and reopen it the cookies are also deleted even sessionid also.and i comes to login page again. but i wants keep session continuous even after reopening browser. -
How to return actions and parameters in OPTIONS request with django rest framework
I try to return a list of select options for countries using django-countries and django rest framework. I use JWT_AUTH for the authentication. When I try a options request: curl -H "Authentication: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFsYmVydG9fdmVudGEiLCJ1c2VyX2lkIjoyLCJlbWFpbCI6IiIsImV4cCI6MTUwODE2Mzg4Mn0.svxqTThCahSl1Vu27sMjuJyd1PRLk28-Xgn2OKKb5-g" -X OPTIONS -v http://127.0.0.1:8000/api/v1/core/perfilViajeroUserPass/ The response is: {"name":"Perfil Viajero User Pass Create","description":"","renders":["application/json","text/html"],"parses":["application/json","application/x-www-form-urlencoded","multipart/form-data"]} But I think that it should be something like this by default: { "name": "To Do List", "description": "List existing 'To Do' items, or create a new item.", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "note": { "type": "string", "required": false, "read_only": false, "label": "title", "max_length": 100 } } } } Someone could help me? thanks. -
Apache LoadModule issue
my Apache24 cannot load the module Mod_wsgi on Windows , i tried to add the configuration using: mod_wsgi-express module-config and I added the results to the config file: LoadModule wsgi_module "C:/Python27/lib/site-packages/mod_wsgi-4.5.20-py2.7-win-amd64.egg/mod_wsgi/server/mod_wsgiNone" WSGIPythonHome "C:/Python27" but i could not start the Apache Service after that . I have Apache2.4 Python 2.7.14 and on python the following packages: mod-wsgi==4.5.20 Django==1.11.6 setuptools 5.7 -
How to integrate Khalti Payment Gateway in Django/Python?
I am developing a website in Django 1.11. I need to integrate Khalti Payment Gateway. I have followed the [1]: http://docs.khalti.com/. But I'm unable to perform the server side integration with verification api. A step by step procedure would be great. Please Help ! ! ! -
A for loop in forms.py fails to load data immediately after it's sent | Python Django
In the forms.py I have a short piece of code which loads the data, but only after I edit print("hello") in it. The code as follows: models.py: class CreateAssignment(models.Model): user = models.ForeignKey(User, editable=False, blank=True, null=True) progress = models.CharField(max_length=254, editable=False, blank=True, null=True) class SetAssignment(models.Model): mechanic = models.ForeignKey(User, editable=False, blank=True, null=True) assignment = models.IntegerField(blank=True, null=True) The mechanic is a permission, plus this mechanic's ID will show in the url of the website, when you will try to set an assignment for this mechanic. forms.py: class SetAssignmentForm(forms.ModelForm): ASSIGNMENT_CHOICES = () for item in CreateAssignment.objects.all(): if item.progress == 'Scheduling': user = User.objects.get(id=item.user_id).username ASSIGNMENT_CHOICES += ( (item.id, user + ' - ' + str(item.id)), ) assignment = forms.ChoiceField(choices=ASSIGNMENT_CHOICES, help_text='This is the assignment that you want to apply to this mechanic.') class Meta: model = SetAssignment fields = ('assignment', ) The user_id in this situation is the user that has been set in the CreateAssignment model. Now the issue is: - The for loop in the SetAssignmentForm works, but it loads data after I put a print in it or when I remove the print from it. Which of course shouldn't really affect the code. Is there something I'm overlooking? I've been programming in Python Django … -
couldn't register the user in my application
I'm unable to create in it.I couldn't find the mistake. -
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'