Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: Module use of python34.dll conflicts with this version of Python
I have downloaded and installed Anaconda3-4.4.0 with Python 3.6. I already have Python 3.4 as the working version.Now after installing, when I try to launch Anaconda prompt I am getting the below error: No Module named 'conda' I have also added the path in the environment variables. Can anyone provide any suggestion on how to proceed further and solve this issue ? Thanks! -
Migrations applied but no migration folder
I have developed a Django 1.8 project a while ago. I deployed the project a few months back and everything was running perfectly. Today, I had to make a change in the database, but when I tried to run python manage.py makemigrations, I got the message "No changes detected". I then noticed that there was no migration folder in any of the apps of the project. What I don't understand is: I made the migrations (makemigrations then migrate) when I first deployed the project, and everything was ok. I didn't check that the migration folders were there though. I didn't made any change to the database since this first migration and didn't remove any folder. When I run python manage.py showmigrations, I get the following: admin [X] 0001_initial auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial This is the full output. No sign of any of my apps. So my questions are the following: How is it possible that the migrations were made, the tables were created, etc. but no migration folder was created ? Where do I go from here ? I want to make the … -
Django delete cache with specific key_prefix
I'm using Django's per-view @cache_page decorator and have set a different key_prefix for each view. I've previously deleted the cache with: from django.core.cache import cache cache.clear() But what if I just want to delete the keys containing a specific key_prefix? I can obviously do it by just connecting to the database and delete with raw sql but I wonder if it can be done with 'pure' Django? I'm using Django 1.11 and Python 3.6 -
nginx location and Django auth
I'm trying to create a NGINX redirect based on an URL param in the querystring. Basically having: http://localhost/redirect/?url=https://www.google.it/search?dcr=0&source=hp&q=django&oq=django and location /redirect/ { proxy_cache STATIC; # cache status code 200 responses for 10 minutes proxy_cache_valid 200 1d; proxy_cache_revalidate on; proxy_cache_min_uses 3; # use the cache if there's a error on app server or it's updating from another request proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504; # don't let two requests try to populate the cache at the same time proxy_cache_lock on; # Strip out query param "timestamp" if ($args ~ (.*)&timestamp=[^&]*(.*)) { set $args $1$2; } return 302 $arg_url$args; } It works and keeps the qs keys/values: dcr=0&source=hp&q=django&oq=django while removing the unwanted keys. I could do it at the Django level (https://github.com/mjumbewu/django-proxy/blob/master/proxy/views.py) but I suppose it's faster and less computationally expensive at the NGINX level. Is this a correct approach to proxy requests through NGINX? Now, only Django authenticated users (JWT/Cookie) can use the /redirect?url= end point, hence is it possible to implement a session/cookie check without opening a proxy to the entire world? Thanks, D -
Why does retrieving a single resource execute serializer.to_representation() multiple times in Django REST framework?
Lets say I have a model called Thingy, and there are 20 Thingies in my database. When I retrieve all Thingies, serializer.to_represenatation() is executed 20 times. This is good. However, when I retrieve just a single Thingy from /api/thingies/1, I observe that serializer.to_representation() is executed four (4!!!) times. Why does this happen, and how can I get away with just one call to to_representation()? -
Get specific attribute data from Json
I'm implemented a code to return Json value like this { "key1":"1", "key2":"2", ......} But I want to get only value of key1. so I first defined info to get Json. info = requests.get(url, headers=headers) And use info.text['key1'] to get value of key1. but i got error. could anyone suggest any solution? -
send email in django through gmail
I am trying to send a mail using django through gmail. Following is my settings.py code: EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'me@mycompany.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_USE_TLS = True view.py I am using method send_mail(): send_mail(subject, contact_message, emailfrom, emailto) When I execute the code & enter details in my contact form & hit submit. I get the below error: smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server. Please suggest! -
How to pass the time to the DateTimeField?
In my models.py I have a GTTime model: class GTTime(models.Model): gt_time = models.DateTimeField(null=True) ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) And in my views.py, how to add the time to in the gt_time? I tried use the time.time() to pass the timestamp, but there will report error: gt = models.GTTime(gt_time=time.time()) gt.save() Error: TypeError: expected string or buffer -
Can't display Query result in DataTable with Django
i recently made changes on my project to call stored procedure with django inside the python. I used to work with pyodbc and it was working fine, i was getting results from my stored procedure and was able to display them on the datatable. View: def index(request): cursor = connections['site'].cursor() try: cursor.execute("{CALL SP_webGET_RESUME_MVT_INIT_ACTIF}") mouvements = cursor.fetchall() finally: cursor.close() return render(request, 'index.html', locals()) Template : {% load static %} <!doctype html> <html> <head> <meta charset="utf-8"> <title>Untitled Page</title> <meta name="generator" content="WYSIWYG Web Builder 12 - http://www.wysiwygwebbuilder.com"> <link href="../static\css/Gestion_Mouvements.css" rel="stylesheet"> <link href="../static\css/index.css" rel="stylesheet"> <link href="{% static 'css/jquery-ui.min.css' %}" media="all" rel="stylesheet"> <link href="{% static 'css/jquery.dataTables.min.css' %}" media="all" rel="stylesheet"> <link href="{% static 'css/bootstrap.min.css" rel="stylesheet' %}" media="all"> <link href="{% static 'css//bootstrap-datetimepicker.min.css' %}" media="all" rel="stylesheet"> <script src="{% static 'js/jquery-1.12.4.min.js' %}"></script> <script src="{% static 'js/jquery.dataTables.min.js' %}"></script> <script src="{% static 'js/jquery-ui.min.js' %}"></script> <script> $(document).ready(function() { $('#indexTab').dataTable( { "bLengthChange": false, "lengthMenu": [ [-1], ["All"] ] } ); $('.editbtn').click(function(){ var $row = $(this).closest("tr"); // Find the row var $text = $row.find(".idMark").text(); // Find the text alert($text); }); $('.deletebtn').click(function(){ var $row = $(this).closest("tr"); // Find the row var $text = $row.find(".idMark").text(); // Find the text alert($text); }); }); </script> </head> <body> <div id="wb_Shape1" style="position:absolute;left:4px;top:5px;width:1300px;height:100px;z-index:0;"> <img src="../static\images/img0003.png" id="Shape1" alt="" style="width:1300px;height:100px;"></div> <div id="Html1" style="position:absolute;left:4px;top:107px;width:1300px;height:400px;z-index:1"> … -
Django Rest Swagger 2: Is there anyway so far to document parameters for POST requests of FUNCTION based views?
I am trying to integrate django-rest-swagger==2.1.1 with my existing project that uses djangorestframework==3.5.3. The project has some Class based views and some Function based views. After integrating swagger, It displays input boxes for POST requests of "Class Based views"(which have serializers obviously), but does not show for "function based views". The question has been asked several times, I have tried following solutions: Solution1 Solution2 and few others too, but did not work for my case. Is there any possible way to do that for 'function based views' or I ll have to convert them to class based views? -
I wanna connected 2 drill down button in large content&small content
I wanna connected 2 drill down button in large content&small content.But now 2 button is independency. My ideal output is like Left button is large content and right one is small content.If I select A in left button and a-1 & a-2 & a-3 is shown in small content.If I select B in left button and b-1 & b-2 is shown in small content.Now I wrote in views.py like from collections import OrderedDict from django.shortcuts import render import json from django.http import JsonResponse def index(request): with open('./data/data.json', 'r') as f: json_data = json.loads(f.read(), object_pairs_hook=OrderedDict) preprocessed = [] counter = 0 for key in ["type1", "type2", "type3", "type4"]: values = [(i + counter, value) for i, value in enumerate(json_data[key].values())] preprocessed.append((key, values)) counter = len(json_data[key]) return render(request, 'index.html', {'json_data': json_data,'preprocessed': preprocessed}) I wrote like index.html like <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option>{{ i }}</option> {% endfor %} </select> {% for key, values in preprocessed %} <select name="type" id=key> {% for counter, value in values %} <option value="{{ counter }}">{{ value }}</option> {% endfor %} </select> {% endfor %} Now 3 button is shown in browser, large content button & A's small content button & B's small … -
prevent SQL injection in django forms
I use this for validation: class MyValidationForm(forms.Form): title = forms.CharField() body = forms.Textarea() taxonomy = forms.IntegerField() and this is my class-based view: class blog_createpost(dashboardBaseViews): template_name = "dashboardtems/blog_createpost.html" model = {} def post(self, request, *args, **kwargs): form = MyValidationForm(request.POST) if not form.is_valid(): return HttpResponse("not valid") new_data = post(title=request.POST['title'], body=request.POST['body'], description=request.POST['description'], taxonomy=get_object_or_404(taxonomy, pk=request.POST['taxonomy']), writer=request.user) new_data.save() return HttpResponse("done") like you see i check my received request validation in this line: if not form.is_valid(): and its working on but when i add some SQL-command inside my form inputs. it does not preventing to insert the value inside database!.. means i have a field in database which contains some value like select * from user where 1=1!. doesn't it cause sql-injection danger from user inputs?... -
How can we view database in django of stored username and password of an default login page
How can we view database in django of stored username and password of an default login page. -
django form request.POST.get('field-name', '') always empty
Trying to get some values from a form but the parameters are always empty. here is the path from my urls.py: url((r'^partners-email$'), views.partners_email, name="Partners Email"), This is a simple form I have in the template: <form method="POST" action="/partners-email"> <input name="email" class="form-control" id="client-email"> <input type="submit" value="Submit" /> </form> and here is my function in views.py: def partners_email(request): from_email = request.POST.get('email', '') print('MY_TAG: ' + from_email) output is always: "MYTAG: " any ideas? Thank you very much in advance -
Django import-export.admin customize:for xlsx sheets, and change the diff strategy
I have a knotty problem. I used django-import-export to import xlsx data. I have integrated it to Django admin by ImportExportModelAdmin. below is admin.py: @admin.register(assets) class data_import(ImportExportModelAdmin): pass But when I import data several times, I found it just save the newest data(the last) to model, I want save all data every time I import, and just use some columns to decide if the data is duplicated.How can I solve this? -
I did not show big drill down button
I did not show large content drill down button. I load json file and the content of the file become drill down button's content.But now only small content drill down buttons are shown.json is like {'items': {'---': '---', ‘A’: ‘a’, ‘B’: ‘b’, ‘C: ‘c’, ‘D’: ‘d’}, 'type1': { "---":"---", "a1":"a1", "a2:"a2", "a3":"a3", "a4":"a4" }, 'type2': { "---":"---", "b1":"b1", "b2:"b2", "b3":"b3", "b4":"b4" }, 'type3': { "---":"---", "c1":"c1", "c2:"c2", }, 'type4': { "---":"---", "d1":"d1", "d2:"d2", "d3":"d3" }, } views.py is from collections import OrderedDict from django.shortcuts import render import json from django.http import JsonResponse def index(request): with open('./data/company_demand.json', 'r') as f: json_data = json.loads(f.read(), object_pairs_hook=OrderedDict) preprocessed = [] counter = 0 for key in ["type1", "type2", "type3", "type4"]: values = [(i + counter, value) for i, value in enumerate(json_data[key].values())] preprocessed.append((key, values)) counter = len(json_data[key]) return render(request, 'index.html', {'json_data': json_data}, {'preprocessed': preprocessed}) index.html is <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option>{{ i }}</option> {% endfor %} </select> {% for key, values in preprocessed %} <select name="type" id="{{ key }}"> {% for counter, value in values %} <option value="{{ counter }}">{{ value }}-{{counter}}</option> {% endfor %} </select> {% endfor %} But now this part <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> … -
ID and Class Name Delimiters in HTML
Django==1.11.5 Googl tells us not to use underscores: https://google.github.io/styleguide/htmlcssguide.html#ID_and_Class_Name_Delimiters Well, it is ok. But let's have a look at how to behave in the reality of Django. Let's open django/contrib/admin/templates/admin/index.html. We can see: <div id="content-main"> As if a hyphen is Ok for Django. But on the other hand if one organizes a Django form then opens its HTML, they will see something like this: id="id_keeper_not_absent" Well, this id was automatically created by this code: forms.py keeper_not_absent = forms.BooleanField(label='Keeper absent', required=False) Well, now we have underscores in HTML element ids. It is also Ok. But mixing doesn't seem Ok. Could you help me understand why Django itself uses such a mix and what should we ourselves use? -
How to set a path to virtual environment for sublime text 3 plugin to work correctly
I am trying to install a plugin called "Django manage commands" in sublime text 3. and after installation, I got the following message Remember to set the path to the directory where your virtual environments are installed in "python_virtualenv_paths" for the plugin to work correctly, as many directories as you need can be added. How can I do this? I found the same message in other plugins as well. Thanks for your time in advance '_' -
How to you join two models with a specific requirement
I have two models Model A class Affiliate(models.Model): instructor = models.OneToOneField(Profile) Model B class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) instructor = models.BooleanField(default=False, blank=False) My goal is in my django admin to show a list of Profiles where instructor = True, right now I am getting all of the instructors, how can I limit this list. class AffiliateAdmin(admin.ModelAdmin): fields = ['instructor'] This works but it gets the whole list of profiles. I only want the profiles that have instructor = True. I have tried limiting the profile on the affiliate model with no success. Any help is appreciated. -
Django issue with argon2 hasher in live production
So I have just setup my Digital Ocean droplet (server) and have been working to get this site to work, however I have been coming across error after error. I finally got the site to load the login page (which is what should happen), but when I login I get an error that Argon2 Pass Hasher couldn't load. I really have no idea what the problem is, as everything was working perfectly while in development. Here is the error: ValueError at /accounts/login/ Couldn't load 'Argon2PasswordHasher' algorithm library: No module named argon2 Here are my settings: """ Django settings for django_project project. Generated by 'django-admin startproject' using Django 1.8.7. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') MEDIA_DIR = os.path.join(BASE_DIR, 'media') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'h&*(yq942_a^pa+ty&wh(bl9s4d#z^*_6cmeb#5&49jb^r$&!f' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', … -
Database Queries: Fast alternatives to Django's order_by()
I've been teaching myself Django and SQL, and one thing I've noticed is that when working with large tables (> 1,000,000 records), specifying an ordering is painfully slow. For example: Model.objects()[offset:limit] might take a few milliseconds, assuming offset and limit are a small enough range. However: Model.objects()[offset:limit].order_by('name') Could take 10 or 20 seconds, depending on the number of rows in the table. I understand why this is happening; all rows must be checked to ensure that the correct results are returned. I also understand that this is more an SQL problem and not a Django problem, it's just easier for me to explain it with Django code. So these are my questions: Since I see Django production websites display ordered data from extremely large tables, how do they achieve this without each query taking >10 seconds? After I solve the first question, how could I extend my Django application to allow ordering of multiple columns (name, date, value, etc)? My intuition says that the answer to the first question is to insert each record in the order I want it displayed so that no ordering is necessary when performing queries, but that seems difficult to maintain. Also, that means that … -
I wanna add number which is correspond to the number of this list's content
Now index.html is <html> <head> <script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.8.2/chosen.jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.js"></script> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.css"> </head> <body> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option>{{ i }}</option> {% endfor %} </select> <select name="type" id="type1"> {% for j in json_data.type1.values %} <option>{{ j }}</option> {% endfor %} </select> <select name="type" id="type2"> {% for k in json_data.type2.values %} <option>{{ k }}</option> {% endfor %} </select> <select name="type" id="type3"> {% for l in json_data.type3.values %} <option>{{ l }}</option> {% endfor %} </select> <select name="type" id="type4"> {% for m in json_data.type4.values %} <option>{{ m }}</option> {% endfor %} </select> <script type="text/javascript"> $(document).ready(function () { $('#mainDD').on('change', function() { console.log($(this).val()); console.log($('#mainDD :selected').text()) ; var thisType = "type" + $(this).val(); for(i=1; i<5; i++) { var thisId = "type" + i; console.log(thisType + " " + thisId); if(thisType !== thisId) { $("#"+thisId).hide(); } else { $("#"+thisId).show(); } } }).trigger('change'); }); </script> </body> </html> I wanna add number to tag like .So my ideal output is <select name="type" id="type1"> <option value="1">a-1</option> <option value="2">a-2</option> <option value="3">a-3</option> <option value="4">a-4</option> </select> <select name="type" id="type2"> <option value="5">b-1</option> <option value="6">b-2</option> <option value="7">b-3</option> <option value="8">b-4</option> <option value="9">b-5</option> </select> <select name="type" id="type3"> <option value="10">c-1</option> <option value="11">c-2</option> </select> <select name="type" id="type4"> <option … -
Duplicate key issue when loading back.json file PostgreSQL
I have a PostgreSQL database that where I performed python manage.py dumpdata to backup the data into a json file. I created a new PostgreSQL database, performed a migrate, and everything worked like clockwork. When I tried to load the backup.json file with python manage.py loaddata backup.json it, gives me this error. Could not load contenttypes.ContentType(pk=15): duplicate key value violates unique constraint "django_content_type_app_label_76bd3d3b_uniq" DETAIL: Key (app_label, model)=(navigation, navigation) already exists. I checked phpPgAdmin, and there is a row for News. Is there a way to load the backup json file without including the content types, or better yet dump everything except for content types data ? -
Convert serialized object to json in Django
I'm coding unit tests for a serializer. I have got a serializer object from the serializer that I'm testing (This is actual serialized content). I have serialized the sample data using from django.core import serializers and got the json (This is the expected content which is in json). Could anyone please let me know how do I convert either (expected/actual) into class object/json, so that I can assert both? Below is the code I'm trying: obj = mixer.blend('register.Register', first_name='first_name') actual_serialized_content = RegisterSerializer(data=Register.objects.filter(first_name='first_name').values()) expected_serialized_content = serializers.serialize('json',Register.objects.filter(first_name='first_name')) I'm all new to Django and unit testing, if the above approach isn't right, please suggest. -
Global View-Context in Django App
Currently I've a class which I call in every single view for some global context variables which I use in my templates. It looks like this: class WikiContext(): def getWikiContext(self, view, request): context = { 'app': request.resolver_match.app_name, 'controller': view.__class__.__module__.split('.')[-1], 'action': view.__class__.__name__.lower(), 'categories': CategoryModel.objects.all() } return context I call it like this in every single view: context = WikiContext().getWikiContext(self, request) Is it possible to make it a little less code? I don't wanna repeat the call in every single view if possible. Thank you.