Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I rioritize the order of the fields in the filter
When I filter the objects, objs = Page.objects.filter(slug="some-slug.html", web_id=1) the SQL query generated is select * from cms_page WHERE ("cms_page"."web_id" = '1' AND "cms_page"."slug" = '''some-slug''') I would like change the SQL to select * from cms_page WHERE ("cms_page"."slug" = '''some-slug''' and "cms_page"."web_id" = '1' ) First slug field, because the slug field is a index (Exist index with this field) class Page(models.Model): title = models.CharField(max_length=128) body = models.TextField(blank=True) slug = models.CharField(max_length=200, db_index=True) web = models.ForeignKey(Web, editable=False) def __unicode__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = "{0}{1}".format(slugify(self.title),".html") super(Page,self).save(*args,**kwargs) class Meta: unique_together = ("web", "slug") index_together = ["web", "slug"] -
Django Custom Auth Migration
I was trying to alter something on my user model in django and in the process I used makemigration to generate the migration file for it. But then decided against the whole thing, but now I have an unmigrated migration file located somewhere and I can't find it. I don't have an auth migrations folder in my app and I looked in the django auth migrations file and it's not there either. It shows up when I run python manage.py showmigrations as unmigrated, but I don't see the file anywhere. It doesn't show up when I do git status either. Now I'm stuck because I can't run migrate without it trying to migrate it and erroring. This is probably something silly that I'm overlooking. :-/ -
Django Admin Panel
I am trying to set up a new blog. I want to keep all my project templates folder in the same folder as where my settings.py is. To do this I did the following... [...] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates/")], 'APP_DIRS': False, 'OPTIONS': { 'context_processors': [ [...] But now, my admin panel layout doesn't work. How can I circumvent the above solution when using the admin panel? I get the error Exception Type: TemplateDoesNotExist Exception Value: admin/login.html -
django crispy forms label override not working
I can't seem to override the default label with django crispy forms. model.py class User(AbstractUser): house_name_number = models.CharField(max_length=255) street_name = models.CharField(max_length=255) town_city = models.CharField(max_length=255) county = models.CharField(max_length=255) postcode = models.CharField(max_length=8) same_address = models.BooleanField() move_in_date = models.DateField(null=True) forms.py class AddressForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.label_class = 'sr-only' self.helper.form_tag = False self.helper.layout = Layout( PrependedText('postcode', '<i class="fa fa-home"></i>', placeholder="Postcode", autofocus=""), PrependedText('house_name_number', '<i class="fa fa-home"></i>', placeholder="Building Number or Name", ), PrependedText('street_name', '<i class="fa fa-home"></i>', placeholder="Street Name", ), PrependedText('town_city', '<i class="fa fa-home"></i>', placeholder="Town or City", label="test"), PrependedText('county', '<i class="fa fa-home"></i>', placeholder="County"), Field('same_address', '<i class="fa fa-home"></i>', label="Have you lived at the property for 3 years"), PrependedText('move_in_date', '<i class="fa fa-calendar"></i>', required=False, placeholder="What date did you move in to your current address"), ) -
DJCelery to Celery + Django 1.8 to 1.10 = Postgres Connection Issues
I've been trying to debug an issue whereby my application is getting "OperationalError: FATAL: remaining connection slots are reserved for non-replication superuser connections" using postgres 9.4 and Django 1.10. As part of the switch from 1.8 to 1.10 we began using plain ol' celery rather than dj-celery for our task scheduling. Threaded Django task doesn't automatically handle transactions or db connections? The above SO question has me thinking that the issue might be that our celery tasks are keeping their connections open. I could see how switching from dj-celery to celery could impact our django integration. I've increased the maximum number of connections from 100 to 500 (well within our hardware's memory capability) as a bandaid, but I need this connection count to go down. For now, the connection count seems to have stabilized at 180 and isn't going up further, but I'm worried about not being able to throw more memory at the problem. While I suspect celery, it could be another part of my app code that is failing to close these connections. Is there a way for me to see in Postgres which connections are staying open? The only query I've been running so far has been … -
Django Translation
Try to translate block this block and load i18n: {% load i18n %} <p>{% trans "Welcome to our page" %}</p> {% language 'ru' %} <p>{% trans "Welcome to our page" %}</p> {% endlanguage %} settings.py SE_I18N = True USE_L10N = True LANGUAGES = ( ('en', _('English')), ('ru', _('Russian')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) TEMPLATES = [ { 'context_processors': [ 'django.template.context_processors.i18n', MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] .po msgid "Welcome to our page" msgstr "Приветствую вас!" #: project/settings.py:172 msgid "English" msgstr "Английский" #: project/settings.py:173 msgid "Russian" msgstr "Русский" mo. Report-Msgid-Bugs-To: POT-Creation-Date: 2016-10-10 19:24+0000 PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE Last-Translator: FULL NAME <EMAIL@ADDRESS> Language-Team: LANGUAGE <LL@li.org> Language: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Английский Русский Приветствую вас! But result is: Welcome to our page Welcome to our page I used this doc https://docs.djangoproject.com/en/1.10/topics/i18n/translation/ Maybe I forgot something? -
Djano-autocomplete-light does not show search box for selecting OneToOneField
I am trying to use autocomplete in admin page to auto select a field(OneToOneField) before saving, I am following the tutorial to add a field in admin. I am not able to see the search box to type in my selections. I tried replicating the select2_one_to_one app from the test project: https://github.com/yourlabs/django-autocomplete-light/tree/master/test_project I am see the same issue for this app as well. Attaching a screeshot of the issue Screen shot of the select2_one_to_one app -
Linking to static files with Django on localhost
Objective I'm trying to change the STATIC_URL in my settings.py in my Django project so that it points to a .css file and those styles render on my local computer Right now, the project runs on http://127.0.0.1:8000/salaries/ while the actually .css file I'm trying to point to lives at: http://127.0.0.1:8000/salaries/static/salaries/css/style.css I've tried Attempts to change it to localhost or 127.0.0.1:8000 in order to point to that file, have resulted in django.core.exceptions.ImproperlyConfigured: If set, STATIC_URL must end with a slash I've also read the documentation here, but it's not particularly clear settings.py """ Django settings for payrolls project. Generated by 'django-admin startproject' using Django 1.8.5. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '9xcfcm300msjjwlgdc6@1y%s06#aec&5*c2)ececvy!c=7kj(q' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', # For a new user to … -
Change Password for user in Django when not using the Django User model
I'm halfway through a Django project and we did not start with the default Django User model that is provided. Now it is too late into the project to go back and implement the User model. The user I have has a set of fields including email, password, firstname, lastname, etc. I created a page to edit the user profile and I'm able to successfully edit any field other than the password field. I tried creating a separate page just to change the password with its own forms, but even then, when I try to save the new password value nothing happens. Almost all of the answers in stack overflow correspond to using the Django User model so it doesn't help in this case. How is it possible to update a password field manually in django? -
'generic_inlineformset_factory' produce " 'NoneType' object has no attribute '_meta' "
I can not save my front-end choices using generic_inlineformset_factory. If I do not select anything in front-end, the line sports = sports_formset.save(commit=False) does not produce any errors, but if I choose anything, I get 'NoneType' object has no attribute '_meta' The # PROBLEM PART at the bottom of the code. # models class M2MProfilesToSportTypeGroups(models.Model): MASTERY_CHOICES = ( (1, _('newby')), (2, _('amateur')), (3, _('semi-pro')), (4, _('pro')) ) mastery = models.IntegerField(_('mastery'), null=True, blank=True, choices=MASTERY_CHOICES) sport_type_group = models.ForeignKey(SportTypesGroups, verbose_name=_('sport type group')) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') # views class CompanyProfileCreateView(LoginRequiredMixin, TemplateView): template_name = 'profiles/create_n_update.html' def get(self, request, *args, **kwargs): profile_form = CompanyProfileForm() #show_criterias=False) PlaceTypeFormSet = inlineformset_factory(CompanyProfiles, M2MCompanyProfilesToPlaceTypeGroups, fields='__all__', can_delete=False) SportTypeFormSet = generic_inlineformset_factory(M2MProfilesToSportTypeGroups, can_delete=False) places_formset = PlaceTypeFormSet() sports_formset = SportTypeFormSet() return self.render_to_response({'form': profile_form, 'places_formset': places_formset, 'sports_formset': sports_formset}) def post(self, request, *args, **kwargs): profile_form = CompanyProfileForm(data=request.POST) PlaceTypeFormSet = inlineformset_factory(CompanyProfiles, M2MCompanyProfilesToPlaceTypeGroups, fields='__all__', can_delete=False) SportTypeFormSet = generic_inlineformset_factory(M2MProfilesToSportTypeGroups, can_delete=False) places_formset = PlaceTypeFormSet(data=request.POST) sports_formset = SportTypeFormSet(data=request.POST) if profile_form.is_valid() and places_formset.is_valid() and sports_formset.is_valid(): profile_form.instance.created_by = request.user company_profile = profile_form.save() places = places_formset.save(commit=False) for place in places: place.company_profile = company_profile place.save() # PROBLEM PART sports = sports_formset.save(commit=False) for sport in sports: obj.content_object = company_profile obj.save() return redirect(company_profile) return self.render_to_response({'form': profile_form, 'places_formset': places_formset, 'sports_formset': sports_formset}) Any … -
Django Rest Framework - M2M via through
Im having trouble with retrieving all fields I need from serializer. Scenario: I have 2 tables: Item & Warehouse. Those tables are connected via M2M relationship via through table called InventoryStatus. What I need is to get Item info with nested warehouse info + status field from InventoryStatus Table. The problem is, I cant get the "status" field.... Model: class InventoryItem(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) code = models.CharField(max_length=25, null=False, blank=True) orgid = models.ForeignKey('glonass.Company', null=True, related_name='inventory_items_company') title = models.CharField(max_length=150, null=False, blank=True) inventory = models.ManyToManyField('CompanyBranch', through='InventoryStatus', related_name='branch_iventoryStatus') class CompanyBranch(BaseDataDescTime, LocationInfo, PostInfo, PoboxInfo, ContactInfo): id = models.UUIDField(primary_key=True, default=uuid.uuid4, orgid = models.ForeignKey('glonass.Company', null=True, related_name='branches') slug = models.SlugField(max_length=150, blank=True, null=False) class InventoryStatus(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) inventoryitem = models.ForeignKey('InventoryItem', related_name='inventory_status_items', null=True) orgid = models.ForeignKey('Company', null=True, related_name='inventory_status_company') companybranch = models.ForeignKey('CompanyBranch', related_name='inventory_status_warehouses', null=True) status = models.DecimalField(max_digits=9, decimal_places=2, null=True, blank=True, default=0) Serializer: class InventoryStatusSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = InventoryStatus class CompanyBranchSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = CompanyBranch class InventoryItemSerializer(serializers.HyperlinkedModelSerializer): inventory = CompanyBranchSerializer(many=True) class Meta: model = InventoryItem Output Needed: [ { 'id': 'xxxxxxxxxxxxx', 'title': 'Car', 'inventory': [ { 'id': 'yyyyyyyyyyy', 'title': 'warehouse 1', 'status': 50 }, { 'id': 'zzzzzzzzzzzz', 'title': 'warehouse 2', 'status': 10 } ] } ] -
Creating a django model that uses a 3rd party web service as a datasource
How do I create a Django model that uses data from a web-service to populate data. To elaborate. I have an HTTP service that returns a JSON array of log entries in the format: [ {date:'2007-01-11',title:'log entry 1'}, {date:'2007-01-12',title:'log entry 2'}, {date:'2007-01-13',title:'log entry 3'}, {date:'2007-01-14',title:'log entry 4'} ] The data is retrieved from a web service, lets say http://localhost/logs via an HTTP GET request. Is it possible to have a model like class log (models.Model): date = models.models.DateTimeField('Last updated', auto_now=True) title = models.CharField(max_length=25) Or would I need to query the service from some kind of controller and pass it to an admin view? If so how do I override the admin controller? -
Django admin template override not working
Django 1.6.11 App structure looks like: my_project/ |-- new_app/ |-- templates/ in my config: TEMPLATE_ROOT = os.path.join(BASE_ROOT, 'templates/') TEMPLATE_DIRS = ( TEMPLATE_ROOT, ) INSTALLED_APPS = ( 'django.contrib.admin', ... 'new_app', ) When I copy venv/django/contrib/admin/templates/admin/change_list.html to my /templates/admin/new_app/change_list.html I don't see my customizations show up. my_project/ |-- new_app/ |-- templates/ |-- admin/ |-- new_app/ |-- change_list.html When I move change_list.html up one level so it's under the admin path, the changes show up just fine: my_project/ |-- new_app/ |-- templates/ |-- admin/ |-- change_list.html |-- new_app/ (now an empty folder) ... but of course that would mean my changes are going to affect every admin page, not just for the app I'm trying to modify. I'm following the documentation guide found at readthedocs in section 2.4.8 on page 31, but I don't seem to be having any luck. -
Django : Error : [u'ManagementForm data is missing or has been tampered with'] after formset is saved
After I press the submit button for a formset being saved, I get this error: "[u'ManagementForm data is missing or has been tampered with']" This is the code in my views.py MarcheFormSet = formset_factory(PrixMarcheForm1, extra=2) if request.method == "POST": formset = MarcheFormSet(request.POST) if (formset.is_valid()): for form in formset: print form form.save() return redirect("/appartement/ajouter3/") else: print "nope" and my form.html(template being called by views.py) {% if formset %} <form action="" method='POST'>{% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form|crispy }} {% endfor %} <input type='submit' class='btn btn-default' value={{ outcome }}> </form> {% endif %} And ideas would be greatly appreciated -
OperationalError: no such table
So I was working on my app and added a slugfield to my models. Then as normal went ahead to makemigrations, and a massive red wall of errors appeared. Traceback (most recent call last): File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: Reader_manga The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Program Files (x86)\JetBrains\PyCharm 2016.2.3\helpers\pycharm\django_manage.py", line 41, in <module> run_module(manage_file, None, '__main__', True) File "C:\Users\Andreas\AppData\Local\Programs\Python\Python35-32\lib\runpy.py", line 182, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "C:\Users\Andreas\AppData\Local\Programs\Python\Python35-32\lib\runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "C:\Users\Andreas\AppData\Local\Programs\Python\Python35-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "D:/WindowsFolders/Documents/Python/ReaderProject\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\core\management\base.py", line 342, in execute self.check() File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\core\management\base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\core\management\base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "C:\Users\Andreas\ReaderProject\lib\site-packages\django\utils\functional.py", line 35, in __get__ … -
Django Rest Framework form-data user json with images in one post request
is there any simple solution or maybe extension for Django rest framework to combine Json with from-data. Purpose for this is, create one post request and send multiply files with json objects. I don't know is this a good way to do post request, or maybe execute first Json then wait for response take ID from Parent and send files in next request. Verison of framework: Django: 1.10.2 Rest Framework: 3.4.7 Here is my simple code explanation: Models class Title(models.Model): name = models.CharField(max_length=255) def __str__(self): return str(self.id) class Definition(models.Model): description = models.TextField() title = models.ForeignKey('Title', related_name='title') def __str__(self): return str(self.id) class Files(models.Model): file = models.FileField(upload_to='files') definition = models.ForeignKey('Definition', related_name='definition') def __str__(self): return str(self.id) Logic is: first create title on save, then take ID and save next object, then take ID from second object and save, finally return serialization data to view. Serializer class SerializerFiles(serializers.ModelSerializer): class Meta: model = Files class SerializerDefinition(serializers.ModelSerializer): description = serializers.CharField() class Meta: model = Definition class SerializerTitle(serializers.ModelSerializer): title = SerializerDefinition(many=True) definition = SerializerFiles(many=True) class Meta: model = Title def create(self, validated_data): title = validated_data.pop('title', None) definition = validated_data.pop('definition', None) inst = Title.objects.create(**validated_data) pk = 0 for x in title: a = Definition.objects.create(title=inst, **x) pk += int(a.id) … -
Dealing with dependent objects in Django templates
First of all, am I right in understanding that Django tags are effectively a mini-language unto themselves, and that Python won't run in them? If so, how should I deal with values that would be difficult for the view to preprocess? For eg, this is what I want to do (a user has many ratings): {% for user in users %} # Where users are defined in the view/context ... {% endfor %} Then inside that I've tried a couple of things {% for rating in user.ratings %} or {% for rating in Rating.objects.filter(user=user) %} The former never iterates. The latter is hideous, and in any case doesn't work - it raises TemplateSyntaxError at / Could not parse the remainder But since it's only in the middle of the loop through users that I get the relevant user to filter by, I'm not sure how I would set up the second QuerySet in the view. What's the best approach here? -
Create relationship between two models using django class based views
New to django. I have two models Company and Campaign. I need to create a relationship between them. I think my models are fine. companies/model.py class Company(models.Model): class Meta: verbose_name_plural = "companies" user = models.ForeignKey(settings.AUTH_USER_MODEL) title = models.CharField(blank=False, max_length=128, default='') slug = models.SlugField(blank=True, unique=True) archived = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) campaigns/models.py class Campaign(models.Model): class Meta: verbose_name_plural = "campaigns" company = models.ForeignKey('companies.Company', on_delete=models.CASCADE,) title = models.CharField(blank=False, max_length=128, default='') slug = models.UUIDField(default=uuid.uuid4, blank=True, editable=False) def __str__(self): return str(self.title) campaigns/forms.py class CampaignForm(forms.ModelForm): class Meta: model = Campaign fields = ['title','description','archived'] campaigns/views.py class CampaignCreateView(SubmitBtnMixin, CreateView): model = Campaign company = None form_class = CampaignForm submit_btn = "Add Campaign" template_name = "form.html" campaigns/urls.py url(r'^campaign/create/$', CampaignCreateView.as_view(), name='campaign-create'), My question is, when creating a new campaign, where and how do I pick up the Company pk to populate the Campaign model? What is the most secure and best practice for doing this? -
Translating queries with JOIN and generic relations to ORM
class Business(models.Model): manager = models.ForeignKey(User, on_delete=models.CASCADE) #... class Event(models.Model): business = models.ForeignKey(Business, on_delete=models.CASCADE) text = models.TextField() when = models.DateTimeField() likes = GenericRelation('Like') class Like(models.Model): person = models.ForeignKey(User, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') date = models.DateTimeField(auto_now=True) So I have this structure in models.py. Here's an explanation of important models: Event model has "business" field which links to the certain Business object, which further has "manager" field. Also, Event model has "when" field which describes the date when an event will occur. On the other side, Like model has generic foreign key field which can link to the certain Event object, and also "person" and "date" fields which describe who gave like and when it was given to that event. The goal is now to display on user page all liked events by targeted user, and all events which manager is that user. It can be simply done with this SQL command: SELECT event.* FROM event INNER JOIN business ON (event.business_id = business.id) WHERE ((event.id IN (SELECT object_id FROM 'like' WHERE content_type_pk = 17 AND person_id = 1)) OR business.manager_id = 1); But now the results have to be sorted, by already mentioned "date" in Like … -
Django error relation "auth_user" does not exist using multiple database
I'm working on Django 1.9 and python 3.3 project using multiple databases (different schema in a same postgresql database). When I try to migrate the project for the first time, I'm getting this error Running migrations: Rendering model states... DONE Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying MyApp.0001_initial...Traceback (most recent call last): File "/usr/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: ERROR: relation "auth_user" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/usr/lib/python3.4/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/usr/lib/python3.4/site-packages/django/core/management/__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/usr/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/usr/lib/python3.4/site-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/lib/python3.4/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/lib/python3.4/site-packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File "/usr/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 90, in __exit__ self.execute(sql) File "/usr/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 110, in execute cursor.execute(sql, params) File "/usr/lib/python3.4/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/lib/python3.4/site-packages/django/db/utils.py", … -
Passing user to signal
Django 1.10.2 I would like to save history of changes in different models. In this case for the model FrameDate. If I catch the user in save_frame_date_history(), everything will be ok. But there is no user there. I tried to organize a middleware. But in this case I can't catch the signal. That is the debugger doesn't stop at Debugger 2 breakpoint. This seems to be because of some disorder with threads. If I completely comment out the middleware code, the signal is caught. Could you help me pass the user to the signal. Any way would be ok. If my code is complete garbage, well, let throw it away completely. apps.py from general.utils import get_current_user class GeneralConfig(AppConfig): name = 'general' def ready(self): from frame_date.models import FrameDate # Debugger 1 @receiver(pre_save, sender=FrameDate) def save_frame_date_history(sender, **kwargs): print("Hi") # Debugger 2 utils.py from threading import local _user = local() class CurrentUserMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) _user.value = request.user return response def get_current_user(): try: return _user.value except AttributeError: return None -
How can I insert element to a table in a table of a particular database
I have 2 different database in setting.py. To do select operation I use following statement and is working fine: all_data = Bugs.objects.using('database_one').filter(reporter=user_id, bug_status='resolved', resolution__in=all_resolutions)[:2] But how can I pass the database value to insert an entry in the table of same database. I tried this but this doesn't seems to be working: row_to_be_added = TableName(pr=pr, case=case, comments=comments).using('autotriage').save() Can anyone please help me out here. -
How to import CSV file to django models
I have Django models like this class Revo(models.Model): SuiteName = models.CharField(max_length=255) Test_Case = models.CharField(max_length=255) FileName = models.CharField(max_length=255) Total_Action = models.CharField(max_length=255) Pass = models.CharField(max_length=255) Fail = models.CharField(max_length=255) Exe_Time = models.CharField(max_length=255) Result = models.CharField(max_length=255) create_date = models.DateTimeField(default=datetime.datetime.now) class Meta: verbose_name_plural = "Revo" I have CSV file like this SuiteName,Test Case,FileName,Total Action,Pass,Fail,Exe Time,Result DEMO_TEST_SUITE,Testcase 1,file1,82,0,108,0:27:52,FAIL DEMO_TEST_SUITE,Testcase 2,file2,86,0,108,0:27:52,FAIL DEMO_TEST_SUITE,Testcase 3,file3,820,0,108,0:27:52,FAIL DEMO_TEST_SUITE,Testcase 4,file4,182,0,108,0:27:52,FAIL DEMO_TEST_SUITE,Testcase 5,file5,102,0,108,0:27:52,FAIL DEMO_TEST_SUITE,Testcase 6,file6,111,0,108,0:27:52,FAIL How do I import this csv data into my django models? Also, is there any way to plot graphs out this data directly from database? -
Dynamically render and validate only a subset of model choices in form
What I want: The admin should have the possibility to select multiple allowed payments options for a Product and then at the Booking the user should only see the allowed payment methods, to select a single one. I have thought about a good way of implementing this and two approaches came to my mind: Using a pre-filled choice table with many-to-many relationship Using multiselectfield and setting the choices dynamically. I took the second one. (Good/bad idea?) models.py class Booking(models.Model): payment_method = models.CharField( max_length=10, verbose_name=_('Payment Method'), choices=( ('local', _('Pay on location')), ('bank', _('Bank transfer (See description!)')), ), default='local', ) class Product(models.Model): payment_options = MultiSelectField( max_length=10, verbose_name=_('Payment Options'), choices=( ('local', _('Pay on location')), ('bank', _('Bank transfer')), ), default='local', ) forms.py: class BookingForm(forms.ModelForm): def __init__(self, *args, **kwargs): payment_options = kwargs.pop('payment_options', False) super(BookingForm, self).__init__(*args, **kwargs) if payment_options: self.fields['payment_method'].choices = payment_options Now I think I only need to pass the payent_options kwarg in views.py and I have to adjust the clean method for the form. views.py missing query here paymentform = PaymentForm(payment_options=payment_options) How do I query for the payment_options and produce a choices iterable from the query with the right display name (label)? Django multiselect stores to the database as a CharField of comma-separated values. … -
How to highlight parent when current view is child using django-sitetree
I'm having trouble getting a Parent tree item to highlight when a child view is active using django-sitetree. I'm defining a tree like so: sitetrees = ( tree('mytree', items=[ item('Alerts & Coverage', 'coverage', children=[ item("Latest", 'coverage_archive'), item("Alerts", 'coverage_alerts'), item("Options Weekly", 'coverage_weekly'), item("Article", 'article'), ]), ]), ) When you are viewing an article using the article URL, I'd like "Alerts & Coverage" to be highlighted, but no matter what I try I can't seem to get that to happen. It does happen when you view the other 3 URLs. The obvious difference is that the article URL pattern handles more than just a single URL since it handles every article, but I'm not sure how that impacts things. Here are the relevant URL patterns: url(r'^coverage/$', RedirectView.as_view(pattern_name='coverage_archive'), name='coverage'), url(r'^coverage/latest/$', CoverageArchive.as_view(), name='coverage_archive'), url(r'^coverage/alerts/$', AlertsArchive.as_view(), name='coverage_alerts'), url(r'^coverage/weekly/$', WeeklyArchive.as_view(), name='coverage_weekly'), url(r'^coverage(?P<path>.+?)$', ArticleDetailByPath.as_view(), name='article'),