Re: Multiple Database Setup problem !?
Hi David Your router isn't configured correctly. This applies to all the allow_foo() methods, but see allow_migrate [1] as an example: Determine if the migration operation is allowed to run on the database with alias db. Return True if the operation should run, False if it shouldn’t run, or None if the router has no opinion. Your routers *should* be having an opinion about whether that app/model can be migrated on a specific database! For instance, you say "the last app" should stay only on validations, but what your ValidationRouter says is "If the app label is called fourth_model, run migrations on this database", but it never checks what the database is. For ValidationRouter.allow_migrate you probably want something like this: def allow_migrate(self, ...): if app_label == "fourth_model": return db == "validations" elif db == "validations": return False EG: * if the app label is an app that should be in the validations DB, allow migrate when the db is the validations DB * if it isn't and the DB is the validations DB, don't allow migrations to it * if neither of those things, this router doesn't care. Similarly, for allow_relations() you should be returning False when the models should not be related. Incidentally, all python functions return None if the end of the function is reached without an explicit return value, so you never have to end your functions with an explicit "return None". Cheers Tom [1] https://docs.djangoproject.com/en/2.1/topics/db/multi-db/#allow_migrate On Tue, Oct 30, 2018 at 10:09 AM David Lubomirov wrote: > > Hello, > > In my project I have 3 applications, and I'm trying to split them across 2 > databases. > > More specifically 2 of the apps and Django "auth" application should work > with the first database, > and the last application should remain in the second database. > > These are the DB settings: > > DATABASE_ROUTERS = [ > '.PrimaryRouter', > '.ValidationRouter' > ] > > DATABASES = { > 'default': {}, > 'primary': { > 'NAME': 'primary', > 'ENGINE': 'django.db.backends.postgresql', > 'USER': '', > 'PASSWORD': '', > 'HOST': 'localhost', > }, > 'validations': { > 'NAME': 'validations', > 'ENGINE': 'django.db.backends.postgresql', > 'USER': '', > 'PASSWORD': '', > 'HOST': 'localhost', > } > } > > Therefore these are the class routers: > > class PrimaryRouter: > """ > Router to control all database operations for the following applications: > - first_model > - second_model > - auth > """ > def db_for_read(self, model, **hints): > if model._meta.app_label == 'auth' or \ > model._meta.app_label == 'first_model' or \ > model._meta.app_label == 'second_model': > > return 'primary' > > return None > > def db_for_write(self, model, **hints): > if model._meta.app_label == 'auth' or \ > model._meta.app_label == 'first_model' or \ > model._meta.app_label == 'second_model': > > return 'primary' > > return None > > def allow_relation(self, first_object, second_object, **hints): > if first_object._meta.app_label == 'auth' or \ > second_object._meta.app_label == 'auth': > > return True > > if first_object._meta.app_label == 'first_model' or \ > second_object._meta.app_label == 'first_model': > > return True > > if first_object._meta.app_label == 'second_model' or \ > second_object._meta.app_label == 'second_model': > > return True > > return None > > def allow_migrate(self, db, app_label, model_name=None, **hints): > if app_label == 'auth' or \ > app_label == 'first_model' or \ > app_label == 'second_model': > > return db == 'primary' > > return None > > > class ValidationRouter: > """ > Router to control all database operations for the following applications: > - fourth_model > """ > def db_for_read(self, model, **hints): > if model._meta.app_label == 'fourth_model': > return 'validations' > > return None > > def db_for_write(self, model, **hints): > if model._meta.app_label == 'fourth_model': > return 'validations' > > return None > > def allow_relation(self, first_object, second_object, **hints): > if first_object._meta.app_label == 'fourth_model' or \ > second_object._meta.app_label == 'fourth_model': > return True > > return None > > def allow_migrate(self, db, app_label, model_name=None, **hints): > if app_label == 'fourth_model': > return True > > return None > > > When I run migration on the first database "primary", everything is working. > But on the second database I'm getting
Re: Get data from an external api into my database.
On Tue, Mar 20, 2018 at 10:23 AM, Mukesh Jhawrote: > I want to access a api from http://open-platform.theguardian.com/ or > https://newsapi.org/ and load it into my sqlite database. The data in these > site is in json format and I want them to get converted into my database > model format and store in it and later on use them as when queried. I am > clueless as I am quite new in this development system. Please help if > possible. > Adjust for your needs: data = requests.get(url).json() for datum in data: MyModel.objects.save(**datum) Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2BHs0DHHZtpR8L2asSAtNLdw_NaJF-ST9%2BRsTwQ021-fA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Trouble deploying Django/wagtail on Ubuntu 14.04
It is not looking for "home_page.html", it is looking for "base/home_page.html". On the error page it lists the locations it is searching for the template, and explicitly says the directories that are being searched. You say the file is at /home//bakerydemo/bakerydemo/templates/base/home_page.html It says it is looking in /var/www/bakerydemo/templates/ This means that your TEMPLATES['DIRS'] setting is wrong. Looking at the configuration section of the error report shows that you have put a relative path into TEMPLATE['DIRS']. Use settings.PROJECT_ROOT to make that in to an absolute path, as the example settings.py tells you to do. Cheers Tom PS - there is very little point anonymising your username when you share the full error report. On Tue, Mar 20, 2018 at 4:14 PM, drone4fourwrote: > Thank you, Andreas. I added the python-path to my Apache ssl.conf and the > Internal Server Error is gone now. It appears WSGI is serving my Django > project perfectly. > > I adjusted ALLOWED_HOSTS just fine. But now Django is saying something about > "TemplateDoesNotExist at /" in base/home_page.html. You can see the full > Django traceback here: https://daniel496.agency/ > > $ locate home_page.html > /home//.virtualenvs/wagtailbakerydemo/lib/python3.4/site-packages/wagtail/project_template/home/templates/home/home_page.html > /home//bakerydemo/bakerydemo/templates/base/home_page.html > > The home_page.html file is present but apparently it is not being referred > to properly in my configuration. Can anyone shed some light on what the > issue could be now? > > Thanks. > > On Tuesday, March 20, 2018 at 5:45:27 AM UTC-4, Cictani wrote: >> >> You have to set the python-path too: >> >> WSGIDaemonProcess bakerydemo >> python-home=/home//.virtualenvs/wagtailbakerydemo/ >> python-path=/home//bakerydemo/ >> >> In the logs you see "No module named 'bakerydemo'" because you did not add >> the project directory to the python-path. Hope this works. >> >> Best regards >> >> Andreas > > -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to django-users+unsubscr...@googlegroups.com. > To post to this group, send email to django-users@googlegroups.com. > Visit this group at https://groups.google.com/group/django-users. > To view this discussion on the web visit > https://groups.google.com/d/msgid/django-users/d90b8924-5458-4c0e-8f0f-2866af4dd156%40googlegroups.com. > > For more options, visit https://groups.google.com/d/optout. -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2B%2BfRpK3EqfqqojAt9%2BUyWyx79QYo-nopq0zx38Bdi93Q%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Running makemigrations in pluggable nested app using AppConfig
In order to make it "work", I imported the models from foo_lib.django app.models into foo_lib.models. Django was then able to find the models, and create the migration files. They are all in the wrong place however, that part of the library should have nothing to do with django and so this obviously isn't correct. I didn't mention it in the first post, this is for py{27,34,35,36}-dj{108,109,110,111,200}, and developing against py36-dj200 Cheers Tom On Mon, Mar 19, 2018 at 3:35 PM, Tom Evanswrote: > Hi all > > I'm writing a small library which will be bundled together with a > pluggable django app. > > The app provides a bunch of different AppConfig instances, the end > user chooses one and pops it in their INSTALLED_APPS: > > INSTALLED_APPS += [ 'foo_lib.contrib.django_app.configs.FooAppConfig', ] > > All the AppConfigs have their name attribute set to "foo_lib", they > have their path attribute set to the directory containing models.py > and there is a default AppConfig > > I have a test project that I'm using to run "makemigrations" and so > on. With INSTALLED_APPS as above, django cannot find any changes for > "foo_lib". If I supply the dotted path to the appconfig to > "makemigrations", I am told: > >"App 'foo_lib.contrib.django.configs.FooAppConfig' could not be > found. Is it in INSTALLED_APPS?" > > which is quite amusing. > > If I replace the path to the appconfig with the dotted path to the > module, and then use "makemigrations django_app", then the migrations > get created, but obviously that seriously sucks. > > Furthermore, even with the migration files in place, they are not > actually acted upon when running migrate or tests. > > > What is the correct way to do this? > > Cheers > > Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1K3LbBjV%2BwbxdgKnTJj_nnGHHqkMNcRn2ROwVEXiaecgQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Running makemigrations in pluggable nested app using AppConfig
Hi all I'm writing a small library which will be bundled together with a pluggable django app. The app provides a bunch of different AppConfig instances, the end user chooses one and pops it in their INSTALLED_APPS: INSTALLED_APPS += [ 'foo_lib.contrib.django_app.configs.FooAppConfig', ] All the AppConfigs have their name attribute set to "foo_lib", they have their path attribute set to the directory containing models.py and there is a default AppConfig I have a test project that I'm using to run "makemigrations" and so on. With INSTALLED_APPS as above, django cannot find any changes for "foo_lib". If I supply the dotted path to the appconfig to "makemigrations", I am told: "App 'foo_lib.contrib.django.configs.FooAppConfig' could not be found. Is it in INSTALLED_APPS?" which is quite amusing. If I replace the path to the appconfig with the dotted path to the module, and then use "makemigrations django_app", then the migrations get created, but obviously that seriously sucks. Furthermore, even with the migration files in place, they are not actually acted upon when running migrate or tests. What is the correct way to do this? Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1JH2Y2WJrriCrs0x6eH4Le3cVsTR19jYRDzxEw70-C6FA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: UUIDs eventually choke as primary key
On Fri, Feb 23, 2018 at 4:20 PM, M Mackeywrote: > I have noticed in the python > path that there are two paths to .../lib/python3.6. One from my virtualenv, > and one at /usr/local/. Not sure where to clear that up, since I don't > believe I've got my apache env set up to pull from both places. That would happen if you created your virtualenv with --use-site-packages, it, er, puts the path to the site packages in the pythonpath. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1KkY%2B_WXpTsEiA-2RmXg%2Bz7n5Zij-ie1-gvqKnL4KGOHg%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
StaticLiveServerTestCase: database emptied after first test after upgrading to Django 1.11
Hi all We have a bunch of functional tests derived from StaticLiveServerTestCase using selenium that have started failing after upgrading from Django 1.8 to Django 1.11. The database is initially populated via data migrations, but after running one test it all the data loaded via migrations has been removed from the database, and all subsequent tests fail because the expected data is not in the database. Note that this is after running one test, not one test case; if we run each test from an affected test case individually, they pass; if we run the entire test case, the first test passes and the rest fail. These tests were initially written under Django 1.8, with the data coming from the same migrations, and they worked correctly in Django 1.8. I looked back through the release notes and documentation; rollback emulation[1] via serialized_rollback=True appeared promising, but after enabling it we had IntegrityErrors immediately after finishing the first test; it appears as though when it was attempting to re-load the serialized data back in to the database, the data was still there: Any thoughts? I've included some of the output below - running without serialized_rollback[2] and with[3]. Unfortunately, I cannot share much of the code itself. Cheers Tom [1] https://docs.djangoproject.com/en/1.11/topics/testing/overview/#rollback-emulation [2] tests.functional_tests.test_search_defaults.DefaultSearchResultsTest test_browsing_to_a_saved_search_keeps_the_default_hero_block ... [, , ] ok test_infinite_scrolling_of_search_results ... [] ERROR screenshotting to /home/london/te/moat-effortless_web_app/reports/screendumps/DefaultSearchResultsTest.test_infinite_scrolling_of_search_results-window0-2 018-02-23T11.59.55.png dumping page HTML to /home/london/te/moat-effortless_web_app/reports/screendumps/DefaultSearchResultsTest.test_infinite_scrolling_of_search_results-window 0-2018-02-23T11.59.55.html writing har log to /home/london/te/moat-effortless_web_app/reports/screendumps/DefaultSearchResultsTest.test_infinite_scrolling_of_search_results-window0- 2018-02-23T11.59.55.har.logwriting browser log to /home/london/te/moat-effortless_web_app/reports/screendumps/DefaultSearchResultsTest.test_infinite_scrol ling_of_search_results-window0-2018-02-23T11.59.55.browser.logLast URL visited was http://dev-vip04.london.mintel.ad:53066/facelift/ http requests made during test: == ERROR: test_infinite_scrolling_of_search_results (tests.functional_tests.test_search_defaults.DefaultSearchResultsTest) -- Traceback (most recent call last): File "/data/home/london/te/moat-effortless_web_app/web_app/tests/functional_tests/test_search_defaults.py", line 10, in test_infinite_scrolling_of_searc h_results homepage = HomePage.browse_to_directly(self) File "/data/home/london/te/moat-effortless_web_app/web_app/tests/functional_tests/pages/base.py", line 61, in browse_to_directly page.wait_for_page_load() File "/data/home/london/te/moat-effortless_web_app/web_app/tests/functional_tests/pages/home.py", line 248, in wait_for_page_load self.test.waitFor(_assert_page_ready) File "/data/home/london/te/moat-effortless_web_app/web_app/tests/functional_tests/base.py", line 394, in waitFor return function_with_assertion(*args) File "/data/home/london/te/moat-effortless_web_app/web_app/tests/functional_tests/pages/home.py", line 246, in _assert_page_ready 'div.home-page' File "/data/home/london/te/moat-effortless_web_app/env/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 397, in find_element_by_css_selector return self.find_element(by=By.CSS_SELECTOR, value=css_selector) File "/data/home/london/te/moat-effortless_web_app/env/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 707, in find_element {'using': by, 'value': value})['value'] File "/data/home/london/te/moat-effortless_web_app/env/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 196, in execute self.error_handler.check_response(response) File "/data/home/london/te/moat-effortless_web_app/env/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 181, in check_response raise exception_class(message, screen, stacktrace) NoSuchElementException: Message: {"errorMessage":"Unable to find element with css selector 'div.home-page'","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"104","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:38766","User-Agent":"Python-urllib/2.7"},"httpVersion":"1.1","method":"POST","post":"{\"using\": \"css selector\", \"sessionId\": \"073fdaf0-1891-11e8-aa90-778d14a3b7d7\", \"value\":
Re: Hi, a little help here.
Please reply with the full error message. Also, I am pretty sure that when pip fails to build something it also says "Full log message available in /foo/bar/quuz.log". If it does, please also send the contents of that log file. Cheers Tom On Fri, Dec 15, 2017 at 12:41 AM, Aaronwrote: > I wasn't sure where to ask this question and then I found this place. I've > got a MacBook running mac OS High Sierra. I've been trying to install > Django for a while. Whenever I try, I get an error that says "Command > "python setup.py egg_info" failed with error code 1 in > /private/var/folders/8y/lq4gsyx97_q171qrh2q18z0hgn/T/pip-build-cZ0Fno/django/" > in terminal. I'm not sure what to do. Thanks. > > -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to django-users+unsubscr...@googlegroups.com. > To post to this group, send email to django-users@googlegroups.com. > Visit this group at https://groups.google.com/group/django-users. > To view this discussion on the web visit > https://groups.google.com/d/msgid/django-users/a202cdff-dc2e-416d-9462-3b7cfe11d46b%40googlegroups.com. > For more options, visit https://groups.google.com/d/optout. -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2BV-5ff1841m3-0nShnf_ZQQ71JDG0EHjpN41F5jdz7rg%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Migrations circular dependency on upgrade to Django 1.11
After more investigating, it seems that the problem was due to the squashed migrations and the migrations they replaced both being present. After removing all migrations (from our apps) listed in "replaces" and fixing up the dependencies to not point at the old squashed migration (which I guess was the real problem?) I now get no circular dependencies (woo!) Unfortunately they still don't run, so that's the next task :( Cheers Tom On Fri, Dec 15, 2017 at 11:37 AM, Tom Evanswrote: > Hi all > > I'm updating a project from Django 1.8 to 1.11, however the migrations > which ran correctly under 1.8 now raise a CircularDependencyError for > (effortless_auth.0001_initial, app.0028_create_south_korea_data_set, > effortless_auth.0003_add_dev_group, > app.0027_create_effortless_verticals), which I'll summarise: > > effortless_auth.0001_initial > Depends: > auth.__first__, places.__first__, auth.0006_require_contenttypes_0002 > Adds: > AccountManager, DataSetType, PropValue, SpeedTestResult, > Vertical -> no FKs outside of app > GroupExtension -> (modified after creation to add fk to auth.Group) > PropDefinition -> fk to auth.Group > UserEvent -> fk to auth.User (settings.AUTH_USER_MODEL) > UserProp -> fk to auth.User (settings.AUTH_USER_MODEL) > Modifies: > GroupExtension -> add fk to auth.Group > > app.0028_create_south_korea_data_set > Depends: > effortless_auth.003_add_dev_group > Runs: > Creates DataSetType instance > > effortless_auth.0003_add_dev_group > Depends: > effortless_auth.0002_create_custom_content_group > Runs: > Creates and populates a Group and GroupExtension > > app.0027_create_effortless_verticals > Depends: > effortless_auth.003_add_dev_group > Runs: > Creates 4 Vertical instances > > I do not see what is circular from this, the graph should surely be: > auth.__first__ > auth > auth.0006 > effortless_auth.0001 > .. > effortless_auth.0003 > ... > app.0027 > app.0028 > > Why does this now confuse Django? I have a feeling this is due to > swappable models for auth (which we do not use, this project was > started with AUTH_USER_MODEL unset, but another project which re-uses > some of our libraries does do). > > I can share more of the migrations, there is some additional > complexity I have skipped over because effortless_auth used to be part > of "app" and 'app' has had migrations squashed in the past, so many of > these migrations have "replaces" attributes also. > > Cheers > > Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2BU34k20OdtXHjQfzziXOBKVy5%2Beg0m0jrR8twmHJXknw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Migrations circular dependency on upgrade to Django 1.11
Hi all I'm updating a project from Django 1.8 to 1.11, however the migrations which ran correctly under 1.8 now raise a CircularDependencyError for (effortless_auth.0001_initial, app.0028_create_south_korea_data_set, effortless_auth.0003_add_dev_group, app.0027_create_effortless_verticals), which I'll summarise: effortless_auth.0001_initial Depends: auth.__first__, places.__first__, auth.0006_require_contenttypes_0002 Adds: AccountManager, DataSetType, PropValue, SpeedTestResult, Vertical -> no FKs outside of app GroupExtension -> (modified after creation to add fk to auth.Group) PropDefinition -> fk to auth.Group UserEvent -> fk to auth.User (settings.AUTH_USER_MODEL) UserProp -> fk to auth.User (settings.AUTH_USER_MODEL) Modifies: GroupExtension -> add fk to auth.Group app.0028_create_south_korea_data_set Depends: effortless_auth.003_add_dev_group Runs: Creates DataSetType instance effortless_auth.0003_add_dev_group Depends: effortless_auth.0002_create_custom_content_group Runs: Creates and populates a Group and GroupExtension app.0027_create_effortless_verticals Depends: effortless_auth.003_add_dev_group Runs: Creates 4 Vertical instances I do not see what is circular from this, the graph should surely be: auth.__first__ auth auth.0006 effortless_auth.0001 .. effortless_auth.0003 ... app.0027 app.0028 Why does this now confuse Django? I have a feeling this is due to swappable models for auth (which we do not use, this project was started with AUTH_USER_MODEL unset, but another project which re-uses some of our libraries does do). I can share more of the migrations, there is some additional complexity I have skipped over because effortless_auth used to be part of "app" and 'app' has had migrations squashed in the past, so many of these migrations have "replaces" attributes also. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1JaB8fkex6VswPc_jVf6MNHaggU1%2B0o%2Bxs6tQT9Lo5ABQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Remove/undo a multi table inheritance
Does it work if you do it in several stages (each one is a separate migration action): * Add the OneToOneField, make it nullable, still using MTI * Add a python migration that populates it from the existing MTI information * Remove the MTI * Make the 1-2-1 field as you like it (remove null=True etc) Of course, this won't get rid of MTI, as MTI is simply a normalized way of specifying that other models have a one to one correspondence with a base model - if you express this as model inheritance, or if you express it as an explicit 1-2-1 with a base model makes no difference to the underlying structure of the tables, and hence any performance characteristics will not change, so why bother? Cheers Tom On Thu, Nov 2, 2017 at 9:11 AM,wrote: > Hi, > > I have introduced a multi table inheritance in the past. Now I am trying to > remove it again by adding an explicit one-to-one relation from the child > table to the parent. So my starting point is: > > from django.db import models > > class Place(models.Model): > name = models.CharField(max_length=50) > address = models.CharField(max_length=80) > > class Restaurant(Place): > serves_hot_dogs = models.BooleanField(default=False) > serves_pizza = models.BooleanField(default=False) > > > And I want to end up with something similar to this: > > > from django.db import models > > class Place(models.Model): > name = models.CharField(max_length=50) > address = models.CharField(max_length=80) > > class Restaurant(models.Model): > place_ptr = models.OneToOneField(Place) > serves_hot_dogs = models.BooleanField(default=False) > serves_pizza = models.BooleanField(default=False) > > When running make migrations it will prompt me for an initial value for the > newly introduced `id` field, which I don't know howto provide. > > > I attempt the following fixes: > > >- introducing an Integer field, copy data from the implicit OneToOneField > and making both explicit while switiching the primary_key at the same time > (fails in sqlite with NOT NULL constraint and primary key issues on > postgres) > >- writing a SplitDatabaseAndState migration where in the State part the > model is deleted and recreated, while in the database part the shema editor > is used to alter the fields as needed, that didn't work either > > > So there are two questions that come to my mind: > > > 1. What is the proper way to undo a multi table inheritance? > > 2. Is there even an official way to change the primary key of a model in > Django, that does work without SQL migrations? > > > -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to django-users+unsubscr...@googlegroups.com. > To post to this group, send email to django-users@googlegroups.com. > Visit this group at https://groups.google.com/group/django-users. > To view this discussion on the web visit > https://groups.google.com/d/msgid/django-users/ff8be877-1eb8-419b-b456-89d20e9c09d8%40googlegroups.com. > For more options, visit https://groups.google.com/d/optout. -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1L2O%2Bw%3DGzvG1Y8zsFWqFTsEaPQDFPHiHSjK_MJN4MhgJA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Bizarre URL behaviour after deploying
On Thu, Aug 31, 2017 at 2:09 AM, Bernd Wechnerwrote: > Daniel, > > Yes, I have deployed, that is the problem in a sense. URLs are clean in dev > and suddenly contain an app_name when deployed. > > Not sure what you mean by configuration? The Django settings are here: > > https://github.com/bernd-wechner/CoGs/blob/master/CoGs/settings.py > > The rest of the config is uwsgi under lighttpd, but none of that is likely > to impact the appearance of an app_name in my URLs all of a sudden. I don't > mind sharing the config files, but it's a distraction I fear. I think you will be surprised. I'm surprised your diagnosis doesn't point you at this straight away, if the URLs are correct on one site but incorrect on another site, and both sites run the exact same python/django code, then the error is certainly in the bits that are different. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1Lo6RNeWiVJutdL9%2BKNdRmXKNsRO-9nAOcn9vs2xq1%2BMQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: A lot of Problems with Migrating (conceptual)
On Tue, Aug 22, 2017 at 8:37 PM, Alexander Josephwrote: > Thanks for all the advice. > > One more question - could project structure be causing issues with > migrations? I'm working on a large project and many apps in my project have > several layers of "sub-apps". My structure looks something like this... This approach seems appealing, but personally I think it is a bad idea because the ease of introducing dependencies between apps is extremely high. Even when the apps are all tightly related to a particular project (to the extent their package name is "fooproject-some-function"), I think its better to simply develop each one as a standalone app, separate from the other apps and not requiring the other apps in order to test/develop. With this approach, you will not get unnecessarily thin apps simply because you cannot easily couple two apps together, and everything within the app should have high cohesion. Remember (or discover :) that in software engineering, high quality code is loosely coupled (it doesn't depend on many external things) and highly cohesive (the things within the module are related to each other). I would also avoid the use of subapps. First off, Django only uses the final part of the dotted import path as the app name - 'engineering.products.product1' has the same name as 'accounting.invoices.product1' (I know that doesn't exist, but...). I have a (unsubstantiated) theory that your migration woes are down to subapps. Long model files are not good, but I'd also disagree with 2SoD that getting to 5 models means a new app because of long files - what ridiculousness! If your model file is getting long, replace it with a model directory, each model in a separate module, and all of them imported in the __init__. You should split your app when it is no longer cohesive (or more accurately, when the level of cohesion is upsetting and/or slows development). 2SoD is good, but its not a holy text! Cheers Tom PS Make sure you have a sensible workflow for migrations - I'm assuming you are using some sort of version control. While you are developing your changes, you might generate a lot of temporary migrations. You do not want to apply these migrations to live, so you should squash them - either manually, using squashmigrations or by migrating the DB back to before they existed, remove them and recreate them. If you do the last one, remember to preserve any custom logic you have placed in the migration. At the end of the day, the migrations you commit are what will run on your production database, so you should ensure they do exactly what you are expecting them to do and are running in the correct order. Particularly if you have a lot of small apps, getting the dependencies right is essential. -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1J-Oxam2oHB37ap3rY5Sio2%2BR0WGMKKpmPtT-5JMaGDHA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: TypeError: __init__() takes 2 positional arguments but 3 were given (django-material)
Your error refers to part of a class you haven't included, ClientsForm, and it has an error to do with a class called Stacked, which you haven't shown where it is imported from. Hard to diagnose further.. Cheers Tom On Thu, Jul 27, 2017 at 1:02 AM, Elias Coutinhowrote: > Traceback (most recent call last): > File > "/home/eliaspai/danibraz/.danibraz/lib/python3.5/site-packages/django/utils/autoreload.py", > line 226, in wrapper > fn(*args, **kwargs) > File > "/home/eliaspai/danibraz/.danibraz/lib/python3.5/site-packages/django/core/management/commands/runserver.py", > line 121, in inner_run > self.check(display_num_errors=True) > File > "/home/eliaspai/danibraz/.danibraz/lib/python3.5/site-packages/django/core/management/base.py", > line 374, in check > include_deployment_checks=include_deployment_checks, > File > "/home/eliaspai/danibraz/.danibraz/lib/python3.5/site-packages/django/core/management/base.py", > line 361, in _run_checks > return checks.run_checks(**kwargs) > File > "/home/eliaspai/danibraz/.danibraz/lib/python3.5/site-packages/django/core/checks/registry.py", > line 81, in run_checks > new_errors = check(app_configs=app_configs) > File > "/home/eliaspai/danibraz/.danibraz/lib/python3.5/site-packages/django/core/checks/urls.py", > line 14, in check_url_config > return check_resolver(resolver) > File > "/home/eliaspai/danibraz/.danibraz/lib/python3.5/site-packages/django/core/checks/urls.py", > line 24, in check_resolver > for pattern in resolver.url_patterns: > File > "/home/eliaspai/danibraz/.danibraz/lib/python3.5/site-packages/django/utils/functional.py", > line 35, in __get__ > res = instance.__dict__[self.name] = self.func(instance) > File > "/home/eliaspai/danibraz/.danibraz/lib/python3.5/site-packages/django/urls/resolvers.py", > line 313, in url_patterns > patterns = getattr(self.urlconf_module, "urlpatterns", > self.urlconf_module) > File > "/home/eliaspai/danibraz/.danibraz/lib/python3.5/site-packages/django/utils/functional.py", > line 35, in __get__ > res = instance.__dict__[self.name] = self.func(instance) > File > "/home/eliaspai/danibraz/.danibraz/lib/python3.5/site-packages/django/urls/resolvers.py", > line 306, in urlconf_module > return import_module(self.urlconf_name) > File > "/home/eliaspai/.pyenv/versions/3.5.0/lib/python3.5/importlib/__init__.py", > line 126, in import_module > return _bootstrap._gcd_import(name[level:], package, level) > File "", line 986, in _gcd_import > File "", line 969, in _find_and_load > File "", line 958, in _find_and_load_unlocked > File "", line 673, in _load_unlocked > File "", line 662, in exec_module > File "", line 222, in > _call_with_frames_removed > File "/home/eliaspai/dani/config/urls.py", line 20, in > url(r'^cadastro/', include('danibraz.persons.urls', > namespace='persons')), > File > "/home/eliaspai/danibraz/.danibraz/lib/python3.5/site-packages/django/conf/urls/__init__.py", > line 50, in include > urlconf_module = import_module(urlconf_module) > File > "/home/eliaspai/.pyenv/versions/3.5.0/lib/python3.5/importlib/__init__.py", > line 126, in import_module > return _bootstrap._gcd_import(name[level:], package, level) > File "", line 986, in _gcd_import > File "", line 969, in _find_and_load > File "", line 958, in _find_and_load_unlocked > File "", line 673, in _load_unlocked > File "", line 662, in exec_module > File "", line 222, in > _call_with_frames_removed > File "/home/eliaspai/dani/danibraz/persons/urls.py", line 5, in > from danibraz.persons.views import clients, employees > File "/home/eliaspai/dani/danibraz/persons/views.py", line 6, in > from danibraz.persons.forms import ClientsForm, EmployeeForm > File "/home/eliaspai/dani/danibraz/persons/forms.py", line 31, in > class ClientsForm(Form): > File "/home/eliaspai/dani/danibraz/persons/forms.py", line 52, in > ClientsForm > Stacked(1, 'addresses'), > TypeError: __init__() takes 1 positional argument but 3 were given > > > > > Em terça-feira, 25 de julho de 2017 18:16:20 UTC-3, Tim Graham escreveu: >> >> Please give the exception traceback. >> >> On Tuesday, July 25, 2017 at 3:35:41 PM UTC-4, Elias Coutinho wrote: >>> >>> Hello guys! >>> >>> I'm trying to recreate a form with Inline using django and django-stuff. >>> I already got it once, but this is not being easy! >>> >>> I want to create a form that can register a Client and its addresses, or >>> something similar to this link here. >>> >>> Example 1: Adding contacts. >>> >>> Example 2: Adding addresses. >>> >>> I'm trying like this: >>> >>> Forms.py >>> >>> from django import forms >>> from material import Layout, Row, Fieldset >>> from .models import Client >>> >>> >>> class Address(forms.Form):# TA FEITO >>> public_place = forms.CharField(label='Logradouro') >>> number = forms.CharField(label='Número') >>> city =
Re: serving over either 80 or 443
On Wed, Jul 19, 2017 at 9:55 PM, Larry Martellwrote: > This is probably not strictly a Django question, but I'm hoping > someone here has had to solve this before. > > We have a django app that is sometimes deployed in an environment with > SSL and talks over port 443, and other times is deployed in a non-SSL > environment and talks over port 80. In our templates we serve CSS and > JS files with this: href="https://0.0.0.0:443/...; When running over > port 80 that does not work. Is there a way to tell in the template if > we are using port 80 or 443 and adjust the href accordingly? > For links within the same site, use relative URLs. For resources on other sites, use protocol relative URLs, like: //www.foo.com/foo/bar The resource will be loaded using whatever protocol the page requesting it was loaded with. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1K%2BaQvuok00OGfa5duMK1UGLvXR_us0AfP5joEgUm%3Dvdw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: How to get extra data in clean_data?
On Tue, Jul 18, 2017 at 2:13 PM, 李余通wrote: > Thank you very much!you are right > I solve the problem: > [...] > And last,I want konw how to send a web pag (can auto jumps Specific > location) to others,such as you url > "https://github.com/django/django/blob/master/django/contrib/auth/forms.py#L64; Perhaps reading some simple documentation about HTML might be more assistance than asking several thousand people to do it for you? Anyway - Anchors: http://html.com/anchors-links/ Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1JCsj92ugNQNc-%2BdzcnyM1JdhiC7kiAOw4OwROHd-mUBA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: How to get extra data in clean_data?
As described in the docs on form and field validation, if you want to validate one field using another field, you do so in the clean() method: https://docs.djangoproject.com/en/1.8/ref/forms/validation/ and in detail https://docs.djangoproject.com/en/1.8/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other Cheers Tom On Tue, Jul 18, 2017 at 10:19 AM, 李余通wrote: > My mind is here: > > class Register(forms.Form): > passwd = > forms.CharField(max_length=20,label='密码',widget=forms.PasswordInput) > repasswd = > forms.CharField(max_length=20,label='重复密码',widget=forms.PasswordInput) > > def clean_passwd(self): > passwd = self.cleaned_data['passwd'] > repasswd = self.cleaned_data['repasswd'] #here is error > > if passwd != repasswd: > raise forms.ValidationError('两次密码不一致') > return passwd > > So,problems is i want to check passwd and repasswd same,How to solve? > > -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to django-users+unsubscr...@googlegroups.com. > To post to this group, send email to django-users@googlegroups.com. > Visit this group at https://groups.google.com/group/django-users. > To view this discussion on the web visit > https://groups.google.com/d/msgid/django-users/ab8a7050-37c8-4547-9b86-5bd16821ede9%40googlegroups.com. > For more options, visit https://groups.google.com/d/optout. -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1LbDR7QxRsGZB6dC6doYPONvURcANrVxfUT_r%3DtT4h_9w%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: How to create a fixed-length binary field with a unique constraint?
On Tue, Jul 11, 2017 at 12:05 AM, Mike Morriswrote: > From your description (save a SHA-256 checksum), you do not need a binary > field. Binaries are always of indeterminant length; they can hold photos, > executables, sound files, etc. > > By definition, a SHA -256 is 256 bytes of ASCII. > > You probably want a CharField(length=256). > BinaryField is arbitrary size, binaries are not. The binary representation of a SHA-256 is significantly smaller (it's 256 *bits*, or 32 bytes), hence why the OP wants to store his binary objects in the most efficient format possible, not 2 or 8 times that size. Its like storing an IPv4 address as the 15 bytes string "10.123.132.254" or the 4 byte integer 175867134. Guido: You can make your own custom database types quite simply (completely untested): class FixedSizedBinaryField(models.BinaryField): def __init__(self, num_bytes=None, *args, **kwargs): self.nbytes = num_bytes super(FixedSizedBinaryField, self).__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super(FixedSizedBinaryField, self).deconstruct() kwargs[''num_bytes'] = self.nbytes return name, path, args, kwargs def db_type(self, connection): return "binary(%d)" % self.nbytes For more details, check out the docs on custom fields: https://docs.djangoproject.com/en/1.11/howto/custom-model-fields/ Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1Jv9YriAoqwh9GUku_6yojLpt7AV_U8ujVusQcG1EAiKA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: django implementation group by every two hours,
On Tue, Jul 11, 2017 at 10:22 AM, kanhaiya yadavwrote: > Hi, > > I have a model > class XyzModel (models.Model): >name = models.CharField(max_length=NAME_LENGTH) >unique_id = models.CharField(max_length=NAME_LENGTH) >info = models.CharField(max_length=NAME_LENGTH, blank=True) >violation_time = models.DateTimeField() > > > > > I have many rows in the database. So I want to group by the results for > every two hours or for every four hours. > I want the result something like > > name violation_date > interval counts > abc 2017-07-01 > 06:00 - 08:00 20 > xyz 2017-07-01 > 08:00 - 10:00 30 > > My query is > XyzModel.objects > .extra({"day": "date_trunc('hour',violation_time)"} > .values("day") > .order_by("day") > .annotate(count=Count("id")) > But using this query I can only group the result by one hour interval. I > want to group by more than one hour interval. You realise your "day" parameter is actually hours, right? .extra({'day', 'TRUNC(EXTRACT(hour FROM violation_time) / 2)'}) 'day' will then be the 0-based index of the 2 hour periods, starting from midnight, so a value of 5 would mean 10 AM - 12 AM. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1KQBaTFkwV6Ar%3DfK9RM-vU-8GB_C6MsaPrLwQSko6Yv3Q%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: save cropped image with PIL to database
On Mon, Jul 3, 2017 at 11:09 AM, shahab emamiwrote: > hello > > i have a question and i cant find answer with search. > > i want to save cropped image in database then : > this is my model: > > class Photo(models.Model): > file= models.ImageField(upload_to='%Y/%m/%d', > blank=True,null=True) > > > i have a form then user can select image and send to view like this: > > > {% csrf_token %} > > > > > > > > > and in the view i have this : > > from PIL import Image > > > def save_photo(request): > > _photo, created = models.Photo.objects.get_or_create(pk=1) > > if request.method == 'POST': > photo = request.FILES.get('file') This is a django.core.files.File (or subclass) object. It is file-like and can be treated as a file. > > image = Image.open(photo) > > cropped_image = image.crop((100, 100, 200, 200)) > resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) resized_image is a pil.Image. Again, it is file-like, but it is not a django.core.files.File... > _photo.file = resized_image > _photo.save() so this doesn't work. You will need to wrap the PIL.Image file-like object with the django File class (remember appropriate imports): _photo.file = File(resized_image) _photo.save() Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2BTeg-joCvt%3DosHTThpzduQ0_ZYr%2BKvMfbD%3DJJPHZ2gcw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Vim plugin that does Django code completion?
Hi Robert Ignore the helpful people telling you to stop using vim and use some god awful UI, the plugin you are looking for is called jedi.vim https://github.com/davidhalter/jedi-vim Debian has a package, vim-python-jedi, or you can install using Pathogen or Vundle. Cheers Tom On Fri, Jul 7, 2017 at 4:27 PM, Robert F.wrote: > Is there a Vim plugin that does code completion for Django? I'd like to be > able to type something like "foobar = models." and hit Tab and see a list of > classes like CharField or Foreign key. Alternately, I'd be OK with entering > an abbreviation that would bring up the proper code snippet. The Django > documentation suggests YouCompleteMe but it appears to only handle Python > code, not Django specifically. Also, I haven't been able to get it to work > on my Mac laptop. > > I almost exclusively do editing of Django files on a remote Debian server > from my Mac laptop. I know PyCharm provides the ability to edit remote > files and it has Vim emulation but it's pretty expensive and I'm not sure > how closely the emulator emulates Vim. SublimeText appears to have a > "Djaneiro" package that does what I need but it looks like editing remote > files is rather difficult with Sublime. Doesn't Vim have better support for > Django code completion that's comparable to these two applications? > > -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to django-users+unsubscr...@googlegroups.com. > To post to this group, send email to django-users@googlegroups.com. > Visit this group at https://groups.google.com/group/django-users. > To view this discussion on the web visit > https://groups.google.com/d/msgid/django-users/166226ca-2fc6-4454-9baf-0d871c552a8f%40googlegroups.com. > For more options, visit https://groups.google.com/d/optout. -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1LySk_S4BBrTOho8mWD6AcJM8JO231%2B25rmnZOBjS0YWA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: value of checkbox aren't saved in the form
Your checkbox fields on the form are "market" and "sector", but your "Parameters" model doesn't have fields with those names, and you aren't doing anything with the values from the form in your save() method. Where were you expecting those checkboxes to be saved? Cheers Tom On Wed, May 31, 2017 at 1:15 PM,wrote: > i am a beginner with Django. I don''t know what the problem with the value > of checkbox. When i enter to the saved form the value of checkbox aren't > save.The image is here . Please I need your help, I loose too much time on > this. > > This is my forms.py: > > class BacktestForm(forms.ModelForm): > > period_start = forms.DateField(initial=datetime.datetime.today().date() - > datetime.timedelta(days=365+16), > widget=forms.widgets.DateInput(format="%Y/%m/%d"), > input_formats=["%Y/%m/%d"]) > period_end = forms.DateField(initial=datetime.datetime.today().date() - > datetime.timedelta(days=16), > widget=forms.widgets.DateInput(format="%Y/%m/%d"), > input_formats=["%Y/%m/%d"]) > > market = > forms.MultipleChoiceField(required=False,widget=CheckboxSelectMultiple, > choices=MARKET_CHOICES) > sector = > forms.MultipleChoiceField(required=False,widget=CheckboxSelectMultiple, > choices= MEDIA_CHOICES) > class Meta: > model = Parameters > > This is my models.py: > > class Parameters(models.Model): > > user = models.ForeignKey(User) > title = models.CharField('title', max_length=100, default='', blank=True, > help_text='Use an indicative name, related to the chosen parameters') > type = models.CharField('forecast type', choices=FORECAST_TYPES, > max_length=20, default="backtest") > > #input characteristics > price_1_min = models.FloatField('1. Price, min', default=0.1, > validators=[MinValueValidator(0.1), MaxValueValidator(2)]) > > def get_backtest_url(self): > return reverse('saved_backtest', kwargs={'pk': self.pk}) > > > The save function in views.py: > > > if request.method == 'POST': > if form.is_valid(): > if 'save' in request.POST: > obj = form.save(commit= False) > obj.user = request.user > obj.type = "backtest" > obj.save() > messages.info(request, 'Saved!') > return redirect(obj.get_backtest_url()) > > > The template for the saved form is : > > {% if user.is_authenticated %} > {% if user.profile.is_active %} > Saved from "Backtesting" > > {% for param in user.parameters_set.all %} > {% if param.type == "backtest" %} > style="width:100%"> > > Saved File > > Created at > > > > > href='{{param.get_backtest_url}}'>{{param.title}} >{{param.created_at}} > > > > {% endif %} > {% endfor %} > > > -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to django-users+unsubscr...@googlegroups.com. > To post to this group, send email to django-users@googlegroups.com. > Visit this group at https://groups.google.com/group/django-users. > To view this discussion on the web visit > https://groups.google.com/d/msgid/django-users/55e259b4-8986-41d0-849e-4fe809001ff0%40googlegroups.com. > For more options, visit https://groups.google.com/d/optout. -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1KXUD5%3DZRT%2Bu4k3EBLnzC%3D5MLt6LCPO-UX%2BWJrLrAT5wQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: How to fix "plural forms expression could be dangerous"
You need to change INTEGER and EXPRESSION for the correct values. I believe for zh you want "nplurals=1; plural=0;" Cheers Tom On Thu, May 18, 2017 at 7:41 AM, Martin Brochhauswrote: > Hi everyone, > > in my project, I am generating my .po files like this: > > python manage.py makemessages --ignore=node_modules/* --ignore=*migrations/* > --ignore=*tests/* --ignore=__init__.py --ignore=submodules/* > --ignore=fabfile* -l zh_CN > > Usually this results in the following line being added to my `django.po` > file: > > "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n" > > When this line is in the file and when I switch the language to Chinese, I > will get this error: > > ValueError at /zh-cn/ > plural forms expression could be dangerous > > When I delete that line and run `./manage.py compilemessages`, everything > seems to work fine, but this is obviously can't be a good solution and would > mess up my deployment workflow quite a bit. > > So my question is: Why does this line pop up in my .po file? What if I > change that expression to something valid, would it be overwritten with that > same faulty expression again when I run makemessages? What would a correct > expression look like for Chinese? > > Best regards, > Martin > > -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to django-users+unsubscr...@googlegroups.com. > To post to this group, send email to django-users@googlegroups.com. > Visit this group at https://groups.google.com/group/django-users. > To view this discussion on the web visit > https://groups.google.com/d/msgid/django-users/5db9fbc1-9f59-4947-a214-0af82c8c4458%40googlegroups.com. > For more options, visit https://groups.google.com/d/optout. -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1K1tFqLUozgn%3DjZxdFF18WDJGYB2-rxra_-m2%2BvxKj3gw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Django Deployment showing list of directory
On Mon, May 8, 2017 at 11:08 AM, sarfaraz ahmedwrote: > Hello Guys, > [ .. ] > This is conf file for Apache > -- > > ServerAdmin ad...@testarhamcollections.com > DocumentRoot "C:/Apache24/htdocs/testarhamcollections" > ServerName www.testarhamcollections.com > ServerAlias testarhamcollections.com > ErrorLog > "C:/Apache24/htdocs/testarhamcollections/logs/testarhamcollections.com-error.log" > CustomLog > "C:/Apache24/htdocs/testarhamcollections/logs/testarhamcollections.com-access.log" > common > > WSGIScriptAlias / > "c:/Apache24/htdocs/testarhamcollections/project1/wsgi.py" > > Alias / "c:/Apache24/htdocs/testarhamcollections" > Alias /static/ "c:/Apache24/htdocs/testarhamcollections/static/" > Alias /media/ "c:/Apache24/htdocs/testarhamcollections/static/media/" DANGER! Python/WSGI is not like PHP, the program files should not live in web accessible directory. Your WSGI script should not be in a web accessible directory. The only things that should be in a web accessible directory are your static htdocs, which are collected to that location by Django using the command "collectstatic". Your project files should be OUTSIDE the document root and NOT aliased into it in any way! A typical layout should look like so: c:/DjangoProjects/project_name ├── htdocs ├── logs ├── my_project │ ├── manage.py │ ├── my_app1 │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ └── views.py │ ├── my_app2 │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ └── views.py │ └── my_project │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── my_virtual_env The only directory of those that should be web accessible is htdocs, and none of your code should live there. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1JoAHqgWnyxeNMn1EwqaMnvf8fsahT8JW0nK2A9%2BYRoOQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Unicode error in __unicode__(self) function
What data is "Jón"? Is it u'J\xf3n' or something else? (print repr(self.fname)) Cheers Tom On Mon, May 8, 2017 at 5:10 PM, rmschnewrote: > I have a Django setup that has worked for a very long time. Yesterday I > upgraded from Django 1.10 to 1.11.1 and am getting the error: > > raise DjangoUnicodeDecodeError(s, *e.args) > django.utils.encoding.DjangoUnicodeDecodeErrorJón > : 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in > range(128). You passed in ( 'soc_util.models.Meetingattendee'>) > > when in the code simply printing the "Meetingattendee" object with > > def __unicode__(self): > print self.fname > return self.fname > > The above is a simplified version. The error first cropped up on the more > complex version > > def __unicode__(self): > s=u'%s: %s, %s %s, %-12s, %s %s, %s, INV:%s, PO:%s, ItemCode:%s' % > (self.id,self.meeting.date.strftime("%d-%b-%Y"),self.table,self.seat,\ > self.attendeestatus.status,self.fname, self.lname, > self.affiliation, \ > self.invoiceno,self.ponumber,self.itemcode) > return s > > where I eventually determined that the code was not working when working the > field self.fname. > > self.fname fails when it is "Jón". Works fin with "Jon", of course. > > I have not tried to revert back to Django 1.10, but i guess that's the next > step unless there is something in Django 1.11.1 that was changed that > affects this. I can't find anything mentioned in the release notes. > > -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to django-users+unsubscr...@googlegroups.com. > To post to this group, send email to django-users@googlegroups.com. > Visit this group at https://groups.google.com/group/django-users. > To view this discussion on the web visit > https://groups.google.com/d/msgid/django-users/4d37cc78-7fe9-41b6-bcba-eb788465e54f%40googlegroups.com. > For more options, visit https://groups.google.com/d/optout. -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1Lw_gfZANGr95XFM2RSoRVemtnv3YSvC3zK1FTgbnSiGg%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Django and Nginx through uwsgi is not working
On Thu, Mar 16, 2017 at 12:25 PM, valerio orfanowrote: > Hi All > > i ve created a django application not using virtual environment. I ve > installed nginx and trying to integrate them via uwsgi application. > Here my configurations files. > > [uwsgi] > chdir = /home/elastic/workspace/ES_Brevetti > wsgi-file = ES_Brevetti/wsgi.py > master = true > processes = 5 > uid = nginx > gid = nginx > socket = unix:///socket/uwsgi.sock > chmod-socket = 666 > vacuum = true > > i've created the file /sockect/uwsgi.sock with permission 777 > > chown nginx:nginx -R /sockect/uwsgi.sock When you say you've "created the file /socket/uwsgi.sock", what have you actually done? You should have made a directory that uwsgi will be able to create a unix socket in. You should not create a regular file, or even a named fifo, with the same name as the socket, otherwise uwsgi will be unable to create the socket. Typically people do this by placing their socket files in /tmp or /var/tmp, a world writeable sticky directory. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1JbngRuEkjj_DvZQBinGtFi%3DKaJqN17qeMuQpxZH%3D1XDA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Initial data, tests and migrations
On Wed, Feb 22, 2017 at 2:40 PM, Tim Grahamwrote: > I'm curious if you feel that running django_otp's tests as part of your > project's tests is adding value. I'm curious whether you think I commonly spend my time doing things that I don't think add value... django_otp is simply an example of this issue, but yes, running those tests would give my project value. These tests exercise parts of django_otp that interact with parts of my code. Successful tests indicate that those two parts interoperate correctly. The tests are successful when run individually, but fail when run as a suite because data loaded as part of a migration is flushed away before the second test. -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2BHB_R6dY3LzEXVp_cu9G%3D%2Bo_KcX224hSG1PGNSqd5sFQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Initial data, tests and migrations
On Wed, Feb 22, 2017 at 2:41 PM, Adam Stein <a...@csh.rit.edu> wrote: > On Wed, 2017-02-22 at 14:22 +0000, 'Tom Evans' via Django users wrote: > > The URL you refer to mentions about loading data for apps. Doesn't mention > anything in regards to tests. Why are fixtures bad for tests? In fact, right > above the "Providing initial data with migrations" section is a "See also" > box that says "Fixtures are also used by the testing framework to help set > up a consistent test environment". It would seem to me that the docs are > telling you to use fixtures for tests and use migrations for real data. OK. How do I load that data from a fixture in a TestCase I cannot modify? Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1KsEwKmJzWgYxxFJRU8XiHBAY7u0djah6brLxjKU6yYNg%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Initial data, tests and migrations
On Wed, Feb 22, 2017 at 12:47 AM, Melvyn Sopacua <m.r.sopa...@gmail.com> wrote: > On Tuesday 21 February 2017 19:00:42 'Tom Evans' via Django users wrote: > > > >> Previously, these instances were loaded from a JSON fixtures file, > > > > And you can still do that. > > > >> which used to be the recommended way. For our own tests, we simply > >> load these fixtures in the setUp portion of the test; obviously we > >> can't go around modifying tests in third party libraries. > >> I tried taking them out of the fixtures, and adding them instead in a > >> data migration, but this also had the same effect - the instances were > >> there for the first test ran, and then missing for all the subsequent > >> ones. > > > > setUp is run between test methods of a test case. setupTestData is a class > method on the testcase run once per test case. > >> > >> > >> What is the "correct" way of ensuring that these instances exist in > >> the test database before any test is run? > > > > All explained in the docs. > > Either redeclare the same fixtures for different test cases or reorganize > your testcases to share the same fixture(s). > I think you have misunderstood: 1) The test cases belong to a library and cannot be modified 2) The initial data is populated from a data migration and not from a fixture, as that is not recommended [1] Data is placed in to the test database using migrations, but after the first test has been run the data is flushed out again, causing the second test to fail. I would like the all the tests to pass: * I don't want to put the same data into fixtures as well as migrations (DRY) * I don't want to modify the 3rd party library. How? Cheers Tom [1] https://docs.djangoproject.com/en/1.10/howto/initial-data/#providing-initial-data-with-migrations -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2B9n%3DwvT7UVycDWr5vttHwgVeUJAD8BivNutXx9tf3d6A%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Initial data, tests and migrations
Hi all I'm having some difficulty working out how I am supposed to provide initial data for testing purposes, particularly when the initial data is not immediately pertinent to the test. For instance, our project uses django_otp, which has some simple tests. However, these tests create user objects, which then calls in to other parts of the project code. This code adds users to various auth.Group, depending upon the user attributes. This code fails after the first test has been run, because all the auth.Group model instances are flushed from the database. Previously, these instances were loaded from a JSON fixtures file, which used to be the recommended way. For our own tests, we simply load these fixtures in the setUp portion of the test; obviously we can't go around modifying tests in third party libraries. I tried taking them out of the fixtures, and adding them instead in a data migration, but this also had the same effect - the instances were there for the first test ran, and then missing for all the subsequent ones. What is the "correct" way of ensuring that these instances exist in the test database before any test is run? How can I stop them getting wiped out after any test has run? Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1JKCugKaijhD6_wX-M-2nN04eTqDuFG08%3D%2BtUNBW3o5hA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Django and timezones ... how to initialize a field to now() in the in clients time zone?
On Sat, Jan 21, 2017 at 9:40 AM, Bernd Wechnerwrote: > I have a model with this field: > > date_time = models.DateTimeField(default=timezone.now) > > if I look at the generic create form, it inializes the date_time field with > now in UTC, not in local time. > > Now I appreciate there are two things at play here: > > the desired UX is to see now in my time zone. > Django, running on the server has no idea what my time zone is. > > Now I can think my way through this and find some solutions, not short of > imagination here. But as I work on nutting one out, I am struck, as ever, > with the notion that 1. is surely a ubiquitous use case ... namely I cannot > seriously be the first person to have this desire or tackle this problem and > is there not a stock standard approach in Django to doing this? > > As I read it I can find the time zone in Javascript at the client side: > > This works fine for example: > > var tz_name = jstz.determine().name(); > var tz_offset = new Date().getTimezoneOffset()/60; > > giving me pleasing results (though I appreciate, before anyone points it > out, that pleasing results are by no means guaranteed as it as it is > premised on the correct TZ configuration of the client computer among other > things, but the application in mind does not REQUIRE time accuracy (am just > logging events that happened at a given time and timezone errors are of no > practical data integrity or security concerns for a few good reasons) . > > And I can submit these in hidden fields too. > > But the obvious solution, which I find a tad kludgy alas is at the client > side in JS to find the date_time input field, and adjust it's value from UTC > to local time. Right now it's presenting as UTC. > > Even if I could find a way to ask Django to use a different timezone > (tmiezone.activate) it won't kow what Timezone until it's heard from the > client. And it's not in HTTP headers alas, though someone thinks it should > be: > > http://blogs.windwardreports.com/davidt/2010/04/can-we-please-get-a-time-zone-in-the-http-request-header.html > > On submission of course as I can submit the TZ info in hidden fields it > should be easy to convert the submission back to UTC for saving into the > database. > > Still, I wonder openly, is this not long solved, more elegantly? > > Regards, > > Bernd. > I think you're worrying about the wrong thing here. "Now" is always the same moment everywhere, it does not matter what timezone is currently active when it is recorded, only what timezone is active when it is displayed. As long as you have USE_TZ=True, all your datetimes will be stored in the database in UTC. So, the important thing is setting the appropriate current timezone. As you've discovered, you can perhaps discern the timezone using javascript. We have a snippet of javascript that determines TZ and populates a hidden field in the login form with the browser determined TZ. At login, this extra parameter is pulled out if available, and compared to the setting on the users profile. If the users profile has no current TZ setting, we update their profile with the determined settings. If the user has manually specified a timezone, we don't update it or overwrite it. Finally, we have a small piece of middleware that changes the active timezone to that indicated on the user's profile, orto the server time zone if nothing is indicated or the user is not logged in. Sadly, this isn't code I can share, but we are talking around 40 LOC total. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1JbiLgVddenqv3K_fPLXAyXe30S-Yb2%2BZoDrq%3DdOAvPgg%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: StreamingHttpResponse response length in a stats middleware
On Wed, Jan 18, 2017 at 11:42 AM, Stefano Tranquilliniwrote: > Hi there, > > I'm using the StreamingHttpResponse to stream a response, it works great. > Now, I've a middleware that measures the size of req/response that users do. > For normal HttpResponse i use len(response.content) [i know that it does not > give the bytes, but it's pretty close], for the streaming I can't, and I > can't use the streaming_content as well. > > the docs says ` Because the content can’t be accessed, many middlewares > can’t function normally.` > Thus, is there a way to get the length of the response for a > StreamingHttpResponse? > > If I would be able to know the size of the response at some point in time > (it's an iterator, so i just need to count) and i could put it in the > request object, how can I make it working with the middleware? beacuse the > process_response is fired just after the first yield, no This is for 1.8 middleware, same method can be applied to 1.10 It's not very clean, but from your middleware you can return a new response object. The new object would also be a streaming response, but for each chunk it emits (by calling the generator on the original response), it would also count the size of the chunk and store a rolling sum on the response object. After the final chunk is emitted, your logging middleware can then be called with the resulting value. Something like: class WrappedStreamingResponse(StreamingHttpResponse): def __init__(self, orig_response, middleware): self.orig_response = orig_response self.middleware = middleware self.response_length = 0 super(WrappedStreamingResponse, self).__init__(self.chunks()) def chunks(self): for chunk in self.orig_response.streaming_content: self.response_length += len(chunk) yield chunk self.middleware.log_response_size(self.orig_response, self.response_length) class MeasureMiddleware: def process_response(self, request, response): if response.streaming: return WrappedStreamingResponse(response, self) else: self.log_response_size(response, len(response.content)) def log_response_size(self, response, length): pass Cheers Tom PS: 1 big caveat for this is that if a middleware class returns a new response, middleware classes further down the chain are not called at all, so StreamingHttpResponse would not get handled by the same middleware as a regular HttpResponse. -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1JwmOqv%3D9Soj0CqWmL%3DMBPsPsfhPA-Qhh-DvtCoyZfctA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: What is the fate of closed database connections?
On Tue, Jan 17, 2017 at 7:58 PM, Fred Stlukawrote: > Mike, > > As of version 1.6, Django supports persistent DB connections > (connection pooling). Pedantry: Persistent connections are not the same as connection pooling. With persistent connections, if a worker does not have a currently open connection to the database, it will open a new one. With a connection pool, it will retrieve an unused open connection from the pool, which is shared amongst many processes. Connection pools are not built in to django, but you can use external software like pgbouncer to provide them. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2B-1W%2BvphSCFotb0gnjYmSzvFmorn4TsTSuBBNWMn9MrQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Initial data with migrations vs fixtures
Hi all We're moving a project over to the latest release (well, we're at 1.7 now, but that's the end goal anyway) and replacing South migrations with Django migrations. It looks like that fixtures are no longer thought of as the correct way of providing initial data. Is this because Run{SQL,Python} can have "reverse" instructions included, or is it some other reason? I couldn't see anything pertinent in the docs. Given that we have an existing project and fixture files, is it very bad and wrong to simply have a data migration that runs loaddata on our required fixtures? It would not be reversible, but it would be massively simpler. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1KqGdMEgHsY2WyLSS1LZHQ1k-oBfFtSQ68JZNb%2BVA_yrA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Silently continuing past an exception: is this proper? how else can I do this?
On Sun, Oct 23, 2016 at 1:39 PM, Andrew Chiwwrote: > It seems there's a problem with my code, because you're just supposed to > pass a dict to DocumentForm (or any modelForm really), not a model instance. > > I actually want to make a DocumentForm initialized with values from an > existing Document, so I can list existing Documents and provide a way to > re-upload them and edit their description. Is this the right way to do it? DocumentForm(instance=d) I can't see anywhere in the docs where this is explicitly specified as the stock ModelForm API, but it is firmly implied by this page: https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#modelform The first positional argument is expected to be data submitted by the browser. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1JQiqaEbKrkzhRN2u8NU5tFO5jWQZgaqDWcLAXAKcKaDg%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Slow first request django
On Fri, Oct 14, 2016 at 5:15 AM, Avraham Serourwrote: > I will take a wild guess here and say that this is a modwsgi problem, it > seems it will only load the django app after the first request. Indeed, see this SO post for how to tell it to load your app immediately on start up: http://stackoverflow.com/questions/1702562/speeding-up-the-first-page-load-in-django (EasyReader: Add "WSGIImportScript" directive) > > Honestly I suggest you to use nginx with uwsgi, the killer feature is that > it is not apache, I ran with so many bumps with apache that I turned to > nginx and never looked back. > > Also the config files are sane and will not drive you crazy. Apache is an excellent webserver, particularly Apache 2.4. It has the largest installed base and ecosystem of third party support and packages, and can be configured to serve both the smallest and the largest sites without any bothers. If you are already using apache and happy with it (bar this issue), you will only waste time (and perhaps get different issues) by switching to a different webserver. To not get into a vim/emacs style situation, nginx/uwsgi is also excellent; the choice of what webserver used is largely irrelevant to how real django based sites (that actually do things) will perform. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1JHudsGkBsx0f0z17S_Br3GKF_rFPAmgm_1%3DW0i-gjCmg%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: A public cloud with django backend
On Thu, Sep 15, 2016 at 8:21 AM, Rahul Doshiwrote: > Hi ,I want to setup a dropbox like server with django. So far i have > achieved uploading files onto a location .I want these files to show up on > browser which they do(while saving file to the location I indexed an entry > in the Db so i just print the file names from the DB(POSTGRESQL).Now i want > to provide users options to view or download the files.I put a link on it > and tried ,it did not work since it shows an javascript error "NOT ALLOWED > TO LOAD LOCAL RECOURCE" . All uploaded files are loaded in C drive of my > laptop. Where else do i load so that javascript can load it? Attaching my > code ..thanks in advance. For security reasons, browser do not allow internet zone sites to access local content from javascript (otherwise, any site could read any accessible file from your computer and submit it, well, anywhere). Serve the files from the webserver instead. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1LaHEEpfm_9xVx2xeVq-eJQSoevSi2eKuK2wLtj%3DwXvcA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: django 1.9, migrations SUCK
On Fri, Jul 29, 2016 at 9:19 PM, Aztrockwrote: > Excellent, thanks > > This method i use from django 1.4, never have problem. > Apart from having to restart your application server each time you added a country, sure, no problems. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2BTjwpfyOAFBY%2BBZrh_qAKCx86Y1D%2BBW821HVtYK44dCA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: pass link value in argument for view
On Wed, May 11, 2016 at 3:28 PM, quentin ladrierwrote: > sorry for the delay . I obtain this kind of error message: > NoReverseMatch at /my_views/my_arg/ . Reverse for 'xxx' with arguments > '(my_arg,)' and keyword arguments '{}' not found. 1 pattern(s) tried: > ['my_views/(?P\d+)$'] \d+ means 1 or more digits (0-9). 'my_arg' doesn't match that. Either pass a number, or change the regular expression to match the content of the argument you wish to pass. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2BJ8QX9z-%2BzebBKsA059co9DCYQeN8JkPO%2Bomp7HPnNDQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: help with django-guardian
On Thu, Mar 3, 2016 at 10:58 PM, Joshua Chanwrote: > First off, I am new to both django and python. > > I am extending an existing app. We have several admin.py files > > They all look like this: > > #!/usr/bin/env python > # coding: utf-8 > from guardian.admin import GuardedModelAdmin > from django.contrib import admin > > > from devices import models > > > class SomeModelAdmin(GuardedModelAdmin): > pass > > > admin.site.register(models.SomeModel, SomeModelAdmin) > > Everything has been working. > > I added my classes > > #!/usr/bin/env python > # coding: utf-8 > from guardian.admin import GuardedModelAdmin > > > from django.contrib import admin > from common import models > > > class MyModel1Admin(GuardedModelAdmin): > pass > > > admin.site.register(models.Model, MyModel1Admin) > > > class MyModel2Admin(GuardedModelAdmin): > pass > > > admin.site.register(models.Model2, MyModel2Admin) > > This also works fine locally, but when we deploy it, it blows up on the > import: > >> Traceback (most recent call last): >> File >> "/usr/local/share/.virtualenvs/my_app/lib/python2.7/site-packages/django/core/handlers/wsgi.py", >> line 187, in __call__ >> self.load_middleware() >> File >> "/usr/local/share/.virtualenvs/my_app/lib/python2.7/site-packages/django/core/handlers/base.py", >> line 47, in load_middleware >> mw_instance = mw_class() >> File >> "/usr/local/share/.virtualenvs/my_app/lib/python2.7/site-packages/django/middleware/locale.py", >> line 24, in __init__ >> for url_pattern in get_resolver(None).url_patterns: >> File >> "/usr/local/share/.virtualenvs/my_app/lib/python2.7/site-packages/django/core/urlresolvers.py", >> line 365, in url_patterns >> patterns = getattr(self.urlconf_module, "urlpatterns", >> self.urlconf_module) >> File >> "/usr/local/share/.virtualenvs/my_app/lib/python2.7/site-packages/django/core/urlresolvers.py", >> line 360, in urlconf_module >> self._urlconf_module = import_module(self.urlconf_name) >> File >> "/usr/local/share/.virtualenvs/my_app/lib/python2.7/site-packages/django/utils/importlib.py", >> line 40, in import_module >> __import__(name) >> File "./sites/zpanel/urls.py", line 19, in >> admin.autodiscover() >> File >> "/usr/local/share/.virtualenvs/my_app/lib/python2.7/site-packages/django/contrib/admin/__init__.py", >> line 29, in autodiscover >> import_module('%s.admin' % app) >> File >> "/usr/local/share/.virtualenvs/my_app/lib/python2.7/site-packages/django/utils/importlib.py", >> line 40, in import_module >> __import__(name) >> File "./common/admin.py", line 3, in >> from guardian.admin import GuardedModelAdmin >> ImportError: No module named admin > > > > I am running 2.7.10 locally. The failing machine is running 2.7.6. I'm not > sure how to switch my env around, but why would other admin.py files import > guardian.admin correctly? Is there a module adjacent to the failing admin.py named guardian? Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2BLPxL5kjTM9QChS-KMBPJqo9ZjGpb7x-E7mvCBwCQ9Fw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Ajax + Django + jQuery + HTML5
On Sun, Feb 28, 2016 at 9:46 PM,wrote: > > I need get path to local file in for ImageField. > Next, transfer path to my view thought Ajax request, update in database and > almost all. > > I need will make it manually, for my goals. > > May be, anyone known how it make? > > I am tried already django-ajaximage, Ajaxfileupload and many other, but it > not working correct for me. You cannot retrieve the path of the submitted file server side, it is simply not possible - browsers will not share that information with you, neither via HTTP requests, nor by poking at the DOM with javascript. If it is absolutely necessary, you must provide a second text input and have the user manually put the information in there. Bear in mind that there would be no way of verifying that what the user put in that box is at all correct. Can you explain what you are trying to do rather than what is going wrong, because I think that would be illuminating. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1L2dMrH%3DdUDuUaTN9J84Emnj0BA8woNkzbMDUgNqR75Rg%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Manually setting the session cookie
On Mon, Feb 1, 2016 at 10:13 AM, monoBOTwrote: > Hello django! > > Im creating a saas with django, due to some project requirements need to > manually change the user "on the fly" but have problems with the cookie, > since I dont know how to manually (read programatically) set it. > > Any insights or a good place to start? Thanks! > I would simply add a secondary custom auth backend that always authenticates the user if the argument switch_login is true: class SwitchAuthBackend(object): def authenticate(self, switch_login=False, new_user=None): if switch_login: return new_user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: pass Now you can switch user simply using authenticate() and login(): new_user = ... authenticated_user = authenticate(switch_login=True, new_user=new_user) login(request, authenticated_user) This would be an alternative to poking around and manually manipulating the session attributes. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1JjAzjA7rgpNLR4iQvFzqyD7M9GtYSXzYtauK4eacjhnw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: date picker
On Mon, Jan 18, 2016 at 1:03 AM, sum abiutwrote: > Hi, > i am having some trouble with my date picker. I probably missing someting, > the form fields are displaying fine, but some how the datepicker is no > displaying. probably something to do with my jquery. Please help > [ ... ] > class foregin_exchange_form(forms.ModelForm): > class Meta: > model =foreginexchange > widgets = {'Value_date': > forms.DateInput(attrs={'class':'datepicker'}),} > widgets={'Done_Date':forms.DateInput(attrs={'class':'datepicker'}),} This sets the *class* of the element to "datepicker". > [ ... ] > > $(function() { > $( "#datepicker" ).datepicker(); > }); > This turns an element with the *id* "datepicker" in to a date picker. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1LP8XWTOcwgp3ZMdGOz7XP%2B9srKFEoJ_bWRS9YFbU5Tiw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Upgrading to 1.9 - Any Easy Guide ?
On Mon, Jan 11, 2016 at 4:36 PM, Vibhu Rishiwrote: > Hi > > I work on a hobby project on and off which is based on django. After a long > gap, I picked up the work again. In the meantime, it seems that django has > been evolving faster than I have been working. I am currently on 1.6 (which > I think i had upgraded from 1.4 or 1.3 as my starting base). However, the > current new version of Django is 1.9 > > I created a new virtual environment and used pip to get the latest version > of django. > > Now I am getting a lot of errors. That is the hard way. > > Is there an easy way to upgrade django ? Or a howto for best practices ? > (Releases have version components: "1.9.1" is major release 1, minor release 9, minor-minor release 1) If you are on release 1.N, update to release 1.N+1.Y (with Y being the highest released minor-minor version), and step through its release notes dealing with all the things which have changed or been deprecated, and update them accordingly. Run your test suite to determine if anything has been broken (pro tip: tests are useful - you might want to write some if you don't already test your most common features) Then, do the next minor release until you reach the latest release. A more complete process would be to update to 1.N+1, ensure tests pass and deprecated behaviour handled, THEN subsequently to 1.N+1.Y, ensure tests pass and only then go to the next minor version. That can be a bit paranoid, as (deliberately) not much functionality or breaking changes are added in minor-minor releases of django. Release notes are here: https://docs.djangoproject.com/en/1.9/releases/ Cheers Tom PS: Best practices are not to fall that far behind! -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1LiKM3pzb1bAFTk88iLmbJKWpEaa3NTMdsVw3WJ%2BRwbdw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Update model field after a certain period
On Wed, Jan 6, 2016 at 9:39 AM,wrote: > I have a Django model with a Boolean field called New. During the model > creation it's set to True, but I want it to be updated automatically to > False after a certain period (1 month post creation for example). Can I use > signals here? Another option is to replace the field with a "created" date time, and add a computed property called "new" that tests to see whether it is old or not. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2B8AJYJbeq9Z4VgBH%3DQcLTY17dhJg6gCfVRDfVnaf9evg%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Django Model | Relationship question. Student->School Class
On Tue, Dec 22, 2015 at 6:50 AM, Pembywrote: > With this code for example. > > class Students(models.Model): > first_name = models.CharField(max_length=30) > last_name = models.CharField(max_length=30) > classChoice1 = ? > classChoice2 = ? > classChouce3 = ? > > class Class(models.Model): > class_name = models.CharField(max_length=30) > class_discription = models.CharField(max_length=30) > > > Say for example I have Nth students, S1 S2 S3 ... and Nth classes (as in > college class) C1 C2 C3 ... > And I want to create a relationship where each student can only be assigned > to one class uniquely for each classChoice > selected. How would I create that relationship? Remove the classChoiceN fields from Students, and add a ManyToMany between Student and Class (remember model class names should be singular, so "Student", not "Students") using a through table with an additional "choice" integer field. The "choice" field should have a maximum value of 3, and you will want unique_together constraints on the through table for (student, class) and (student, choice) - you can't sign up for the same class twice, and you can only have one of each choice. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1LyMUkxqVnDBciMZv39fvg5Ly9H%2BLWgp63RRonYoxKZuQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Tests not passing in suite but pass individually
On Wed, Dec 2, 2015 at 4:20 PM, Siddhi Divekarwrote: > Hi Tim, > > Below is what am trying to achieve. > > class OrcaTestCase(TestCase): > > def test_customer_create_modify_delete(self): > '''Test customer object create, modify and delete operations in > DB.''' > # Create. > CustomerDb.objects.create(c_name='Pnc', c_role='ADFS-Admin', > c_date_created=timezone.now(), > c_date_updated=timezone.now()) > customer_list = CustomerDb.objects.all() > self.assertEqual(len(customer_list), 1) > > # Modify. > customer = CustomerDb.objects.get(c_name='Pnc') > self.assertNotEqual(customer, None) > setattr(customer, 'c_name', 'Zoo') > customer.save() > customer_list = CustomerDb.objects.all() > self.assertEqual(len(customer_list), 1) > self.assertEqual(str(customer_list[0]), 'Gap') > > # Delete. > customer = CustomerDb.objects.get(c_name='foo') > self.assertNotEqual(customer, None) > customer.delete() > customer_list = CustomerDb.objects.all() > self.assertEqual(len(customer_list), 0) > > def test_create_customer(self): > '''Handle customer create.''' > customer_list = CustomerDb.objects.all() > self.assertEqual(len(customer_list), 1) > > test_create_customer runs first, test_customer_create_modify_delete fails at > the highlighted line. > You really really do not need to be testing that Django's CRUD operations work - there is no value in doing so, since Django is well tested. Tests should concentrate on the custom business logic that your app uses, not that when you create an object in the database, an object exists in the database. As to your question, what DB backend are you using for tests? Each django.test.TestCase test is run inside a transaction that is rolled back[1]; if your backend "supports" transactions by ignoring them (cough, MySQL/MyISAM), then nothing happens when the transaction is rolled back. Cheers Tom [1] https://docs.djangoproject.com/en/1.9/topics/testing/overview/#writing-tests -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2B6W%3Dgg2op%2BFc5xKHDCE8QOhiZx-CdCdm6a%3DtWG3YvNEw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Transitioning existing login portal to Django
On Tue, Dec 1, 2015 at 10:15 PM, Evan Palmerwrote: > Hello, > > Does anyone have experience with transitioning an existing database > including user login data to Django? > > I am about to begin work on a startup's hand-written web portal that > consists of about 2000 lines of custom Python code (hashing passwords, > managing user accounts, DB connections, etc.), some Mako templates, and a > Postgresql database. A hand-written web framework makes me nervous for many > reasons. I don't have access to the source code or the database yet, but my > plan is to transition it to Django 1.8. I'd like to use inspectdb to help > generate the models, but I doubt inspectdb will be smart enough to handle > usernames and password hashes properly. How can I make sure this data gets > transferred correctly? > > I'm looking for ideas about how to proceed and/or what to expect during the > transition. Thanks. inspectdb will do a pretty decent stab of things, although there is always some rewriting necessary in order to give the model attributes appropriate names (they don't have to match the table column name, that is what the db_column attribute is for). Django does not support composite primary keys; where this will particularly bite is on M2M "through" or "link" tables; 3NF/BCNF would have those tables with (foreign_key_to_table_a, foreign_key_to_table_b) as the primary key, where as django will want a separate "id" column as a primary key. For passwords, Django provides a password hashing framework: https://docs.djangoproject.com/en/1.9/topics/auth/passwords/#how-django-stores-passwords This allows you to define your own custom password hashing algorithm to accommodate the existing passwords. Ideally, you will update the stored passwords to the same format ("$$$"), defining your own custom name for the algorithm. Adding your new custom password hasher class to the end of settings.PASSWORD_HASHERS will then allow users to authenticate, and then on login or password change - basically, any time the system verifies a plaintext password - the password hash will be updated to the preferred hasher (settings.PASSWORD_HASHERS[0]). If your current hashing algorithm is not secure, eg unsalted md5, then after a certain amount of time (business decision), you should email all users who have not got an up-to-date hash that in X weeks you will reset their passwords and they will have to reset their password. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1Lbru1PHcOsFQq0KSkOYMFvhnofUj9Bdjkv%3DduJwvTqFw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Getting NoReverseMatch and can't find the mistake
On Tue, Nov 17, 2015 at 7:08 PM, Bob Aalsmawrote: > Sorry, can't seem to find what's wrong here, please help: what am I > missing??? > > I'm seeing > > NoReverseMatch at /zoekopdrachten/4/resultaat/ > > Reverse for 'resultaat' with arguments '('',)' and keyword arguments '{}' > not found. 1 pattern(s) tried: > [u'zoekopdrachten/(?P[0-9]+)/resultaat/$'] The pattern asked for an argument, but no arguments were passed to reverse() / {% url %} > > and vraag.html: > Zoekvraag "{{ vraag.zoekvraag_id }}" > > {% if error_message %} > {{ error_message }} > > {% endif %} > > Verzamelen resultaten > method="post"> and therefore the argument you are trying to pass here does not exist. Debug your template context to determine why. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1JTfWteyz%3DXVCLzmstSGL9XHzsuqnCpBu1soW1uYcO4PQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: How do I let forms.models.ModelChoiceField.queryset relate on request.user?
On Mon, Nov 16, 2015 at 5:38 PM, Axel Rauwrote: > > Any idea how to add __init__() to a form class, created by modelform_factory > () ? > > Axel > modelform_factory takes many arguments, one of which is for the base form class to use. You can provide a different base class from the default ModelForm, make sure to derive the new base class from ModelForm. https://docs.djangoproject.com/en/1.8/ref/forms/models/#django.forms.models.modelform_factory Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1LCk_oH4HLMW_7KhjtARkZxESxgQGBUrCeHx1D24h%3DpdQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: django seems does not support mysql 5.7.9
On Tue, Nov 17, 2015 at 11:44 AM, Pengfei Xuewrote: > yesterday, i upgraded my local mysql server to 5.7.9 (mysql Ver 14.14 > Distrib 5.7.9, for osx10.11 (x86_64) using EditLine wrapper), and > found i can not make my app run anymore, find this error, is there some one > else get this error before? > > MySQL-python==1.2.5 mysql-python (MySQLdb) uses a C extension that would be dynamicly linked to the mysql client libraries from your older version of mysql. Did you reinstall and recompile this after upgrading to a newer version of the client libraries? Another alternative is that mysql server no longer supports the client API that mysql-python is presenting. You can mostly connect to older servers using newer client libraries, you can't always connect to newer servers using older client libraries. There are alternative mysql/python connectors available: https://docs.djangoproject.com/en/1.8/ref/databases/#mysql-db-api-drivers Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1LKgXhdJMnOZp4Lt0A8%3DV4vJdQTADtQG0wZq2i6mFZWqw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: TemplateSyntaxError: 'subpackage.echo' is not a valid tag library
On Fri, Nov 13, 2015 at 12:14 AM, James Schneiderwrote: > On Thu, Nov 12, 2015 at 5:10 AM, Jose Paul wrote: >> >> I am just running DJango 1.8 test cases ,here is start of the error trace > > I suspect one of your tests is rendering a template. Do you have a reference > to a template tag anywhere in your templates like {% subpackage.echo %}? I'm > guessing if you visit the page that has that reference, it will also break > in a similar manner. You probably need to add a {% load tag_library %} or > whatever your template tags are called in your template before you call the > template tag. He is running the tests that are built in to django, not his own test cases, specifically this one: https://github.com/django/django/blob/master/tests/template_tests/syntax_tests/test_load.py#L41 OP: You will need to clarify how you are running the test suite. The built in django tests depend on various settings, are you following the instructions in: https://docs.djangoproject.com/en/1.8/internals/contributing/writing-code/unit-tests/#quickstart and https://docs.djangoproject.com/en/1.8/internals/contributing/writing-code/unit-tests/#running-all-the-tests ? Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1JCtip4L%3D3hp6UMpLvRB4_KHquTYktGcabWBuD4ZgNguw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: django filebrowser decoding
On Thu, Oct 29, 2015 at 8:35 PM, Emīls Brasswrote: > I got django filebrowser for admin, where admin can see all added files in > special folder. > > When admin click on folder to see whats inside, if there is some file with > name who contains UNICODE chartacter, then I shows 500 error, but if not, > everything is working. > > We exported this webpage to new server, on old server everything where > working good, but on new server we got this problem, but all website file > are the same, so, I think that problem could be in some python libary files, > I need some plugin or something like that to be installed, but what? > > Example: > Userfiles/folder1/abcde.pdf - all working good > Userfiles/folder2/ābčdē.pdf - not working, 500 error > > On log file I got this message - UnicodeEncodeError: 'ascii' codec can't > encode characters in position 0-5: ordinal not in range(128) > The locale on the new server is the C locale, and is not the same as the locale on the old server, which was some UTF-8 locale. Consult the documentation for the webserver you use to host django, and ensure that the LANG is set appropriately. Searching google for " LANG" should show appropriate results. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1LEniOEh%3DXEaTWZnfyHc7RopU%3D2vSEVeH6FJZ8U%3D8TH8w%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Reverse query name clashe with a M2M and through
On Fri, Oct 23, 2015 at 3:27 PM, Gagarowrote: > However, I still have a question. The reverse relation is wishlist_set by > default. Why is Django bothered if the attribute is name wishlist (I would > understand if I named my attribute wishlist_set)? The message doesn't mention the reverse relation names that conflict, it mentions the names of *fields* whose relation names would conflict. > Reverse query name for 'Wishlist.user' clashes with field name > 'User.wishlist'. > HINT: Rename field 'User.wishlist', or add/change a related_name argument to > the definition for field 'Wishlist.user'. 'Wishlist.user' and 'User.wishlist' are the names of the fields being discussed. The meaning might be clearer with some added words: The reverse query name for the field 'Wishlist.user' clashes with the field 'User.wishlist' - they are both ''wishlist_set'. HINT: Rename field 'User.wishlist', or add/change a related_name argument to the definition for field 'Wishlist.user'. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1LWG0Rc0kKU-SwLUmfzc%2B3ATEtYSj%2B18VwQ47Af5o-g2Q%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: django.test: @override_settings(LANGUAGE_CODE = 'xx') does not affect the default language in a test
On Tue, Oct 6, 2015 at 3:11 PM, Yunshi Tanwrote: > Let's say we have a default language code in settings.py > >LANGUAGE_CODE = 'en' > > Then we have > > >> from django.utils import translation > >> assert translation.get_language() == 'en' > > We are good by now. > > Then in a test, I would like to override the default language. Let's say I > have > > @override_settings(LANGUAGE_CODE='fr') > > class SomeTestCase(TestCase): > > def test_some_case(self): > self.assert(translation.get_language(), 'en') # it will pass > self.assert(translation.get_language(), 'fr') # it would fail > > > Is this a bug? I don't think so, if simply because 'translation.get_language()' gets the currently activated language, not what the current value of "settings.LANGUAGE_CODE" is. LANGUAGE_CODE shouldn't normally change, so I don't think any code detecting when it is changed is warranted. It seems that what you want to do is to change the currently activated language and perform some tests - translation.activate_language() serves this purpose better than patching settings. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1JfSQegCNFv-hfrBAy_hc0eQH5WE%2BKyKWssmxB3k4gVYA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: NOOB exposes CSRF token. Now what?
On Fri, Sep 25, 2015 at 12:01 PM, Tom Evanswrote: > However, what is stored in settings is your SECRET_KEY. If you have > leaked it, you should change it immediately. This will invalidate.. Helpfully, the django documentation for SECRET_KEY details precisely what cycling it will invalidate, so you don't need to trust my un-detailed list: https://docs.djangoproject.com/en/1.8/ref/settings/#secret-key Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1KUgsHcCJvFfDCxB9rfSgC1QxA%3DH21pjR_CvdCe3Sbtnw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: NOOB exposes CSRF token. Now what?
On Fri, Sep 25, 2015 at 7:03 AM, Gordon Reederwrote: > I'm learning Django and still very new at it. And like a newbie, I may have > made a newbie goof. > I have leaked my CSRF token. > I am building up a web site with Django which I have under revision control > with Git. I have pushed two commits of the project out to Github. The > commits included the settings.py file, which list the CSRF token. I have > read (after the fact) that maybe that wasn't the smartest thing to do. > > So now what? > > Can I remove the settings.py file from Github? > Or can I generate a new CSRF token? > > Any suggestions? CSRF tokens are generated on the fly, they aren't stored in your settings.py. However, what is stored in settings is your SECRET_KEY. If you have leaked it, you should change it immediately. This will invalidate sessions, signed cookies, password reset tokens, some forms (if loaded before you change it, and submitted after). Take the pain now. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1KSAM%3DGtMcsNob7P2o7%2BHeWgrVU3qnGKwQbmvDmD4D%2BKw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Forms questions
On Tue, Aug 25, 2015 at 6:10 PM, Hugo Kitanowrote: > > Here it is, very simple: > > Submit form: > > {% csrf_token %} > {{ form.as_p }} > > > Read this section of the manual, particularly the section starting "Firstly, ...". The problems yo uare having are that you aren't telling Django there are files to read in the POST, and even if the files were being read from the POST, you aren't passing them to the form. https://docs.djangoproject.com/en/1.8/ref/forms/api/#binding-uploaded-files-to-a-form Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1J3meKf%3Dafo30Z4%3DtsE3LOMngN198ufEDVcb1cCxajaSA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Integrating RabbitMQ with Django
On Wed, Sep 16, 2015 at 2:34 PM, Erol Merdanovićwrote: > Hello Vijay > > The differences are > 1. Celery message and our message has different format > 2. Celery uses custom queues > > Is this correct? > Yep. Celery is a distributed task system which can use AMQP as transport, but by default it just uses simple direct exchanges. If you are using AMQP for something more specialized, like a fanout or topic exchange, you can configure this for celery. It is still all about running tasks though. This page in the celery docs describes how celery uses AMQP, and briefly discusses the format: http://celery.readthedocs.org/en/latest/userguide/routing.html Implementing your worker processes as a management command is sensible, I would use something like supervisord or circusd to manage the processes. You should integrate restarting the workers in to the deployment scripts that update your web server code. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1KNGkmSSWSH25N_vsFmq2VOKc3A%2BVAA2VGXKdu--r7%3DDw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Django deployment
On Wed, Sep 16, 2015 at 2:20 PM, bobhaugenwrote: > You gotta give PHP credit here. They did deployment better than anybody. > I'd disagree massively. Deploying code is not the same as ftping a bunch of files in to a directory and hoping for the best. Where is the repeatability, rollback etc? > Django as a community could stand to put more concentrated work into > deployment. Django is a community, but django is also just one part of your stack. Rightfully, things like being a webserver, rotating logs, managing rollout/rollback and a whole heap of other things are orthogonal to Django - is deploying a Django project really that different than deploying another python application? Fortunately, Django is part of a larger community - the python community. The python community has done a lot of work in deployment (think virtualenv, fabric, the logging API, supervisor processes...) Even when there isn't a solution in the python community, we're also all part of the larger open source community. We don't need to bring CI into django, because we can easily leverage things like Jenkins, which despite being a Java project, integrates really quite well. Django isn't a panacea - to really downplay it, it just provides tools to manage the ORM, processing requests and managing content - but by combining it with the appropriate other tools and knowledge, you get awesome deployments. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1Ly%2BJM4cat7R7iymsVZQUZXacjCuhO0aJcww5H1YrBpzQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: How to "stop" validation when having errors (is_valid) for form?
On Fri, Sep 11, 2015 at 7:37 AM,wrote: > Example: I have 2 on a html page, which is a form (assume it is > login form, with username and password, both are required and will do > validation on this.). > > The behavior of is_valid I see is: > When submit, the returned errors for the form are: > This field is required (for username) > This field is required (for password) > We'll usually render these messages for the fields (example: {{ form }} will > automatically do all these). > > Now, my question is, it seems like is_valid will trigger validation on both > username and password every time? How to stop it in case one field cannot > pass the validation? Does it make sense to validate all these always? I > think in some of web pages, the behaviour we see is, when one field does not > fulfill the requirements, it give an error message for this only, and when > user submit again but the next field does not fulfill the requirement, it > give error for this field. > > Current behaviour in django: > user name: .(input box) > password: (input box) > Submit without any value, we get: > user name: .(input box) This field is required > password: (input box)This field is required > > I expect: > user name: .(input box) This field is required > password: (input box)(No error here) > > If username is entered and password is empty, submit again, we'll get: > user name: what you enter here (input box) > password: (input box) This field is required > > Any idea how to achieve this? > "required" means "always required", but you wish to only have the password required when the username is also provided. Therefore, set password as not required, and add a check in clean() that applies your special logic and assigns the error message to the appropriate field. Eg: def clean(self): data = super(MyForm, self).clean() user = data.get('username') password = data.get('password') if user and not password: self.add_error('password', 'This field is required') See also: https://docs.djangoproject.com/en/1.8/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1JXZNQ2Tw00yxb-hZiOCN6%3D5zm03AECSEj9jDBdVEOt2A%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Generating a timeseries and aggregation/annotation using QuerySet.extra()
On Fri, Sep 11, 2015 at 1:15 PM, Wannabe Coderwrote: > Hello everyone! > > I already created a ticket detailing my use case, and one of the developers > pointed me to this discussion group. I am not quite satisfied with the > response I got since the DateTransforms that will be released in Django 1.9 > only appear to extract year/month/day/etc numbers and do not seem to be able > to annotate based on generated time periods from a series of > dates/datetimes. Basically what I can do with .extra() right now is generate > a table like the ones shown in my screenshots. > > I hope that behavior would be possible to customize or even include in > Django 1.9 out of the box. Thanks! I think you have slightly misunderstood. The Expressions and Transform API allows *you* to create user defined expressions and transformations. Yes, there are some new built in expressions and transformations available, but the real power is allowing you to define such a transformation in a reusable way, rather than hacking it in to extra() like you currently have to do in each place you want to use it. So you want an expression that is like MonthTransform, but using DATE_TRUNC() instead of MONTH()? Have at it! It's a documented API: https://docs.djangoproject.com/en/dev/ref/models/lookups/#transform-reference The DB backends operations class even support a datetime_trunc_sql() (compare with the implementation of DateTransform, base class of MonthTransform) https://github.com/django/django/blob/master/django/db/models/fields/__init__.py#L2432 Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1KfNPY2mHUR3A1WtsrQ1qfJxKYnVFJb%3DQBTSgt2Om%2B%3D%2BQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: customize app ordering in django admin
On Thu, Sep 10, 2015 at 11:50 AM, Pawanesh Gautamwrote: > hi > > i have list of app (app1,app2.app3,app3,app4).i would like to change the app > order in admin site so that it will look like dis : > (app1,app3,app4,app2). > please suggest some tips to perform this . > > thanks My top tip: Read the django tutorial all the way through: https://docs.djangoproject.com/en/1.8/intro/tutorial02/#customize-the-admin-index-page Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2Bjuds5%2ByjLaQEoUhsVwtVF%3DDens72D0CRJcW_BPHiwrA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: What frontend-tools to use for a new CRM project? Shall I use Django OR switch to Meteor.js?
On Tue, Sep 8, 2015 at 11:12 PM, ThomasTheDjangoFanwrote: > Hi guys, > > I have invested quite a lot of time & energy into learning django and I feel > comfy using it. (I have studied the 2 Scoops, the Tdd book and got the boook > "Scaling Django" and "lightweight Django" right here next to me). > > It feels like I finally got the right tool, BUT: > I am about to implement my first big project - a customer relation > management system. The userbase will be small - around 1 to 10 users. > > During my planing I came accross javascript-framworks (like angular or > meteor) and yes: my project definetly needs some javaside-tricks on the > client-side. > > So I used the last 7 days to stick my head into the javascript stuff and I > am sooo overwhelmed by all the options out there (!!!). And it seems > like there really is no good tutorial for the javascript-frontend stuff with > django. Django produces web responses, which can contain whatever you want in it. As such, javascript is orthogonal to django. Django can easily generate data in JSON format that is easily consumable by any JS framework. Libraries exist for django to provide REST-like frameworks for even easier access. This will give you a set of API urls which you can consume from any JS framework. > > Now I am going crazy and thinking about dropping django completely and > switching to Meteor. (By the way: The meteor-guys seem to be totally in love > with react.js.) > > Before making a stupid decision I feel like I need some guidance from the > real experts. > > Now my question to you is: > If you were about to implement a quite-complex crm system (starting from the > ground up): what tool would you use? > Would you use Django (maybe in combination with React) or would you switch > to Meteor? You are asking on the django mailing list whether we would use django or a server side JS framework at best we will be quite biased (guess what we like to run server side!), at worst we will be unable to give you a comparison. You say you want to drop django and go with meteor - why? What problem does it solve for you that Django does not? What it really comes down to is if you want to write your server side code in Python, use django. If you want to write it in Javascript, use something else! > If you would stick to Django - which js-framework can you recon? (I really > need some good and clear tutorials to get me started) We have (different!) django projects using react, backbone and angular. Use the frontend framework that allows you to develop your project most efficiently. TBH, if you haven't implemented a reasonable sized project in django/python then it will be hard for you to make a decision between two unknowns. Reading books is not the same as doing. I would factor this in to your project - evaluate your two options by doing things with them. Spend a week putting together it in Django, spend a week doing the same in Meteor, see which one allows you to build the most functionality in the shortest amount of time (and don't disregard the code quality, if it looks like spaghetti after 1 week working on it, imagine how it will look after a year or two.) Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1Kc7N4HO%2Bsr%2BYzPZh2ei-TXDK-NYpYxRtVt2xn6PL9vUA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Missing/inconsistent GenericIPAddressField validation?
On Mon, Sep 7, 2015 at 12:33 PM, Hans S. Tømmerholtwrote: > GenericIPAddressField isn't intended to represent a CIDR address, which I > guess is what I'm trying to put into it. > > There is stuff like this: > https://pypi.python.org/pypi/django-netfields/0.2.1 +1 This is what we use for CIDR and arbitrary IP ranges, stored in postrgres as native types so that queries/filters all happen on the DB server with exceptional performance. > > I am still slightly confused as to why validation doesn't occur on the model > level, though. Validation only happens if you instruct it to happen. If you just save() the model instance, no validation occurs. See the "Note ..." paragraph here: https://docs.djangoproject.com/en/1.8/ref/models/instances/#validating-objects Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2BmgjY2%3DeX2Z53eFr7LBKwDeJRpR%3DQqRWUCLUmFsOoPaQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Django and Wiki
On Thu, Sep 3, 2015 at 12:01 PM, Нина Белявскаяwrote: > Is anywhere in the Web examples of Wiki projects on Django? https://www.djangopackages.com/grids/g/wikis/ > Which wiki-engine is used on https://code.djangoproject.com/wiki/? That is not a django site, it is a Trac instance: http://trac.edgewall.org/ Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1K064Aq4zYun_Evefeuve1GfMYKqGSadGR5tPcKSpWfGQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Time Zone Problem when following on tutorial
On Fri, Jul 4, 2014 at 12:01 AM, Mike Dewhirstwrote: > On 3/07/2014 11:57 PM, Jerry Wu wrote: >> >> Mike, >> >> Sorry for the late reply. >> >> Your explanation about "time is constant" makes sense to me. But I still >> didn't know what to do with time setting following the tutorial. > > > One day I'll do some experiments and *really* understand how it works. > > My variables are: > > TIME_ZONE = 'Australia/Melbourne' > > - time stored in the database eg., "2014-06-30 22:46:29.037+10" which in > June is AEST - Australian Eastern Standard Time or in March "2014-03-05 > 13:48:15.164+11" is daylight saving time. > > - USE_TZ = True With USE_TZ=True, TIME_ZONE only controls the display of datetimes. Django should be storing all the database values as UTC, and converting them to TZ-aware when extracting from the database. > > When I find the courage I will try setting TIME_ZONE = 'UTC' and see how > times are displayed. New ones and existing ones! Maybe I'll do it around the > next changeover to daylight saving in Melbourne. > You probably don't want that, most users don't understand UTC. Always store in UTC, but display in a human timezone. Another thing you can do is to allow users to select their timezone and persist it on their user/profile. You can then use a bit of middleware to activate that timezone, or if not specified, revert back to the one specified in settings. In code: from django.utils import timezone from django.conf import settings class TimeZoneMiddleware(object): """ This middleware activates a user's timezone, so that all dates we give them are localised correctly. """ def process_request(self, request): if request.user.is_authenticated(): if user.timezone: try: timezone.activate(profile.timezone) return except: pass timezone.activate(settings.TIME_ZONE) Dates in the database would all be stored in UTC, and converted in to whatever timezone the end user wishes to use. Unfortunately, you can't easily determine timezone from HTTP headers, but for bonus points, you can *request* it from the browser with javascript and append that data to a form to allow you to provide a "best guess". I say "request", because you don't get back a useful timezone like "Europe/Valencia", you will get "+0200", which is almost impossible to map to a specific timezone. There are many timezones that have offset "+0200" at certain points in the year... Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1K29Wz3wzoSinh%3Dd0fs3L__Vya65PANQUCkDidTcjWaMA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Django 1.6.11 model class query
On Wed, Aug 19, 2015 at 3:18 PM, Nikunj Badjatyawrote: > Hello All, > > I have a django model class defined as: > > > class Test(models.Model): >id=AutoField(primary_key=True) >name = models.CharField(max_length=45, null=False) >description = models.CharField(max_length=200, null=True) >uuid = models.CharField(max_length=250) >class Meta: >managed = False > db_table ="test" > > Where, > uuid is auto generated using a mysql trigger. > > Mysql Trigger looks like: > DROP TRIGGER IF EXISTS `test_uuid`// > CREATE TRIGGER `test_uuid` BEFORE INSERT ON` test > ` > FOR EACH ROW begin if (new.uuid is null or new.uuid = '') then set new.uuid > = (select uuid());end if; end > // > This trigger is added at the db level. > > i.e., any new insert in 'test' table would generate the value for uuid > column. > and insert works fine for this model from the code. Why do you want to do this way? > > Issue is, when I try to access the uuid after I have performed the save(), I > am getting null. > > row = Test(name=in_data['name'], > description=in_data['description'], >) > row.save() # This creates a row with id, name, description and uuid (auto > generated by the pre insert rigger) > print(row.id) # Prints id > print(row.uuid) # Prints u' ' > > > > > Any idea as to what may be going on? > Why row.uuid is coming as empty from the code though the uuid is clearly > generated in the db table. > When you save something to the database, Django does not re-select out the data that you just saved, and the contents of a model instance are exactly as they were before you saved it - as far as django is concerned, it has just persisted the most up to date version of it *from* that model instance, so it would be wasteful to re-select it out. This is because django is an ORM, it knows about its own data serialization, but nothing about your DB level trigger modifying the data that it serializes. You have two straightforward options - move the uuid setting code to a django pre-save hook (ideally using the built in UUID field), or every time you save an object, remember to re-fetch it from the database. Whatever you do, presumably you are using UUIDs as an opaque identifier, and will query the database by UUID to find an object, and so the UUID field should be declared as db_index=True. Cheers Tom PS: UUIDs are 128bit integers - 16 bytes. Storing a 128 bit integer as a variable length string of up to 250 bytes is going to be massively inefficient, so you really should use a UUID type (new in 1.8) so that it uses the best type it can for your database backend, either native uuid or a fixed 32 char string. -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1LyK4E9BqF6%2B3ZXAqJz64f8sExB6fvgAz6OUtbuiqPZ9A%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Issue when rendering manually a form's HiddenInput
On Thu, Aug 6, 2015 at 6:55 PM,wrote: > So, I'm trying to use inputs with the hidden attr. I have my form class > (IndexForm) that has this: > field = HiddenInput() > Then, I pass the instance of IndexForm (index_form) to the template, and > manually render the field (index_form.field). It is alright, but then, in > the HTML, the render of the field is this... > > Why I'm seeing the str representation of the object, and not an HTML hidden > input? Forms are collections of Field instances, but HiddenInput is a Widget. You should be setting the widget attribute of one of the fields to be a HiddenInput, not assigning a HiddenInput as a member of the form. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1K9EbUSdHTkQ3V%3D2dTUXj88ubAmgVvun6jDidP32y6%3DZQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: django "plain managers"
On Wed, Aug 5, 2015 at 1:03 PM, varun naganathanwrote: > what does django mean exacty by "plain manager"??? A models.Manager() instance that is added by default to your models.Model class if you do not explicitly specify a "non plain" manager. https://docs.djangoproject.com/en/1.8/topics/db/managers/ Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1K0WVaKqMmf47AS6fA6%2BvYjT0P7Mb%2BLbM8J86Enf8Td_A%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Upload new file to the uploaded file path
On Tue, Aug 4, 2015 at 9:45 PM, Robin Lerywrote: > I have a model for Video: > > class Video(models.Model): > title = models.CharField(max_length=75) > pubdate = models.DateTimeField(default=timezone.now) > original_video = models.FileField(upload_to=get_upload_file_name) > mp4_720 = models.FileField(upload_to=get_upload_file_name,blank=True, > null=True) > converted = models.BooleanField(default=False) > > And this is the view: > > def upload_video(request): > if request.POST: > form = VideoForm(request.POST, request.FILES) > if form.is_valid(): > video = form.save(commit=False) > video.save() > convert_video.delay(video.id) > return HttpResponseRedirect('/') > > Lastly the tasks.py: > > def get_upload_file_name(video): > name = video.title > name = name+'.mp4' > return name > > from pyvid.settings import MEDIA_ROOT > > @app.task > def convert_video(video_id): > video = Video.objects.get(id=video_id) > video_path = str(MEDIA_ROOT)+'/'+str(video.original_video) > convert_video_name = get_upload_file_name(video) > cmd = 'ffmpeg -i %s -codec:v libx264 -profile:v baseline -preset slow > -b:v 250k -maxrate 250k -bufsize 500k -vf scale=-1:360 -threads 0 -codec:a > libfdk_aac -movflags +faststart %s.mp4' % (video_path, convert_video_name) > subprocess.call( > cmd, > shell=True > ) > > video.mp4_720 = convert_video_name > video.converted = True > video.save() > > The problem is, even though video.mp4_720 is directed to > upload_to=get_upload_file_name, its just taking the value of > convert_video_name file path (which is in the base directory of the project) > but not to the path applied. > > How do I upload the new converted file it to the uploaded path? > You asked this about 3 weeks ago as well (and replied to that email today), did this approach not work?: This is explained in the docs for FileField, you need to create a django.core.files.File subclass, and save() it on the FieldFile object that is returned when you access the FileField field on your model instance. Eg: from django.core.files import File fp = open('/path/to/file') myfile = File(fp) my_obj.mp4_720.save(name="", content=myfile) https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.fields.files.FieldFile.save Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2BxUVC0vnV2wctro46ZOfWrF53BjOj1odQdzg92SDvL0Q%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Two-to-Many Mapping between Models in Django ORM
On Thu, Jul 30, 2015 at 4:08 PM, Rich Lewiswrote: > Dear All, > > I'm new to the Django ORM, and quite new to ORMs in general. I have two > models (lets call them A and B) between which I have an interesting mapping. > There are precisely 2 B instances associated with each A instance. Each A > instance can have many B instances. The order of Bs are important for As. > > I want to do something like this: > > class A(models.Model): > b_1 = models.ForeignKey(B) > b_2 = models.ForeignKey(B) This would fail here, when you have more than one foreign key to the same model, you must supply a related_name argument on one of them, which is used for the inverse relation on the related object. Which leads us in to... > > class B(models.Model): > pass > > Such that i can do: > b1, b2, b3 = B(), B(), B() a1, a2 = A(b_1=b1, b_2=b2), A(b_1=b2, b_2=b3) b2.as > [, ] #(order doesn't matter) Typically, B instances would have an attribute named 'a_set' (the lower case model name of the model it is related to, with "_set" appended). When you have multiple relationships with the same model, as I mentioned you must supply your own related_name arguments. In which case, with the models you mentioned, you could then do something like this: >>> b2.a1_set.all() | b2.a2_set.all() > [, ] > > I expect I could eventually do something a bit hacky that would work, but > what would be the best way to handle this? I would say the above is the hacky way. You could have the same B assigned to b_1 and b_2 and would have duplicates in the set, and no way to specify DB constraints to limit it. Given that you anticipate being able to retrieve all the A's for a particular B, regardless of how they are related, I would model it as a M2M with a through table holding any additional information about the relationship, using the through table to add DB level constraints. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2B7-KieRLGT_hG-UDC6zeyg%2Bb8d%3D7XtEK4EEM8nFvzFng%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Celery to process task and modify the model fields
On Tue, Jul 14, 2015 at 9:15 PM, Robin Lerywrote: > Yes. That time you were the one to guide me. I was looking at other projects > after that. > > I am just confused on how to get the video.mp4_720 to be the converted > video. Will you please help. > This is explained in the docs for FileField, you need to create a django.core.files.File subclass, and save() it on the FieldFile object that is returned when you access the FileField field on your model instance. Eg: from django.core.files import File fp = open('/path/to/file') myfile = File(fp) my_obj.mp4_720.save(name="", content=myfile) https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.fields.files.FieldFile.save Also, you should not pass objects as arguments to celery tasks, you should instead pass the id of the object and fetch the object again in the celery task. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1J%2BGf_hRB7ERLonXpT_jhDqX8NkEYtV5qnftyMgKvJ0OA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: potential bug
On Sun, Jun 14, 2015 at 3:24 PM, Mark Nesterovychwrote: > Hello. > I've just finished small django site, and keep going on creating tests. > I've found and issue with Model.objects.values_list method. > Looks like it disregard test database and looks into production one. > > Some details. > I have a form with a filed customer = > forms.ChoiseField(choises=Customer.objects.values_list('id', 'name')) > > When this form initing during tests, it loads data from production database. > > My test looks like this. > class CustomerFormTest(TestCase): > def setUp: > self.customer = Customer.objects.create(name='test name') > > def test_form_creation(self): > form = CustomerLoginForm() > self.assertIn('test name', form.as_ul()) > > > Assertion fails, and when I printing form content, I see select widget with > options from production database objects. > > Can somebody confirm it's a bug ? > Thank you. It's not a bug. You are specifying the choices when the form is defined, and at that point there is nothing in the database and so the form has no choices. Since the field is never redefined in the form, the choices will be whatever existed in the database when the form is defined, which is a bad way of designing the form. Typically, when your choices are instances of a model, you would not use ChoiceField, but ModelChoicefield. ModelChoiceField takes a queryset when defining the form, and avoids evaluating the queryset until the form is instantiated, which avoids the issue. The documentation also explains how you can specify the queryset more dynamically if that is required. https://docs.djangoproject.com/en/1.8/ref/forms/fields/#modelchoicefield (I'm assuming that the typo "choises" is only present in your email, and your code correctly says "choices" and "ChoiceField") Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1LerMfvVs056hVnFY8Jqm0gqtLDm0wcpWqgjC4V88fpBg%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Django plugin
On Thu, Jun 11, 2015 at 8:02 PM, Andreas Kuhnewrote: > Hi all, > > I was wondering if there is a plugin application for Django. What I want to > accomplish is react to different kinds of events on my models and then > create plugins on the fly for them. > > The system I am working on has for example an Order model. When a new Order > is created, I want to send a notification to the person who created the > order. I know that I can do this with signals, but I don't want it to > specifically be tied to a Django application. > > I was thinking something along the lines of using RabbitMQ for example to > post all events there and then be able to react on them later. Has anyone > done anything like this? > > I have seen Celery, but as I understand that, it takes some method to run > like a delayed job? > > Regards, > > Andréas > Celery is (usually) built on top of an AMQP broker. AMQP was developed to support High Frequency Trading (HFT) and is ideal for publishing events and taking actions based upon them. I'd suggest reading this blog post: http://blogs.digitar.com/jjww/2009/01/rabbits-and-warrens/ and then the docs for Kombu, which is an excellent messaging library for python. http://kombu.readthedocs.org/en/latest/ AMQP is not the only message bus, but we've had great results with it (using rabbitmq). Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1JEb08O0PMdzEBC0%3Dq8LRVZcHz11PPg067aSby7YhaLjQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Simulating REMOTE_USER login with the test server
On Tue, Jun 9, 2015 at 10:07 PM, Gergely Polonkaiwrote: > Hello, > > I’m about to use the test server with REMOTE_USER based logins. I already > know how to set it up with my Apache based server, but I can see no way of > doing the same with the dev server (manage.py runserver). I have tried > setting the environment variable REMOTE_USER to a desired value, as I saw > some env vars in request.META earlier, but it doesn’t seem to help. Does > anybody know if this is possible, and if so, how? > > Best, > Gergely > Write a piece of custom middleware that is only active with DEBUG=True that sets the REMOTE_USER you desire. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1Lv6XyBuj6_Xy%3DGSC3g-tndH77Z9oD3QdPUNHk9PLqLqA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.