Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
send just a specific filed on ModelSerializer to client - django rest framework
I have a Serializer like below: class KlassStudentSerializer(ModelSerializer): student = ProfileSerializer() klass = KlassSerializer() class Meta: model = KlassStudents fields = ['pk', 'student', 'klass'] I want to send just klass values in a view and send just student in another view. How can I do that? -
In Django REST API, should a POST only APIView define a GET method?
I am fairly new to Django and REST APIs in general. I am exposing a data import URL using Django REST framework i.e. /api/data/import. I currently have an associated APIView that implements a POST method, but returns 405 - Bad Request on a GET as that is the default framework behaviour when GET has not been explicitly implemented. This MDN article strongly suggests GET should always be implemented, so should I just return an empty 200 response? This also smells a little bit like I am using REST incorrectly. Thanks -
Remain logged in ldap between views using Django
I'm using the ldap3 module and trying to create a simple Web App to search for users in an ldap server. The user (help desk people normally, doing the searching) must log in and input the user searched for. The code so far creates/binds to the ldap server, and upon finding the searched user, a different page is displayed showing the user's credentials. So far so good. On the page displaying the credentials, there is a search box, so that that the user can search again for another user. The problem I have now is how to remain logged in via ldap, so that the user only needs to input the searched user (and not again his username and password). I'm thinking I need to parse the conn object in my returns, but somehow this seems a little clumsy. Here is my code: views.py def ldap_authentication(request): if request.POST: username = request.POST['username'] LDAP_MODIFY_PASS = request.POST['password'] searchFilter = request.POST['searchUser'] LDAP_AUTH_SEARCH_DN = '{}\\{}'.format(settings.DOMAIN_NAME, username) conn = ldap_connect(request, un=LDAP_AUTH_SEARCH_DN, pw=LDAP_MODIFY_PASS) attributes_list_keys = ['mail', 'givenName', 'employeeID', 'department', 'telephoneNumber', 'st', 'cn', 'l', 'title'] conn.search( search_base=settings.LDAP_AUTH_SEARCH_BASE, search_filter= '(cn={})'.format(searchFilter), search_scope=SUBTREE, attributes = attributes_list_keys ) entry = conn.entries[0] attributes_split = list(entry._attributes.values()) attr_keys = [] attr_values = [] for i … -
python custom password hasher error
hye . i cannot import my new custom password hasher and i still cannot figure it out why . the error : ImportError at /admin/ No module named 'honeywordHasher.hashers.MyHoneywordHasherdjango'; 'honeywordHasher.hashers' is not a package i already did install honeywordHasher in INSTALLED_APPS and i have the init.py inside the honeywordHasher file. directory : C:. ├───checkout │ ├───migrations │ │ └───__pycache__ │ ├───templates │ └───__pycache__ ├───contact │ ├───migrations │ │ └───__pycache__ │ ├───templates │ └───__pycache__ ├───custom_user │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ ├───honeywordHasher │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ ├───profiles │ ├───migrations │ │ └───__pycache__ │ ├───templates │ │ └───accounts │ └───__pycache__ ├───register │ ├───migrations │ ├───templates │ │ └───accounts │ └───__pycache__ ├───sqlite ├───tryFOUR │ └───__pycache__ └───__pycache__ settings.py : PASSWORD_HASHERS = [ 'honeywordHasher.hashers.MyHoneywordHasher' 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.Argon2PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', ] i already create hashers.py and also the honeyword generation in honeywordgen.py . i still get this error . can someone help me ? -
Dynamic Django model Table x doesn't exist
I'm new to Django and I start to do a project that consist of create a dynamic table based on csv file. The program have to manage columns addition and deletion on the fly. I face an issue which is that the table do not exist and I don't understand why ... I guess it's a basic problem. (1146, "Table x doesn't exist") CSV File is loaded : HTML def gestionTable(request) : if (request.method == 'POST' and request.FILES['file']) : if (handle_uploaded_file(request.FILES['file'], request.POST['table'])) : messages.success(request, 'ok') else : messages.error(request, _("failed")) return HttpResponseRedirect('#') return render(request, 'weather/gestion_table.html') Model is created here : Python def csv_to_model(f, tableName): reader = csv.reader(f, delimiter=";") data_list = list(reader) col_names = data_list[0] first_values = data_list[1] fields = {} for i in range(len(col_names)) : try : fields[col_names[i]] = typeDeduce(type(literal_eval(first_values[i])).__name__) print(typeDeduce(type(literal_eval(first_values[i])).__name__)) except ValueError: fields[col_names[i]] = typeDeduce("str") return create_model(name=str(tableName), fields=fields, app_label="weather", module="weather") def typeDeduce(a): if (a == "int") : return models.IntegerField() if (a == "float") : return models.FloatField() if (a == "str") : return models.CharField() Dynamic model factory : def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None): class Meta: pass if app_label: setattr(Meta, 'app_label', app_label) if options is not None: for key, value in options.iteritems(): setattr(Meta, key, value) attrs = {'__module__': module, 'Meta': … -
Can not add a user to group in django using admin site
I cannot add a user to a group in django, when use admin site. I got the message below: Internal Server Error: /admin/auth/user/3/change/ Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py", line 551, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/sites.py", line 224, in inner return view(request, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py", line 1511, in change_view return self.changeform_view(request, object_id, form_url, extra_context) File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 67, in _wrapper return bound_func(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 63, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py", line 1408, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py", line 1449, in _changeform_view self.save_related(request, form, formsets, not add) File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py", line 1001, in save_related form.save_m2m() File "/usr/local/lib/python3.5/dist-packages/django/forms/models.py", line 446, in _save_m2m f.save_form_data(self.instance, cleaned_data[f.name]) File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related.py", line 1686, in save_form_data getattr(instance, self.attname).set(data) File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 1007, in set self.add(*new_objs) File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 934, in add self._add_items(self.source_field_name, self.target_field_name, … -
Push django app to IBM Bluemix
I am currently trying to push my local Django App to IBM Bluemix servers. I am using Cloud-foundry to do it and the cf command. Here is the error i get when i'm using the following command: cf push my-app $ python manage.py collectstatic --noinput test os1913 55 static files copied to '/tmp/app/backoffice2/static'. Exit status 0 Staging complete Uploading droplet, build artifacts cache... Uploading build artifacts cache... Uploading droplet... Uploaded build artifacts cache (155M) Uploaded droplet (223.8M) Uploading complete Destroying container Successfully destroyed container 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 crashed FAILED Error restarting application: Start unsuccessful I tried to use the … -
Can't override product status in Django Mezzanine admin
Hi I've been trying to override Django Mezzanine's product status field (Draft/ Published) and add a new option (Draft/Published/Research) in admin but no luck. I'm a total newbie at Django trying to start a new project on Django instead of Wordpress, so please see with my low knowledge on django's structure. Here's my code: cart/cart/apps/mezzanine/models.py from django.db import models from django.utils.translation import ugettext, ugettext_lazy as _ from mezzanine.core.models import Slugged, MetaData, TimeStamped CONTENT_STATUS_DRAFT = 1 CONTENT_STATUS_PUBLISHED = 2 CONTENT_STATUS_RESEARCH = 3 CONTENT_STATUS_CHOICES = ( (CONTENT_STATUS_DRAFT, _("Draft")), (CONTENT_STATUS_PUBLISHED, _("Published")), (CONTENT_STATUS_RESEARCH, _("Research")), ) class Displayable(Slugged, MetaData, TimeStamped): status = models.IntegerField(_("Status"), choices=CONTENT_STATUS_CHOICES, default=CONTENT_STATUS_RESEARCH, help_text=_("With Draft chosen, will only be shown for admin users " "on the site.")) publish_date = models.DateTimeField(_("Published from"), help_text=_("With Published chosen, won't be shown until this time"), blank=True, null=True, db_index=True) Displayable.default=CONTENT_STATUS_RESEARCH Displayable.choices=CONTENT_STATUS_CHOICES cart/cart/apps/mezzanine/admin.py: from django.contrib import admin from mezzanine.conf import settings from django.forms import ModelForm from django.utils.translation import ugettext_lazy as _ from cart.apps.mezzanine.models import Displayable from mezzanine.core.admin import BaseTranslationModelAdmin class DisplayableAdminForm(ModelForm): def clean_content(form): status = form.cleaned_data.get("status") content = form.cleaned_data.get("content") if status == CONTENT_STATUS_PUBLISHED and not content: raise ValidationError(_("This field is required if status " "is set to published.")) return content class DisplayableAdmin(BaseTranslationModelAdmin): list_display = ("title", "status", "admin_link") list_display_links = ("title",) … -
How can I access a model that is instantiated later for a calculation in Django?
I am fairly new to Python/Django and I have the following problem. I have structured my models as follows: class Foo: name = models.CharField(max_length=10) class Bar: othername = models.CharField(max_length=10) othername2 = models.CharField(max_length=10) fkey = models.ForeignKey(Foo, on_delete:models.CASCADE) class FooBaroo: FooBarooInt = models.IntegerField() Barkey = models.ForeignKey(Bar, on_delete:models.CASCADE) The relations are that 1 Foo has multiple Bars and 1 Bar has multiple FooBaroos. What I want is to create a table with Django wherein I have a complete overview of a Bar class. One of the things I want to display is the sum of all FooBarooInts of a Bar. If I however add a property to Bar that takes all relevant FooBaroo objects (through objects.all().filter()) it ends up not returning anything in most cases, but not all (which I find weird). Does anybody have an idea of how I should solve this? -
405 Error, Method not allowed Django Rest Framework and ATrigger
I am trying to make a webhook that get triggered by ATrigger. I tried it but every time it shows error 405, method not allowed. It works when doing a POST through the server, or through Hurl.it -
TemplateSyntaxError: Could not parse the remainder
I'm receiving this error each time I try to access a list within a Django template. I have checked the answers to similar questions, but the problem is usually a lack of % or some other character somewhere. As long as I can see, this is not the case: Here I'm passing a dict containing a a list of item id as keys and list of URLs to images as a value for each id. I know I should integrate this into the item model, but since I'm still at development with SQLite3 I cannot store lists easily. And anyway I am intrigued by this problem. So: <a href="{% url 'details_view' item_id=item.id %}"><img class="hover-image" src="{{ img_gallery[item.id][0] }}" alt=""> Exception Value: Could not parse the remainder: '['item.id'][0]' from 'img_gallery['item.id'][0]' Also, yesterday I tried using bootstrap4 flex-grid to easily achieve 5 columns. Since I'm using pagination to retrieve 20 items, my idea was slicing the list of items (model) for each row, like: {% for item in items[0:5] %} And I also received the same error, even when this was the recommended aproach in related answers aboput slicing data passed with a view. In both cases I cannot find the problem, and … -
Django Import-Export Import Duplicate key value violates Error
I'm working on a project with Django 1.10, Python 3.6 and PostgreSQL as the database backend, in which I have a model called 'Article" and I need to import data from CSV files. I have imported my first CSV file successfully with the following fields: id, link & category It's ID fields starts from 1 to 1960 then in next file, I have started ID field from 1961 to onward but it shows the following error: Line number: 1961 - duplicate key value violates unique constraint "article_article_pkey" DETAIL: Key (id)=(1961) already exists. Even when i see my Article model in Django admin it shows IDs from 1- 1960 Here's my models.py: class Article(models.Model): id = models.AutoField(primary_key=True) link = models.URLField(max_length=255) category = models.CharField(max_length=255, choices=Categories) Here's admin.py @admin.register(Article) class ArticleAdmin(ImportExportModelAdmin): resource_class = views.ArticleResource readonly_fields = ('id',) -
python -m django startproject didn't work, I want to know why
My system is centOS6.8, django version is 1.8.6, python 3.5.0 (my_env) [root@localhost my_env]# python -m django startproject mysite /usr/local/python3.5.0/bin/python3: No module named django.__main__; 'django' is a package and cannot be directly executed Thank you for my friends, I need to know why? -
How to create big csv files and send notification to user after completion for download in django
I am hitting some APIs to create CSVs file. total time taken by the CSV is 20-30 minutes avg. How to send notification to download link after creation file in django python -
Multithreading/multiprocessing in Django
I am working on a Django project in which i'll create an online judge (User can submit solutions to programming problems and will be autograded at server using python subprocess library where i can call g++) (something similiar to Codeforces website). When user submits a solution i take his solution file and have to asynchronously call the grading function (automatic grading may take time) I didnt use celery for the purpose because i read it has overheads and would have been overkill for mey project. So i built a queue object in Django and called a function to run on queue by creating a thread and it's working fine (i have read threads are evil warning). I wanted to ask should i call python multiprocessing library to optimize the automatic grading on different cores. For example i'll create 4 queues and call grading function on each queue through different Processes. Will it be nice idea or overheads of calling multiprocessing will be larger? Also will it be safe to do (if not good style of programming)? -
Django: Class object has no attribute of standard function
I have a model: class Order(models.Model): STATUS_CHOICES = ( (100, 'First'), (200, 'Second'), ) status = models.IntegerField('Status', choices=STATUS_CHOICES) def accept(self): self.status = 200 self.save() return self.status, self.get_status_display() And I have a Unit-Test for it: class CustomTestCase(TestCase): @classmethod def setUp(self): pass @classmethod def save(self): pass class OrderTest(CustomTestCase): def test_accept(self): result = Order.accept(self) expected = (200, 'Second') self.assertEqual(expected, result) As you can see, i added 'save' function that do nothing, the reason for that is because without that custom 'save' function I keep getting this error: '[OrderTest] object has no attribute [save]'. If there is a better solution to that custom 'save' function please tell me. But this kind of solution will not work with django-built-in 'get_status_display()' function. And without solution I keep getting this trouble: '[OrderTest] object has no attribute [get_status_display]'. What can I do to make this work as I need ? -
Could not parse the remainder: '{{request.LANGUAGE_CODE}}' from '{{request.LANGUAGE_CODE}}'
I programing with django 1.11, now I have following script in post_list.html {% with lang={{request.LANGUAGE_CODE}} %} {% endwith %} <p> {% if lang == 'zh-CN' %} {{object.category.name_zh_CN}} {% else %} {{object.category.name}} {% endif %} </p> but I cannot get lang actually with following error message, please help.Thanks. TemplateSyntaxError at /adv/australia-strategic/ Could not parse the remainder: '{{request.LANGUAGE_CODE}}' from '{{request.LANGUAGE_CODE}}' Request Method: GET Request URL: http://localhost:8030/adv/australia-strategic/ Django Version: 1.11.6 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '{{request.LANGUAGE_CODE}}' from '{{request.LANGUAGE_CODE}}' Exception Location: /Users/wzy/anaconda2/envs/python36/lib/python3.6/site-packages/django/template/base.py in __init__, line 700 Python Executable: /Users/wzy/anaconda2/envs/python36/bin/python Python Version: 3.6.3 Python Path: ['/Users/wzy/expo3/expo', '/Users/wzy/anaconda2/envs/python36/lib/python36.zip', '/Users/wzy/anaconda2/envs/python36/lib/python3.6', '/Users/wzy/anaconda2/envs/python36/lib/python3.6/lib-dynload', '/Users/wzy/anaconda2/envs/python36/lib/python3.6/site-packages', '/Users/wzy/expo3/expo'] -
How to make search form in Django?
How to make function search which filter record from text boxes in forms? The function will execute when button 'search' is clicked and the results will appear in a template table. I need a sample code (form/view/model/template) to adapt it with my forms. Any suggestion? Thank you in advance. -
Django project - 1.4 to 1.8?
I'm taking over somebody else's project that was coded using Django 1.4 and Python 2.6. Pretty old, i know. I want to upgrade it to Django 1.8 and Python 2.7. After installing Python 2.7 and Django 1.8 (using pip), i noticed that the project itself didn't change and it's still "set" to work with Django 1.4 and Python 2.6. What is the process i have to go through to make that kind of upgrade? -
Django with Docker Module NOT found Error
I am Trying to build the Django app with Docker.My application will run on local server however when i try to migrate with docker it throw Module Not Found Error This is my requirements.txt djangorestframework==3.7.0 Django==1.11.5 #import_export==0.5.1 django-csvimport==2.2 psycopg2 This is my docker-compose.yml`. docker-compose.yml version: '3' services: web: build: . command: python djangorest/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" This is my Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ #COPY . /code/ RUN pip install -r requirements.txt ADD . /code/ I am get following error when i pass this cmd docker-compose run web python djangorest/manage.py migrate docker-compose run web python djangorest/manage.py migrate Traceback (most recent call last): File "djangorest/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 120, in create mod = import_module(mod_path) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed … -
How do I replace a string variable
I have a code as follows with open(f1) as f: userid=f.read().replace('0', str(instance.id)) The above works well. Now, the variable userid as a string has character In will like to replace. I tried this code and is given errors shown below. Please note: the variable the_user.phonelist is a python LIST. I will like to replace the character [] with the list. ans = userid.replace('[]', the_user.phonelist) Error: Can't convert 'list' object to str implicitly -
How do you hide a field if other field's condition is not met in django?
So if I have this code in my models.py class Computer(models.Model): brand = models.CharField(max_length=225) how do I show either of the following additional field in my django admin depending on the value of brand above? mac_os = models.CharField(max_length=225) windows_os = models.CharField(max_length=225) linux = models.CharField(max_length=225) e.g. if brand == HP only the field for windows_os or linux will be shown when you try to input your data in the admin and will the hide field for mac_os. thanks so much.. :) -
Limit django for loop in the template or the view for better performance?
I have a for loop on my template. I only want to display the first 3 items in the loop for a blog. At present there are only 20 blog entries, but if the blog entries are say 500 or more, from a performance perspective, is it better to limit the loop in the views.py code or in the template code? Here is the loop limit in the views.py file: blog_latest_entries = BlogDetails.objects.filter(blog_date_published__lte=date_now).order_by('-blog_date_published')[:3] ..... return render(request, 'page.html', { 'blog': blog_details_latest_entries, Here is the limit in the template code: {% for blog in blog|slice:"3" %} Which option is best for performance. I suspect the views.py approach, but I would like my suspicion backed up by someone with real knowledge. Thanks. -
Django: how to retain context object passed to the render function for another render
I pass a context dictionary called dict_context in my render function and it renders using the data just fine. return render(request, 'myapp/track.html', dict_context) Now, in the rendered page, I have a button that will POST and I want to use the context dictionary again, but I receive this error: UnboundLocalError at /track_containers_import_data local variable 'dict_context' referenced before assignment How can I reuse dict_context in the next render? I thought contexts are saved automatically in the sessions. -
Using python async / await with django restframework
I am just upgrading an older project to Python 3.6, and found out that there are these cool new async / await keywords. My project contains a web crawler, that is not very performant at the moment, and takes about 7 mins to complete. Now, since I have django restframework in place already to access data of my django application, I thought it would be nice to have a REST endpoint where I could start the crawler from remote with a simple POST request. However, I don't want the client to synchronously wait for the crawler to complete. I just want to straight away send him the message that the crawler has been started and start the crawler in the background. from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from django.conf import settings from mycrawler import tasks async def update_all_async(deep_crawl=True, season=settings.CURRENT_SEASON, log_to_db=True): await tasks.update_all(deep_crawl, season, log_to_db) @api_view(['POST', 'GET']) def start(request): """ Start crawling. """ if request.method == 'POST': print("Crawler: start {}".format(request)) deep = request.data.get('deep', False) season = request.data.get('season', settings.CURRENT_SEASON) # this should be called async update_all_async(season=season, deep_crawl=deep) return Response({"Success": {"crawl finished"}}, status=status.HTTP_200_OK) else: return Response ({"description": "Start the crawler by calling this enpoint via post.", "allowed_parameters": …