Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to custom django admin to remove my actions?
Also the Authentication and Authorization? -
Django Project is failing after nesting apps in an apps folder
Here is what I did: I wrapped my 12 Django apps in an apps folder in my Django project. I added sys.path.append(os.path.join(BASE_DIR,APP_FOLDER_NAME)) in settings.py (before INSTALLED_APPS declaration) sothat I don't need to specify the apps folder when importing my apps. I changed every 12 apps.py files to set name = apps.myappname INSTALLED_APPS are still defined with myappname (not apps.myappname) Here is what I have so far: Code works normally Unit tests, when run app by app, 100% works for the 12 apps. Unit tests, when run as a whole, at some point of execution, fail with errors like this one: ImportError: Failed to import test module: apps.badges.tests Traceback (most recent call last): File "/usr/lib/python3.6/unittest/loader.py", line 428, in _find_test_path module = self._get_module_from_name(name) File "/usr/lib/python3.6/unittest/loader.py", line 369, in _get_module_from_name __import__(name) File "/vagrant/fugo/fugoproj/apps/badges/tests.py", line 10, in <module> from .factories import BadgeFactory File "/vagrant/fugo/fugoproj/apps/badges/factories.py", line 6, in <module> from .models import Badge File "/vagrant/fugo/fugoproj/apps/badges/models.py", line 51, in <module> models.Model): File "/home/ubuntu/fenv/lib/python3.6/site-packages/django/db/models/base.py", line 118, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class apps.badges.models.Badge doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Here is the badges/factories.py file in error (it contains "lazy imports" (to avoid circular imports)): from datetime import timedelta … -
Syntax for django template tag checking object Boolean field
Using Django template tags, I am trying to check if an object Boolean field that I passed to the template (using python) is True. If I print the object on the page I see the value True/False: <p>{{ obj.bool }}</p> I've tried: {% if {{ obj.bool }} == True %} HELLO {% endif %} Which raises a syntax error Could not parse the remainder: '{{' from '{{' And: {% if '{{ obj.bool }}' == 'True' %} <p>HELLO</p> {% endif %} Gives me nothing...? -
Django: Update a few Datatables on input click with requests to same views.py
I have a page with several tables, the contents of which depend on selections from other tables. Example image: The selection on "Table A" would change the results on "Table B", which changes the results on "Tables C and D". For example, to simplify: Table A contains car manufacturers, Ford, Suzuki and Dodge, your selection on Table A would give you a list of cars on Table B, which would contain car models. On Table B you can select many models, say you click on Table A: Ford, then Table B changes to "Mustang, F-150 and Bronco". Then on Table B you can select multiple car models, which would change Table C to show for example, engine sizes. Table C is a list of all engine sizes for all selections on Table B, so it would change to (just an example, I don't know engine sizes off the top of my head): "5 liters, 3 liters, 2.5 liters". Depending on your selections on Tables B and C, then Table D would generate an invoice when you click the button below Table C. I have most of that functionality working, except dynamic updates on tables. On page load, I want tables … -
Django - Calling list or dict item using a variable in template
I'm trying to call a dictionary or list object in a template using a variable in that template with no results. What I'm trying to is identical to this general python code: keylist=[ 'firstkey', 'secondkey', 'thirdkey', ] exampledict={'firstkey':'firstval', 'secondkey':'secondval', 'thirdkey':'thirdval', } for key in keylist: print(exampledict[key]) #Produces: #firstval #secondval #thirdval Things work a little different in the django template. I have a variable defined as key='firstkey' passed onto the template. If i want to call the same dictionary: {{ exampledict.firstkey }} #Produces: firstval {{ exampledict.key }} #Produces: None Django template for loops also has a produced variable forloop.counter0, increasing from 0 in the firstloop to n-1 in the last loop, this cannot call list objects. I have a list: tabletitles=['first table', 'second table', 'third table'] And I want to call and create tables in a loop, putting the table titles for the respective tables above like so: {% for table in tables %} <h3> first table </h3> <table> ... </table> {% endfor %} What I would like to do in this case is {% for table in tables %} <h3> {{ tabletitles.forloop.counter0 }} </h3> <table> ... </table> {% endfor %} Which doesn't work either, since I can't use a separate … -
Django form ignores javascript validation
I'm using a django form for my bookingsystem, inside a boostrap modal. In the form, I have used a onsubmit="return validateTime()" with a javascript-function that validates the time and returns false if its an illegal timeinput. When I test this by giving an illegal time, the alertbox pops up with the errormessage(and then returns false), but the form gets submitted and the modal closes. <form method="post" id="createform" class="js-booking-create-form" onmouseover="checkStartTime()" onsubmit="return validateTime()"> {% csrf_token %} <div class="modal-header"> <h4 class="modal-title" id="dayTitle"></h4> <button title="Close" type="button" id="close" class="btn" style="cursor: pointer" data-dismiss="modal">X</button> </div> <div class="modal-body"> {% include 'booking/includes/partial_booking_form_calendar.html' %} </div> <div class="modal-footer"> <button title="Click to create booking" type="submit" class="btn btn-success" style="cursor: pointer" >Create booking</button> </div> Is it just impossible to validate django forms with javascript functions or are there any small mistakes I'm doing? I didnt post the javascript function as I know it works and validates, but the form ignores it. I'm pretty new to django, so please dont slaughter me. -
In django rest framework, PUT METHOD IS NOT WORKING IN (Dropdown) api/root
Models.py class Product(models.Model): pro_name = models.CharField(max_length=25) class ProductEnquiry(models.Model): productname = models.ForeignKey(Product, on_delete=models.CASCADE) qty = models.CharField(max_length=30) Serializer.py class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ('id','pro_name') class ProductEnquirySerializer(serializers.HyperlinkedModelSerializer): productname = serializers.CharField(source='productname.pro_name') class Meta: model = ProductEnquiry fields = ('id','productname','qty') def create(self, validated_data): productname = validated_data.pop('productname','') validated_data.update({'productname_id': productname['pro_name']}) productenquiry = ProductEnquiry.objects.create(**validated_data) return productenquiry def update(self, instance, validated_data): instance.productname_id = validated_data.get('productname_id', instance.productname_id) instance.qty = validated_data.get('qty', instance.qty) instance.save() return instance Product name is Dropdown from product Model. Here post was working fine but in put method except that dropdown, quantity (qty: input field) updating successfully. -
stoping django dev server gracefully inside docker container
I have Dockerfile with django app setup and docker-compose.yml with service start up instruction: backend: build: . hostname: backend command: ["python", "manage.py", "runserver", "0.0.0.0:8000"] volumes: - .:/app As docker docs recommend I need to use json list CMD format if I want to execute process in current context and being able to stop it gracefully. But after I run docker-compose up backend and after few seconds when server is ready docker-compose stop container stops with code 137. In same setup gunicorn project.wsgi --workers 1 --bind 0.0.0.0:8000 works fine. I also tried to move start up instruction into wrapper script and it didn't work: backend: build: . hostname: backend command: ["./start.sh"] volumes: - .:/app start.sh: exec python manage.py runserver -
Running daphne behind nginx reverse proxy with protocol upgrade always routes to http instead of websocket
I am trying to deploy django channels powered notification application behind Nginx reverse proxy server to only serve the websocket communications, while having Nginx + uWSGI setup to serve the django application. The application works in my local machine seamlessly when run with either python manage.py runserver --noasgi + daphne -p 8000 myproject.asgi:application or python manage.py runserver with daphne handling all the requests internally. Problem: All the websocket requests are routed to http protocol type instead of websocket protocol type and it returns WebSocket connection to 'ws://ip_address/ws/' failed: Error during WebSocket handshake: Unexpected response code: 404 Packages Installed: Django==2.0.3 channels==2.0.2 channels-redis==2.1.1 daphne==2.1.0 asgiref==2.3.0 Twisted==17.9.0 aioredis==1.0.0 autobahn==18.4.1 Environment: Ubuntu - 16.04 Nginx - 1.12.0 Nginx Configuration for upgrading the request: map $http_upgrade $connection_upgrade { default upgrade; '' close; } # the upstream component nginx needs to connect to websocket requests upstream websocket { server unix:/path/to/my/app/daphne.sock; } # configuration of the server server { # the port your site will be served on listen 80; # the domain name it will serve for server_name ip_address; charset utf-8; # Sending all non-media requests for websockets to the Daphne server. location /ws/ { proxy_pass http://websocket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } … -
django filter field as a string
i want to change the filtering field dynamically. i have a model named Product and fields are title and code class Product(models.Model): title = models.CharField(max_length=50) code = models.CharField(max_length=50) my filtering field will be dynamic in views like this def filter(request): search_choices = { '1': 'title__icontains', '2': 'code__icontains', } col_num = request.GET.get("col_num") value = request.GET.get("value") search_field = search_choices.get("col_num") qs = Product.objects.filter(search_field=value) ........ here the variable search_field is always dynamic ... so how can i achieve this -
How to test auto_now_add in django
I have django 1.11 app and I want to write unit test for my solution. I want to test registration date feature. model.py: class User(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) registration_date = models.DateTimeField(auto_now_add=True) def get_registration_date(self): return self.registration_date I'm using also django-boy for models factories: factories.py class UserFactory(factory.DjangoModelFactory): class Meta: model = models.User first_name = 'This is first name' last_name = 'This is last name' registration_date = timezone.now() test.py def test_get_registration_date(self): user = factories.UserFactory.create() self.assertEqual(user.get_registration_date(), timezone.now()) Problem is that I recived AssertionError: AssertionError: datetime.datetime(2018, 4, 17, 9, 39, 36, 707927, tzinfo=<UTC>) != datetime.datetime(2018, 4, 17, 9, 39, 36, 708069, tzinfo=<UTC>) -
passing python variables as an arguments to a perl script
In django project, one of the python function using perl script and I am passing python variables as an arguments but instead of replacing the values of the python variables it is passing variable names how to pass these python variables generically to a perl script. log output is as follows: ('Isource username is %s ', u'sudhb') ('Isource password is %s ', u'123456') (' Command is %s ', ['flexiserver/build/svnenv.sh', '-j', 'svntasktag.pl -u i_uname -a i_passw ss_fvnteste']) Actual code: i_uname = request.POST.get('uname') i_passw = request.POST.get('ispsw') args_str1 = "flexiserver/build/svnenv.sh -j 'svntasktag.pl -u " + i_uname + " -a " + i_passw + " -c \"" + i_desc + "\" ss_fvnteste'" args1 = shlex.split(args_str2) pi = subprocess.Popen(args1, stdout=subprocess.PIPE) stdout = pi.communicate() -
Django return choices with AjaxView
I am using two ChoiceFields in my form. The available choices in the second one depend on the one in the first one. I created an on change event in my template: $("#id_department").change(function(){ console.log($(this).val()) var department = $(this).val(); $.ajax({ type: "POST", url : "{% url "load-choices" %}", data : {"department" : department}, success: function(data){ console.log(data) $("#id_usage").append(data); }, }); }); which points to my view: class LoadChoices(View): def post(self, request, *args, **kwargs): usages = { "new": _("New Device is created"), "room": _("Room is changed"), "owner": _("person currently lending is changed"), "reminder": _("Reminder that device is still owned"), "overdue": _("Reminder that device is overdue"), "trashed": _("Device is trashed") } department = request.POST["department"] used = MailTemplate.objects.values_list('usage', flat=True).filter(department = department) valid = [x for x in usages if not any(y in x for y in used)] return(HttpResponse(valid)) usages are the available choices, used are the choices that I do not want to include in the dropdown and valid are the choices I want to show in the dropdown. Normally, if I was in the edit view, I would just assign validto the field. But as this is the ajax view, as far as I understand it, I have to return valid. But if I … -
Django serving static files locally
It's been a while since I've setup django to work locally. I'm using version 1.11. Getting it to serve the static files. My project is called chatsys and I've created the static folder and css in this folder chatsys\static\css\style.css . Here's the current settings in the settings file. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') and in the urls #for serving static files from django.conf import settings from django.conf.urls.static import static urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and finally in the html {% load static %} ... <link rel="stylesheet" type="text/css" href="/static/css/style.css"> however in the runserver console I get 404 for /static/css/style.css -
Django How to make file to send via email instead of downloading
The users can upload files to the app. But when anyone try to download the files, it will send the file directly to the email address set during the user registration instead of direct download. I have already read the Django documentation to understand the mailing system. Also search in google. But no luck. Can anyone suggest any idea on how to do this or whether there are any django package to implement this etc. -
How to disable read-only project files in PyCharm?
I installed the Apache2 server on Kubuntu and then installed Django (2.0.4) and now all the project files are not available for editing (in PyCharm). I use the 'kate' utility to edit them with sudo. Tell me please how to disable read-only project files in PyCharm. -
how to aggregate after fetching result using groupby using itertools
I am having a list as a=[{'name' xyz,'inv_name':'asd','quant':300,'amt':20000,current:30000},{'name' xyz,'inv_name':'asd','quant':200,'amt':2000,current:3000}] This list i have fetched using itertools groupby. I want to form a list after adding up the quant, amt and current filed for same name and inv_name and create a list something like : [{'name':xyz,'inv_name':'asd','quant':500,'amt':22000,current:33000} Any suggestions on how to achieve this? -
How to implement One to many Relationship in Django RestFramework?
Here i have mentioned my model.py and serilaizers.py i want to use one to many concept here. And my expecting output like this. Expected output { "id": 1, "product_name": "Rice", "description": "expired on 13-04-2018", "sales": "55", "cost": "55", "tax_details": [ {'id': 1, 'tax_name': "http://127.0.0.1:8000/tax/1/", 'percentage': 10}, {'id': 2, 'tax_name': "http://127.0.0.1:8000/tax/3/", 'percentage': 20}, {'id': 3, 'tax_name': "http://127.0.0.1:8000/tax/2/", 'percentage': 05}, ... ], } Models.py TAX model This is main tax table here i will mension Tax name like(IGST,GST,VAT) it was an Dropdown. Product Here it consist of product details and i have mentioned in Expected output TaxProduct In this model the entered taxname and percentage should store separate model. class tax(models.Model) tax_name = models.CharField(max_length=250) percentage=models.CharField(max_length=250) class Taxproduct(models.Model): tax_name = ForeignKey(tax,on_delete=models.CASCADE) percentage = models.CharField(max_length=3) class Product(models.Model): product_name = models.CharField(max_length=25) description = models.CharField(max_length=150) category = models.ForeignKey(Category,on_delete=models.CASCADE) sales = models.CharField(max_length=25) cost = models.CharField(max_length=25) tax_details = models.CharField(max_length=250) Serializer class TaxSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Tax fields = ('id','tax_name','tax_percentage') class TaxproductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Taxproduct fields = ('id','tax_name','percentage') class ProductSerializer(serializers.HyperlinkedModelSerializer): tax_details = TaxproductSerializer(many=True,read_only=True) class Meta: model = Product fields = ('id','pro_name','description','sales','cost','tax_details') so please tell me how to do this? -
csv file is not printing in django webpage
I want upload the csv file,process the data and render it on UI.For that I have created the following code The problem csv file is not uploading If I'm uploaded other file format it not showing any error message.Also help me to print the csv data on UI views.py from django.shortcuts import render from django.conf import settings from django.http import HttpResponseRedirect from django.contrib import messages import csv from django.core.urlresolvers import reverse import logging def upload_csv(request): data = {} if "GET" == request.method: return render(request, "myapp/upload_csv.html", data) # if not GET, then proceed try: csv_file = request.FILES["csv_file"] if not csv_file.name.endswith('.csv'): c=messages.error(request,'File is not CSV type') return HttpResponseRedirect(reverse("myapp:upload_csv",{"c":c})) #if file is too large, return if csv_file.multiple_chunks(): messages.error(request,"Uploaded file is too big (%.2f MB)." % (csv_file.size/(1000*1000),)) return HttpResponseRedirect(reverse("myapp:upload_csv")) file_data = csv_file.read().decode("utf-8") lines = file_data.split("\n") #loop over the lines and save them in db. If error , store as string and then display for line in lines: fields = line.split(",") data_dict = {} data_dict["GSTIN/UIN"] = fields[0] data_dict["start_date_time"] = fields[1] data_dict["end_date_time"] = fields[2] data_dict["notes"] = fields[3] try: form = EventsForm(data_dict) if form.is_valid(): form.save() else: logging.getLogger("error_logger").error(form.errors.as_json()) except Exception as e: logging.getLogger("error_logger").error(repr(e)) pass except Exception as e: logging.getLogger("error_logger").error("Unable to upload file. "+repr(e)) messages.error(request,"Unable to upload file. "+repr(e)) … -
Django : Use multiple CSS file in one html
In Django, it is possible to use different Css files in one HTML document ? I would like to use one css for base.html and another one for page1.html while expanding base.html to page1.html... For example, base.html : {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static "css/base.css" %}"> </head> {% block content %}{% endblock%} </body> </html> and page1.html : {% extends "base.html" %} {% load static %} <link rel="stylesheet" href="{% static "css/page1.css" %}"> {% block content %} code... {% endblock %} I don't want to merge the Css files, do I have an another solution ? -
How to efficiently assign related objects in django
I have two models: class MealOptionCategory(models.Model): name = models.CharField(max_length=255) default = models.ForeignKey('MealOption', on_delete=models.SET_NULL, null=True) class MealOption(models.Model): option_category = models.ForeignKey(MealOptionCategory, related_name='options') I am trying to write a data migration that will assign a default MealOption for each MealOptionCategory that does not have one yet and at the same time something that will be efficient. I only need one MealOption for each category that does not have one assigned yet. This is what I have made to work: def assign_default_meal_option_to_categories(apps, schema_editor): MealOptionCategory = apps.get_model('gloodny', 'MealOptionCategory') MealOption = apps.get_model('gloodny', 'MealOption') for category in MealOptionCategory.objects.prefetch_related('options').filter(default__isnull=True): category.default = category.options.first() category.save() But I thought I could make use of F expressions or better prefetch, but when I try this: meal_option_prefetch = Prefetch('options', MealOption.objects.first()) for category in MealOptionCategory.objects.prefetch_related('options').filter(): # Something I get following error: AttributeError: 'MealOption' object has no attribute '_add_hints' I also can't use Prefetch('options', MealOption.objects.all()[:1]) because I am not allowed to use slicing with filtering. Similarily I can't use F expression to assign first option. Any hint on how to improve this code? -
Django Template Tag `url` not working as expected
So currently, I have the following code: patterns.append(url(r'^sales/crudeoilsale/$', LVCla.as_view(), name='crudeoilsale-list')) With a link that references it as: <a class="nav-model-container" href="{% url 'crudeoilsale-list' %}"></a> Running this code however gives me the error NoReverseMatch at /office/ Reverse for 'crudeoilsale-list' not found. 'crudeoilsale-list' is not a valid view function or pattern name. Checking my url list though, it returns this: ^admin/ office/ ^$ [name='office-index'] office/ ^sales/crudeoilsale/$ [name='crudeoilsale-list'] office/ ^sales/tubosale/$ [name='tubosale-list'] Can someone tell me what I'm doing wrong? -
Dockerfile_Django REST_ERROR _Cannot uninstall 'six'. It is a distutils installed
Docker Django REST API Build stalled with Error Cannot uninstall 'six'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall. Have updated the complete stack trace / log here - https://github.com/digital-cognition-co-in/Django_REST_API_with_OpenCV_on_HEROKU -
How to run daphne under Windows?
I'm trying to run the chat sample for Django Channels. Right now Django Channels does only work under Windows with Python 3.5. I'm at this step. I've tried to set the path: >set PATH=C:\Python35;%PATH% >python Python 3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:17:05) >python daphne python: can't open file 'daphne': [Errno 2] No such file or directory C:\Users\Olivier\Documents\PyCharmProjects\chat>python manage.py daphne Unknown command: 'daphne' Type 'manage.py help' for usage. Then how to run daphne? -
Chart.js with Django - Using REST
Using Django rest frame work i have my query set-up and pulling my data to a url like below. I'm trying to get the data in to chart.js. I can manage to get it to the console or plot the first result, but no further any assistance would be greatly appreciated "comp_history_data": [ [ "(2017, 01, 20)", 256.0 ], [ "(2018, 01, 20)", 456.0 ], [ "(2018, 02, 20)", 568.0 ], [ "(2018, 03, 20)", 683.0 ] ], Here is what i have in my HTML, works fine with dummy data, just not too sure how to plot with the data above <script> var endpoint = '/api/chart/data/' var defaultData = [] var labels = []; $.ajax({ method: "GET", url: endpoint, success: function(data){ labels = data.labels defaultData = data.comp_history_data.forEach(functoin(entry){ console.log(entry) setChart() }, error: function(error_data){ console.log("error") console.log(error_data) } }) function setChart(){ var ctx = document.getElementById("myChart").getContext('2d'); var myChart = new Chart(ctx2, { type: 'line', data: { labels: labels, datasets: [{ label: '# of Computers', data: defaultData, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', ], borderColor: [ 'rgba(255,99,132,1)', ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); } </script> Any thoughts on how i use …