Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change local based on object
I work on a website that needs to differentiate UK english and US english. The distinction we try to make is not per session but rather per object. e.g. We have a UK dog and a US cat, the UK dog costs Β£1 and the US cat $2. The stored value of the cost is 1 and 2 and both object have a locale value: uk / us. We already tried to add a middleware to switch the locale depending on the request. But having to fetch the object (based on the url's parameters) seems excessive. Another idea was to add a ?locale=xx to each url, but it's not ideal, since the information is already stored on the object. Is there a way to use the django i18n mechanism to handle the translation between languages per object? Meaning if the object.locale is uk render Β£, if it's us render $. -
UpdateView and jQuery.ajax()
In my Django project I have a model with just a couple of fields. But there are a lot of related objects: sets of dates, places, comments etc. But its DetailView shows rather a lot of things. So, I decided to update the model via ajax. Django's UpdateView uses redirect to success_url. This seems to be the root of all the troubles. I used this: https://docs.djangoproject.com/en/1.10/topics/class-based-views/generic-editing/#ajax-example I checked the update form manually in the browser. And via ajax the data is also updated on the server. But I can't catch the result via ajax. In Chrome dev tools while debugging js I occur in fail function. And jqXHR.status=0, textStatus = "error", errorThrown="". When I switch from Sources tab to Console I can read: POST http://localhost:8000/frame/2/ 405 (Method Not Allowed) Could you help me cope with this? views.py class FrameUpdate(AjaxableResponseMixin, UpdateView): model = Frame form_class = FrameUpdateForm template_name = "general/ajax/ajax_form.html" def get_success_url(self): success_url = reverse_lazy("frame:frame_detail_ajax", kwargs={"pk":self.object.id}) return success_url frame.js function fail(jqXHR, textStatus, errorThrown){ debugger; } function post(){ $.ajax({ method: "POST", url: "http://localhost:8000/frame/2/update/", data: $("#frame_form").serialize(), success: show_post, error: fail }); } -
django-rest-framework : list parameters in URL
I am pretty new to django and django-rest-framework, but I am trying to pass lists into url parameters to then filter my models by them. Lets say the client application is sending a request that looks something like this... url: "api.com/?something=string,string2,string3/?subthings=sub,sub2,sub3/?year=2014,2015,2016/" I want to pass in those parameters "things", "subthings", and "years" with their values. Where the url looks something like this? NOTE: Trick is that it won't be always an array of length 3 for each parameter. Can someone point me in the right direction for how my url regex should be handing the lists and also retrieving the query lists in my views. Thanks! -
How to put label and input box on the same line using bootstrap?
I've searched extensively on this site and tried my best, but cannot figure out how to put the label and input on the same line, right now, it displays like this:label and input box are on different lines First, as people suggested, I grouped them using "form-group" class, but no luck. Then I continued to search, some says you should use "col-sm-1" which I tried, no luck, some says you should use "form-control-static", but still no luck. Any help is deeply appreciated! <div class="tab-content"> <div class="row" id="create_new_spa_form"> <form method= "post" action ="/purchasing/item_info_new_spa/" onsubmit="javascript: return validate();"> <div class="span4"> <div class="form-group"> <label class="control-label col-sm-1" for="input01">Text input</label> <div class="controls col-sm-1"> <input type="text" class="form-control-static" id="input01"> </div> </div> </div> <div class="span4"> <div class="form-group"> <label class="control-label" for="input01">Text input</label> <div class="controls"> <input type="text" class="input-xlarge" id="input01"> </div> </div> </div> <div class="span4"> <div class="form-group"> <label class="control-label" for="input01">Text input</label> <div class="controls"> <input type="text" class="input-xlarge" id="input01"> </div> </div> </div> </form> </div> </div> -
Pass user replies across different pages
I'd like to create a small web application with Django. It's about different questions: I have ~20 questions/statements that can be answered with "Agree"/"Don't agree"/"Neutral". Now I need a way to pass the data because at the end, when the user has answered all questions I have to analyse the input. But I don't know what's the best way to save the data across the different pages/questions. I guess Form wizard could be a good idea. How many questions I have is saved in the database. But I don't know how to create one Form class for every question dynamically. It would be nonsense to hardcode the form like here: https://django-formtools.readthedocs.io/en/latest/wizard.html#defining-form-classes So, is there a way how I can use it and depening on how many questions are in the database, more or less Form classes get created? Or do you have a whole different solution for my problem? -
django frontend login: TypeError at /auth/login dict expected at most 1 arguments, got 2
In the project im working on the admin site is working fine and i want to test the frontend. But im Getting: TypeError at /auth/login dict expected at most 1 arguments, got 2 Here the full traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/auth/login?next=/ Django Version: 1.10 Python Version: 2.7.10 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'django_nose', 'widget_tweaks', 'rest_framework', 'rest_framework_gis', 'backbone_app', 'accounts', 'map') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "D:\SHK\ElektroClean\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "D:\SHK\ElektroClean\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) File "D:\SHK\ElektroClean\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "D:\SHK\ElektroClean\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\SHK\ElektroClean\accounts\views.py" in login_view 47. return render(request, 'login.html', context) File "D:\SHK\ElektroClean\lib\site-packages\django\shortcuts.py" in render 30. content = loader.render_to_string(template_name, context, request, using=using) File "D:\SHK\ElektroClean\lib\site-packages\django\template\loader.py" in render_to_string 68. return template.render(context, request) File "D:\SHK\ElektroClean\lib\site-packages\django\template\backends\django.py" in render 64. context = make_context(context, request, autoescape=self.backend.engine.autoescape) File "D:\SHK\ElektroClean\lib\site-packages\django\template\context.py" in make_context 267. context.push(original_context) File "D:\SHK\ElektroClean\lib\site-packages\django\template\context.py" in push 59. return ContextDict(self, *dicts, **kwargs) File "D:\SHK\ElektroClean\lib\site-packages\django\template\context.py" in __init__ 18. super(ContextDict, self).__init__(*args, **kwargs) Exception Type: TypeError at /auth/login Exception Value: dict expected at most 1 arguments, got 2 This is the urls.py : urlpatterns = [ url(r'^map/', include('map.urls')), url(r'^admin/', include(admin.site.urls)), β¦ -
page content not rendering properly - python / django?
I am running ubuntu 16.4 with apache2 webserver I am trying to setup this site, downloaded from github: https://github.com/mozilla/http-observatory-website Unfortunately, there is no instructions to follow :( if put these files in the working/public directory and point to index.html from the browser i.e. http://localhost/laravel/work/public/ The page comes up but what seems to be djamgp code shows up.. there is also two python files and a Makefile in the same directory but not sure what to do with those or if anything needs to be compiled - which i also dont have a clue how to do. Here is a screenshot of what it looks like: https://snag.gy/4npmjY.jpg Any assistance would be much appreciated! -
Django Static Finders Search Path
One of the default Django static finder is django.contrib.staticfiles.finders.FileSystemFinder, question is where does Django search for using this default? -
configure django reactjs webpack socket.io and rabbitmq
I am tempted by Internet of Things concept. I want to learn by implementing it on raspberry pi. I have created a boilerplate for my project which covers Reactjs, Webpack and Django. However i want Socket.io and Rabbitmq. I am blank on configuring them to my existing project. I am not using express and will not too. How can i now integrate Socket.io and Rabbitmq in my existing project. Glance at my configuration Project Layout webpack.config.js var path = require("path"); var webpack = require("webpack"); // webpack sets the NODE_ENV when calling it with -p or -d if(!process.env.NODE_ENV) { process.env.NODE_ENV = 'development'; } var webpackConfig = { cache: true, entry: "./src/index.js", output: { path: path.join("../app/static/build/", "js"), filename: "app.js" }, module: { loaders: [ { test: /\.js$/, loader: "babel-loader", exclude: /node_modules/, query: { presets: ['es2015', 'react', 'babel-preset-stage-0'] } } // also adds ES6 support ] }, plugins: [ new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV) }) ], resolve: { root: path.join(__dirname, "src"), modulesDirectories: ["node_modules"] } }; if(process.env.NODE_ENV == 'production') { webpackConfig.plugins.push( new webpack.optimize.UglifyJsPlugin() ); } module.exports = webpackConfig; -
Setting label_suffix for a Django modelform_set
I have a Product model that I use to create ProductFormSet. How do I specify the label_suffix to be something other than the default colon? I want it to be blank. Solutions I've seen only seem to apply when initiating a form - here. ProductFormSet = modelformset_factory(Product, exclude=('abc',)) products = Product.objects.order_by('product_name') pformset = ProductFormSet(queryset=products) -
django cannot fix integrity error
I've decided to drop a row from a field from a database i'm setting up in django. I've deleted it in models/form and completely re-ran the database (makemigrations, migrate). However, no matter what I do i keep getting an integrity error (NOT NULL constraint failed: index_user.email). I'm not sure why i'm getting this, as the field doesn't even exist anymore and I cant find any trace of it in any files. Anyone know how to solve this error? -
How to modify Django form before save?
In my project each user can have multiple enemies, like this: models class EnemyModel(models.Model): name = models.CharField(max_length=128) weapon = models.CharField(max_length=128) related_user = models.ForeignKey(UserProfile) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Only user can add enemies to his profile, so I made a form like this: forms class AddEnemyForm(forms.ModelForm): class Meta: model = EnemyModel exclude = ['related_user'] # only current user My idea was to modify the excluded field in a view, but it doesn't work: views def add_enemy(request): args={} if request.method == "POST": form = AddEnemyForm(request.POST) form.related_user = request.user # error # form.related_user_id = request.user.id # also error if form.is_valid(): form.save() return HttpResponse("<h1>Done!</h1>") else: args.update(csrf(request)) args["form"]=form return render_to_response("add_enemy.html",args) args.update(csrf(request)) args["form"]=AddEnemyForm() return render_to_response("add_enemy.html",args) How to modify a form before save? -
Django Haystack - ElasticCloud Spatial Search Error search_phase_execution_exception
We have a spatial search plugin in which all items within a specified distance around a lat-lng is searched. Following my package versions: Django 1.9 Django-Haystack 2.4.1 Elasticsearch 2.4.0 (Hosted at ElasticCloud) It was working fine when used with Elasticsearch 1.9.0 which was setup in my local machine itself. Here is the code: max_dist = D(m=distance) location = Point((float(lng), float(lat))) sqs = sqs.dwithin('location', location, max_dist).using(using).distance('location', location) And I am getting below error in my terminal: Failed to query Elasticsearch using '*:*': TransportError(500, u'search_phase_execution_exception', u'org.elasticsearch.index.fielddata.plain.PagedBytesIndexFieldData cannot be cast to org.elasticsearch.index.fielddata.IndexGeoPointFieldData') Traceback (most recent call last): File "/home/user/Virtuals/myapp/local/lib/python2.7/site-packages/haystack/backends/elasticsearch_backend.py", line 516, in search _source=True) File "/home/user/Virtuals/myapp/local/lib/python2.7/site-packages/elasticsearch/client/utils.py", line 69, in _wrapped return func(*args, params=params, **kwargs) File "/home/user/Virtuals/myapp/local/lib/python2.7/site-packages/elasticsearch/client/__init__.py", line 539, in search doc_type, '_search'), params=params, body=body) File "/home/user/Virtuals/myapp/local/lib/python2.7/site-packages/elasticsearch/transport.py", line 327, in perform_request status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout) File "/home/user/Virtuals/myapp/local/lib/python2.7/site-packages/elasticsearch/connection/http_urllib3.py", line 109, in perform_request self._raise_error(response.status, raw_data) File "/home/user/Virtuals/myapp/local/lib/python2.7/site-packages/elasticsearch/connection/base.py", line 113, in _raise_error raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info) TransportError: TransportError(500, u'search_phase_execution_exception', u'org.elasticsearch.index.fielddata.plain.PagedBytesIndexFieldData cannot be cast to org.elasticsearch.index.fielddata.IndexGeoPointFieldData') -
How to update some data when post object in Django Rest?
I have this Serializer: class LikeSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(queryset=ExtUser.objects.all(), required=False, allow_null=True, default=None) class Meta: model = Like field = ('user', 'post') def create(self, validated_data): post = Post(id=validated_data['post'], author=validated_data['user']) #post=Post.objects.get(pk=validated_data['post']) post.rating += 1 print(post) post.save() return Like.objects.create(**validated_data) And I get error, when i trying to save Like object TypeError: int() argument must be a string or a number, not 'Post' Trying to add int(), but it not helps, I think I not correct update Post object -
How to test RPC of SOAP web services?
I am currently learning building a SOAP web services with django and spyne. I have successfully tested my model using unit test. However, when I tried to test all those @rpc functions, I have no luck there at all. What I have tried in testing those @rpc functions: 1. Get dummy data in model database 2. Start a server at localhost:8000 3. Create a suds.Client object that can communicate with localhost:8000 4. Try to invoke @rpc functions from the suds.Client object, and test if the output matches what I expected. However, when I run the test, I believe the test got blocked by the running server at localhost:8000 thus no test code can be run while the server is running. I tried to make the server run on a different thread, but that messed up my test even more. I have searched as much as I could online and found no materials that can answer this question. TL;DR: how do you test @rpc functions using unit test? -
python manage.py runserver error environment variable
i tried running this.i m learning django but this shows error..Please help. Kaustubhs-MacBook-Pro-2:crmeasy kaustubhmundra$ python manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/Library/Python/2.7/site-packages/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/Library/Python/2.7/site-packages/django/core/management/init.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 317, in run_from_argv connections.close_all() File "/Library/Python/2.7/site-packages/django/db/utils.py", line 229, in close_all for alias in self: File "/Library/Python/2.7/site-packages/django/db/utils.py", line 223, in iter return iter(self.databases) File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/Library/Python/2.7/site-packages/django/db/utils.py", line 156, in databases self._databases = settings.DATABASES File "/Library/Python/2.7/site-packages/django/conf/init.py", line 53, in getattr self._setup(name) File "/Library/Python/2.7/site-packages/django/conf/init.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/Library/Python/2.7/site-packages/django/conf/init.py", line 97, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/Users/kaustubhmundra/Desktop/Django/crmeasy/crmapp/settings.py", line 28, in ENV_ROLE = get_env_variable('ENV_ROLE') File "/Users/kaustubhmundra/Desktop/Django/crmeasy/crmapp/settings.py", line 25, in get_env_variable raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the ENV_ROLE environment variable -
Filter Django's LogEntry to get objects recently edited by a particular user
I'm trying to get a list of n of objects recently updated by user u sorted by the update datetime (the datetime when u updated the object, not the object's updated datetime simpliciter). I'm using Django's LogEntry model to first get the LogEntries I'm interested in: object_log_ids = LogEntry.objects.filter( user_id=self.request.user.id, content_type_id=model_content_type.id ).order_by( 'object_id', '-action_time' ).distinct('object_id').values_list('id', flat=True) and then sort them by action_time and limit the number of objects returned: object_logs = LogEntry.objects.filter( id__in=object_log_ids ).order_by( '-action_time' )[:n] The only problem is that I need access to the objects being updated, because I want to show information about them and their related objects on a template. Calling get_edited_object() for every LogEntry instance will issue an individual query, just like Model.objects.get(pk=PK). I cannot figure out how to construct a JOIN, or a select_related to get the edited objects together with their LogEntries. -
Non-relational database schema for Django with postgres
My Django project uses postgresql 9.4, which supports JSON fields. I would like to switch from a relational to a (partly) non-relational schema using these fields. Say I have models Foo and Bar and each object Bar belongs to exactly one Foo. Currently, I use a ForeignKey from Bar to Foo to model this, but I would like to switch to storing the Bar objects directly inside Foo as a list of model instances. With postgresql, I can use a JSONField in Foo which would store a list of JSON representations of Bar objects, but then I would have to deal with serialization to JSON manually. The MongoDB ORM for Django provides the Django fields to do that in a clean way: class Foo(models.Model): bar_list = ListField(EmbeddedModelField('Bar') Is there a way to have a similar functionality with the postgres backend? -
Django -- One Template used with multiple variables
I'm trying to display a list of tickets in an HTML table. The table has various headings to display various aspects of the tickets. I would like to present this same table in a bunch of different locations across my project. I've made a single template of /templates/shared/ticket_list.html in which presents the ticket list and then I {% include %} it where I need to display this listing. Simple enough. However, there are a couple of pages in my project where I have a Bootstrap tabbed div. I want to display this table of tickets in both tabs, but with a different set of tickets. The HTML for this essentially requires that I {% include %} my table template twice on the same HTML page. For example: Tab 1: "Created By User" -- a list of tickets that the current user created Tab 2: "Assigned To User" -- a list of tickets that are assigned to the current user In the view, I might have something like: created_by_ticks = Ticket.objects.filter(created_by = self.request.user) assigned_to_ticks = Ticket.objects.filter(assigned_to = self.request.user) The problem is, in my ticket table template, how would I present both querysets since the table itself is likely expecting a single β¦ -
i am using angularjs and django-cors-headers then give "which is disallowed for cross-origin requests that require preflight."
I have a Django local sever that refer to 8000 port, And a local nginx that load 2080 html page. I install django-cross-header package for resolving cross-domain error. django-cross-header config in settings.py: CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_HEADERS = ( 'x-requested-with', 'content-type', 'accept', 'origin', 'authorization', 'x-csrftoken' ) CORS_ORIGIN_WHITELIST = ( '127.0.0.1:2080', 'localhost:2080' ) Config angularjs is like this: portman.config(function ($routeProvider, $interpolateProvider, $httpProvider) { $routeProvider.otherwise('/'); $httpProvider.defaults.headers.common['X-CSRFToken'] = csrftoken; $interpolateProvider.startSymbol('{$').endSymbol('$}'); delete $httpProvider.defaults.headers.common['X-Requested-With']; }); portman.constant('ip','http://127.0.0.1:8000/'); Get method code in angularjs is: $http({ method: 'GET', url: ip+'api/v1/dslam/events', }).then(function (result) { $scope.dslam_events = result.data; }, function (err) { }); request header is : Provisional headers are shown Accept:application/json, text/plain, */* Origin:http://127.0.0.1:2080 Referer:http://127.0.0.1:2080/ User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.99 Safari/537.36 X-CSRFToken:ztouFO8vldho97bWzY9mHQioFk3j6h5V After loading the page I see this error: XMLHttpRequest cannot load http://127.0.0.1:8000/api/v1/dslam/events.The request was redirected to 'http://127.0.0.1:8000/api/v1/dslam/events/', which is disallowed for cross-origin requests that require preflight. But when i send request from console it will corectly response from django server, my jquery code : $.ajax({ type: 'GET', url: "http://5.202.129.160:8020/api/v1/dslam/events/", success:function(data){ console.log(data); } }); request header is: Accept:*/* Accept-Encoding:gzip, deflate, sdch Accept-Language:en-US,en;q=0.8,fa;q=0.6,pt;q=0.4 Connection:keep-alive Host:127.0.0.1:8000 Origin:http://127.0.0.1:2080 Referer:http://127.0.0.1:2080/ User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.99 Safari/537.36 please help me. -
Ubuntu server 16.04 failed building wheel for psycopg2
I'm setting up my new server (ubuntu 16.04.01) and i need to setup my sistem with postgres (9.3)+virtualenv+python+django(1.6)+nginx ecc.. I have already set-up the same sistem, 2 years ago, on ubuntu 14.04 with no problem, but now on new lts, i cant'install psycopg2. When from virtualenv i try to execute pip install psycopg2 i receve this error message: (gips) gips@gips-locale:~/gips/virtualenv/gestogips$ pip install psycopg2 Collecting psycopg2 Using cached psycopg2-2.6.2.tar.gz Building wheels for collected packages: psycopg2 Running setup.py bdist_wheel for psycopg2 ... error Complete output from command /home/gips/gips/virtualenv/gips/bin/python2 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-PF24T2/psycopg2/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /tmp/tmp9wlqN9pip-wheel- --python-tag cp27: running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/psycopg2 copying lib/__init__.py -> build/lib.linux-x86_64-2.7/psycopg2 copying lib/pool.py -> build/lib.linux-x86_64-2.7/psycopg2 copying lib/errorcodes.py -> build/lib.linux-x86_64-2.7/psycopg2 copying lib/extensions.py -> build/lib.linux-x86_64-2.7/psycopg2 copying lib/_range.py -> build/lib.linux-x86_64-2.7/psycopg2 copying lib/psycopg1.py -> build/lib.linux-x86_64-2.7/psycopg2 copying lib/tz.py -> build/lib.linux-x86_64-2.7/psycopg2 copying lib/_json.py -> build/lib.linux-x86_64-2.7/psycopg2 copying lib/extras.py -> build/lib.linux-x86_64-2.7/psycopg2 creating build/lib.linux-x86_64-2.7/psycopg2/tests copying tests/testutils.py -> build/lib.linux-x86_64-2.7/psycopg2/tests copying tests/test_lobject.py -> build/lib.linux-x86_64-2.7/psycopg2/tests copying tests/test_types_basic.py -> build/lib.linux-x86_64-2.7/psycopg2/tests copying tests/test_copy.py -> build/lib.linux-x86_64-2.7/psycopg2/tests copying tests/__init__.py -> build/lib.linux-x86_64-2.7/psycopg2/tests copying tests/test_transaction.py -> build/lib.linux-x86_64-2.7/psycopg2/tests copying tests/test_bug_gc.py -> build/lib.linux-x86_64-2.7/psycopg2/tests copying tests/test_connection.py -> build/lib.linux-x86_64-2.7/psycopg2/tests copying tests/test_green.py -> build/lib.linux-x86_64-2.7/psycopg2/tests copying tests/test_bugX000.py -> build/lib.linux-x86_64-2.7/psycopg2/tests copying tests/test_module.py -> build/lib.linux-x86_64-2.7/psycopg2/tests copying tests/test_dates.py -> build/lib.linux-x86_64-2.7/psycopg2/tests copying β¦ -
Django tag-style input for a list of names
I'm working in Django and I'm currently doing the following to take a comma separated list of names from a CharField and instantiate a new Participant for each name: In forms.py: class ActivityForm(Form): participants = CharField(label = 'Participant names (comma separated)') In views.py: def newActivityView(request): if request.method == 'POST': if form.is_valid(): names = form.cleaned_data['participants'] names = names.split(",") for name in names: new_participant=Participant(name= name) new_participant.save() return HttpResponse... else: Render an empty form Now I don't like the comma separated approach at all. What I want is a tag input field as described here: django-tags-input (this is a Django wrapper for a jQuery tag input field). I have installed this module and added it to my installed apps. What should I put in TAGS_INPUT_MAPPINGS and how do I change my existing code to use a different kind of input field? Can't really make it out from the documentation. Thanks :) -
Django 1.10 ManagementForm data is missing or has been tampered with
I'm using Django Modelforms and also from django.forms import modelformset_factory here is my View def load_meetings(request): if request.method == 'POST': # and request.user.is_authenticated(): RemindersFormSet = modelformset_factory(Reminder, form=ReminderForm, fields=('reminder_type', 'reminder_time')) RemindersFormSet = modelformset_factory(Reminder, exclude=(), can_delete=True, form=ReminderForm, extra=0) data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '10', } reminder_form_set = RemindersFormSet(data) meetings = Event.objects.filter(event_type='Meeting').order_by('-id') print(reminder_form_set) print(reminder_form_set.total_form_count()) return render(request, 'meetings.html', {'meetings': meetings, 'reminder_form_set': reminder_form_set}) else: return HttpResponse('Invalid Method or Not Authanticated in load_meetings') return HttpResponse('Oops!! Something Went Wrong.. in load_tasks') My Model class Reminder(models.Model): reminder_type = models.CharField(max_length=5, blank=True, null=True) reminder_time = models.DateTimeField(blank=True, null=True) def __str__(self): return self.reminder_type My Model Form class ReminderForm(forms.ModelForm): class Meta: model = Reminder fields = '__all__' reminder_type = forms.ChoiceField(choices=(('Email', 'Email'), ('Popup', 'Popup')), error_messages={ 'invalid': ("Invalid Reminder type selected.")}, widget=forms.Select(attrs={'class': 'form-control'}), required=False) reminder_time = forms.ChoiceField(choices=(("0", "on time"), ("60", "1m before"), ("120", "2m before"), ("300", "5m before"), ("600", "10m before"), ("900", "15m before"), ("1800", "30m before"), ("3600", "1h before"), ("7200", "2h before"), ("10800", "3h before"), ("18000", "5h before"), ("86400", "1d before") ), error_messages={ 'invalid': ("Invalid Reminder time selected.")}, widget=forms.Select(attrs={'class': 'form-control'}), required=False) My template <div id="reminder1"> {{ reminder_form_set.management_form }} <div class="reminderslist"> {% for form in reminder_form_set %} {{ form.reminder_type }} {{ form.reminder_time }} <button type="button" id="remove" style="border:none;padding: 10px"> <span class="glyphicon glyphicon-remove"></span> </button> β¦ -
uWSGI-Django spending too much time on poll method
I am using Nginx-uWSGI combination for my Django project, but the performance is sub-par when I compare it with Nginx-Apache-modwsgi combination. Apparently uwsgi was taking about 3-5 seconds to provide response for requests which should be server in about 300-400ms at most. When I ran profiling, I realized most of the time is being spend in response.render function in uWSGI Handler. Here are the profiling results - I am unable to figure out why method poll is consuming more than 90% of the time, even when there is just one request on the server. Here is my uwsgi configuration [uwsgi] uid = www-data gid = www-data listen = 10000 socket-timeout = 60 socket-send-timeout = 60 socket-write-timeout = 60 set-placeholder = username=sysadmin set-placeholder = project_directory=/home/sysadmin/builds/deploy_dir/qa_shine set-placeholder = ruby_shims_path=/home/sysadmin/.rbenv/shims socket = /run/%n.sock chmod-socket = 666 chdir = %(project_directory) pidfile = /run/%n.pid wsgi-file = deploy/uwsgi.py master = true processes = 1 threads = 1 harakiri = 160 virtualenv = /home/%(username)/Envs/candidate/ stats = 127.0.0.1:9191 vacuum = true die-on-term = true daemonize = /var/log/uwsgi/%n.log env = LANG=en_US.UTF-8 auto-procname = true env = PATH=%(ruby_shims_path):$(PATH) env = RUBYPATH=%(ruby_shims_path)/ruby rbrequire = rubygems My nginx upstream configuration location / { uwsgi_pass django; include uwsgi_params; proxy_buffering off; proxy_buffers 128 128k; β¦ -
ImportError for a custom SimpleTestCase child using python manage.py test app
I want to use a generic custom TestCase for my_app that is currently running fine. I have the following simplified directory architecture : my_app βββ tests β βββ __init__.py β βββ test_views β βββ __init__.py β βββ custom_test.py β βββ registration β β βββ __init__.py β β βββ test_login.py βββ views |ββ __init__.py βββ registration β βββ __init__.py β βββ login.py The CustomTest class look like this : from django.test import SimpleTestCase from django.test.client import Client class LionessTest(SimpleTestCase): def setUp(self): self.client = Client() The test I want to launch is the following one : from tests.test_views.custom_test import CustomTest class Test_Login(CustomTest): def test_thing(self): self.assertTrue(True) The 'my_app' directory is in the pythonpath and there is an init.py file for every module. Django can find error in test_login.py (for example if I change CustomTest to something else that does not exists), so test_login.py is read before my real problem happens and it imports and uses CustomTest sucessfully. But when I want to launch the test with : python manage.py test my_app I get the following error : ImportError: Failed to import test module: my_app.tests.test_views.registration.test_login Traceback (most recent call last): File "/usr/lib/python2.7/unittest/loader.py", line 254, in _find_tests module = self._get_module_from_name(name) File "/usr/lib/python2.7/unittest/loader.py", line 232, in β¦