Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django mptt: Get all descendants of a category
I would like my categories to show all items in that category including descendant categories, so the parent category contains all items for subcategories. I have tried adding this method to my Category class in models.py def get_all_products(self): # To display all items from all subcategories return Product.objects.filter(category__in=Category.objects.get_descendants(include_self=True)) And added this to my template.html, but it does't work. What am I doing wrong? {% for product in instance.get_all_products %} <li>{{ product.product_name }}</li> {% empty %} <li>No items</li> {% endfor %} -
Excel table to django model
I am trying to move from excel based form submissions to a web form, but having a problem to figuring out how to store a summary table (from excel) to a database. Excel table, which is submitted quarterly looks like this: |total|at x|at y|other x|other y| ----+-----+----+----+-------+-------+ LD1 | | | | | | LD2 | | | | | | CD1 | | | | | | CD2 | | | | | | ----+-----+----+----+-------+-------+ and I have a problem converting it into a model. I am thinking to create a choice type (LD1, LD2..) for the first column, iterate over those choices and create 4 forms with the choice already filled. My first question - is it the way to go or is there a better way to store this kind of information? Second - how to create those 4 forms, that have first field as a non input (read-only) field? -
Are there any stable opensource rich text editor packages that are compatible with django-2?
I have tried tinymce. But, it has dependency of communicating to tinymce site for checking plugins. Is there any other completely opensource text editor to be used in django 2? Quill seems not stable for django 2. I need to make changes at serveral places, but still couldn't make it work. -
Having a group admin in django
I am trying to create a django app with a user model and a team model...There is a team admin who can add or remove a user in a group...what permission should the admin be given and how is this made possible? -
Django ChoiceArrayField: how to fake an input field
In the context of Django2.0 and the admin part, if the database backend is PostgreSQL; Is it possible to add an extra field in the model that doesn't exist in the database ? More specifically, if in PostgreSQL there is field as_set of type array and I am not in a position of knowing the options for filling that field, in other words, I cannot have a tuple with the options I am thinking of adding an extra field called as_set_text that is of type CharField, and when the user enters a value using the Django admin web app, I would like to validate the value, make it a list, and save it as such (postgresql array) in the as_set column, and ignore the fake as_set_text field. The mapping of a PostgreSQL array in Django terms is like: class ChoiceArrayField(ArrayField): def formfield(self, **kwargs): defaults = { 'form_class': forms.MultipleChoiceField, 'choices': self.base_field.choices, } defaults.update(kwargs) return super(ArrayField, self).formfield(**defaults) Could you please advise how I could possible achieve that ? -
How to implement access control on media files using Django and S3
This seems like a simple requirement, but I just can't figure it out. I have a Django app running on Heroku and I'm using S3 for file storage I've set up the media URL to use a private S3 bucket using django-storages (specifically S3BotoStorage) User uploaded files are saved through a model to my private S3 bucket. To give a user access to the file, I use the url() method that generates a link that's valid for 1 hour. That all works great, but suppose I want to add images to the site that should only be visible to logged in users. These files are not tied to a model. How can I achieve that? I can think of 2 methods: Create another S3 bucket that's publicly accessible, but give the files long very hard to guess names. Not ideal, but it could work Serve the images through a Django view. Potentially this view just redirect to where it is stored on S3 using the url() method as explained above -
Django ChoiceArrayField: how to set a default value
In the context of Django2.0 and the admin part, if the database backend is PostgreSQL; Is it possible to specify "NULL" as the column of a field by default ? For example, class ChoiceArrayField(ArrayField): def formfield(self, **kwargs): defaults = { 'form_class': forms.MultipleChoiceField, 'choices': self.base_field.choices, } defaults.update(kwargs) return super(ArrayField, self).formfield(**defaults) And the model field is: capabilities = ChoiceArrayField(base_field=models.CharField(max_length=64, choices=PEER_CAPS, blank=True, null=True), default=list) where PEER_CAPS = ( ("", "None"), ("blackholing", "blackholing"), ("irrguard", "irrguard"), ) Right now, the default is "None", but it saves the value "" because it needs an iterable, so I cannot have a variable with value equal to None. This is just fine for the admin web app. BUT before I save it to the database I would like to set capabilities to be NULL or an empty list (since the corresponding table in PostgreSQL is an array) Is that possible ? -
Django - compare a matching column from two Querysets/models?
I have two models. sitesubnets and devicesubnets. I would like to compare the two models so I can create two lists. one list will have matching subnets one will have non matching subnets across them I have tried using set difference but as they are different models I don think it works test queries: sitesubnet_data = SiteSubnets.objects.filter(site_id=site_id) devicesubnet_data = DeviceSubnets.objects.filter(device_id=device_id) data = set(sitesubnet_data).difference(set(devicesubnet_data)) when I compare sitesubnet_data with data, they are the same my models: class SiteSubnets(models.Model): site = models.ForeignKey(SiteData, on_delete=models.CASCADE) subnet = models.ForeignKey(Subnets, on_delete=models.CASCADE) class Meta: verbose_name = "Site Subnets" verbose_name_plural = "Site Subnets" unique_together = ('site', 'subnet',) class DeviceSubnets(models.Model): device = models.ForeignKey(DeviceData, on_delete=models.CASCADE) subnet = models.ForeignKey(Subnets, on_delete=models.CASCADE) class Meta: verbose_name = "Device Subnets" verbose_name_plural = "Device Subnets" unique_together = ('device', 'subnet',) -
cannot use custom related_widget_wrapper.html
I get TemplateDoesNotExist error if I use custom related_widget_wrapper.html. What I did is, I created a folder called widgets inside templates/dashboard directory and add a related_widget_wrapper.html file. This way I got the mentioned error and what strange thing I found is django.template.loaders.filesystem.Loader: /Users/.virtualenvs/furniture/lib/python3.6/site-packages/django/forms/templates/dashboard/widgets/related_widget_wrapper.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/.virtualenvs/furniture/lib/python3.6/site-packages/django/contrib/admin/templates/dashboard/widgets/related_widget_wrapper.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/.virtualenvs/furniture/lib/python3.6/site-packages/django/contrib/auth/templates/dashboard/widgets/related_widget_wrapper.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/.virtualenvs/furniture/lib/python3.6/site-packages/django_tables2/templates/dashboard/widgets/related_widget_wrapper.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/.virtualenvs/furniture/lib/python3.6/site-packages/haystack/templates/dashboard/widgets/related_widget_wrapper.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/.virtualenvs/furniture/lib/python3.6/site-packages/treebeard/templates/dashboard/widgets/related_widget_wrapper.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/.virtualenvs/furniture/lib/python3.6/site-packages/versatileimagefield/templates/dashboard/widgets/related_widget_wrapper.html (Source does not exist) it is not searching inside my apps. I mean it should search in my project templates. Am i missing something or what have i done wrong? class RelatedFieldWidgetWrapper(Widget): """ This class is a wrapper to a given widget to add the add icon for the dashboard. """ template_name = 'dashboard/widgets/related_widget_wrapper.html' # this throws an error # template_name = 'admin/widgets//related_widget_wrapper.html' this works though IS_POPUP_VALUE = '1' IS_POPUP_VAR = '_popup' TO_FIELD_VAR = '_to_field' def __init__(self, widget, rel): self.needs_multipart_form = widget.needs_multipart_form self.attrs = widget.attrs self.choices = widget.choices self.widget = widget self.rel = rel def __deepcopy__(self, memo): obj = copy.copy(self) obj.widget = copy.deepcopy(self.widget, memo) obj.attrs = self.widget.attrs memo[id(self)] = obj return obj @property def is_hidden(self): return self.widget.is_hidden @property def media(self): return … -
OperationalError no such table: categories_article
When i enter django admin interface and click "Articles" i got Error: OperationalError at /admin/categories/article/ no such table: categories_article Request Method: GET Request URL: http://127.0.0.1:8000/admin/categories/article/ Django Version: 1.9 Exception Type: OperationalError Exception Value: no such table: categories_article Exception Location: \Envs\django19\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 323 Python Executable: \Envs\django19\Scripts\python.exe Python Version: 3.6.3 admin.py from django.contrib import admin from .models import Category, Article admin.site.register(Category) admin.site.register(Article) models.py from django.db import models class Category(models.Model): category_name = models.CharField(max_length=200) class Article(models.Model): title = models.CharField(max_length=200) text = models.TextField(max_length=20000) What should i do to create new "Article" object in django admin? -
How can I hide a form after submission?
I was wondering how can I hide a form after submission. I tried something with javascript, but I keep getting message from the form that no file was chosen. <script type="text/Javascript"> $('input[type="submit"]').click(function () { $(this).parents('#files').remove(); }); </script> <form id="files" method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> -
Django bitcoin payment module Decimal JSON Serializable Error
I am working on a python django project where users send bitcoins to external addresses. this is how the payment module looks like. I have tried many suggestions posted here with little help. Below is my code. I would appreciate any third eye who could help me troubleshot this error. import decimal as Decimal import bitcoinrpc class Withdrawal(models.Model): amount = models.OneToOneField("Amount", null=True) payment = models.OneToOneField(Payment, null=True, blank=True) to = models.CharField(max_length=35, null=True, blank=True) account = models.ForeignKey(Account) complete = models.BooleanField(default=False) txid = models.CharField(max_length=64, blank=True, null=True) def __str__(self): return u"{} from {} to {}".format(self.amount, self.account, self.to) def alert(self): """Sends email to all staff users about failed withdrawal""" for u in User.objects.filter(is_superuser=True): if u.email != u'': message = "Withdrawal {}, by {}, for {} " \ "has failed due to an insufficient balance." message = message.format(self.pk, self.account.user.email, self.amount) send_mail('FAILED WITHDRAWAL', message, settings.DEFAULT_FROM_EMAIL, [u.email], fail_silently=False) raise Exception("Insufficient funds") def send(self): """Sends payment on the blockchain, or if unable calls self.alert""" if self.complete: raise Exception("Sorry, Can't send a completed payment") s = get_server() fee = Decimal(str(PAYMENTS_FEE)) final_amount = self.amount.base_amt - fee inputs = s.proxy.listunspent(0, 9999999) total = sum([t['amount'] for t in inputs]) if total 0: outputs[get_change()] = Decimal(total) -final_amount - fee raw = s.createrawtransaction(inputs, outputs) s.walletpassphrase(PAYMENTS_PASSPHRASE, … -
not parsing jinja in javascript appended with jquery
I am using Django. I want to append a big and complex form and I would prefer keep it in a separate file (requerimento_cartorio.html). So, I have the main html: projeto.html <div id="form_requerimento" style="display:none;"> <script type="text/javascript"> $(function () { $.get("{% static 'templates/requerimento_cartorio.html' %}", function (data) { $("#form_requerimento").append(data); }); }); </script> </div> The form I want to append contains Jinja (requerimento_cartorio.html): <form action="/your-name/" method="post"> <div class="form-group"> <h2 for="nome">Requerimento</h2> </div> <p>Eu, <input value="{{ representante.nome }}"/>"</p> <p style="height:20px;"></p> <button onclick="pdf_form_requerimento()" class="btn btn-default">Imprimir PDF</button> <button type="submit" class="btn btn-default">Salvar</button> When I do this way, of course, it treats the form as static and do not parse the jinja code. How to append a piece of html that is parsed by jinja before it is inserted, ie, it is not treated as a static piece? -
Using forms to interact with models that contain foreign keys
So I'm trying to do something really simple but I've been trying for what seems like ages and simply can't find the answer by myself. I'm trying to create a form to add a devicetype. In that form there's supposed to be a dropdown menu of existing vendors in the database. The only problem is that I can't seem to display the name of the vendor in the form. Instead it shows the instance name. "Vendors object(1)", "Vendors object(2)". How do I change it to display the name? here are my models: class Vendors(models.Model): name = models.CharField(max_length=30) class DeviceTypes(models.Model): name = models.CharField(max_length=30) vendor = models.ForeignKey(Vendors, on_delete=models.PROTECT) And this is my form: class AddDeviceTypeForm(forms.ModelForm): """ Form to add a devicetype to database """ class Meta: model = DeviceTypes fields = ['name', 'vendor'] This is my view: def addDeviceType(request): """ view shows and processes form to add a device type """ form = AddDeviceTypeForm() args = { 'form': form } return render(request, 'cmdb/addDeviceType.html', args) And I'm displaying the form with: <form action="" method="post"> {% csrf_token %} {{form}} <input type="submit" value="Create" /> </form> -
Getting error while running python manage.py runserver command
I followed the simple steps of creating Django project using https://docs.djangoproject.com/en/2.0/intro/tutorial01/ I have created project mysite, it has got manage.py & child folder named mysite which has init.py, settings.py, urls.py and wsgi.py. Now, when I run server command python manage.py runserver, I get below error, its coming from exception part of manage.py file ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget t o activate a virtual environment? I have installed python, django, pip in below path & also set PATH: Env variables C:\Users\jeevan\AppData\Local\Programs\Python\Python36\Lib\site-packages\mysite -
SQLite to PostgreSQL issue [wagtail tutorial]
It's the first time for me to deploy my wagtail app(and I'm very proud of that :) ) to heroku. I'm following this tutorial (see link below): https://wagtail.io/blog/deploying-wagtail-heroku/ But I have encountered one trouble during this tutorial: It's when I change the database between sqlite to PostgreSQL. There is the trouble : django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"? I am on mac os 10.13.3. Python with Anaconda. There is what I have done : Changed the default port to 5433 in the base.py file but it doesn't work.(like this tutorial : https://vix.digital/insights/deploying-wagtail-production/) Tried to find and modify the .conf file but i didn't find it... Before this one, there no previous postgresql installed. I do not have any postgres server running (I don't know how I can check it but I am stuck at the first step of this tutorial...). Thanks for your help! :) The whole terminal response The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/Users/darkbook/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/darkbook/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line … -
How to edit a variable inside the model class in django
I have a model class as shown below: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) #basket = {'list':['1']} search_list = {} shopping_basket = {} I want to be able to add to the search_list dictionary within views. I'm currently doing this in views: request.user.search_list['results'] = [1, 2, 3, 4, 5] But it returns with: 'User' object has no attribute 'search_list' Is there a way where I can add to the dictionary within views. -
Django filtering twice nested instances
Here is an example of my models: class Model1(models.Model): name = models.CharField(max_length=255) class Model2(models.Model): name = models.CharField(max_length=255) model1 = models.ManyToManyField(Model1, on_delete=models.CASCADE, related_name='model2') class Model3(models.Model): name = models.CharField(max_length=255) active = models.BooleanField(default=True) model2 = models.ManyToManyField(Model3, on_delete=models.CASCADE, related_name='model3') I am trying to find all Model1 instances which have Model2 instances which have Model1 instances who has active field = False Model1.object.filter(model2__model1__active=False) But I am getting all instances of model3 even if their field active=True -
Upload files only for a specific model field in Django
I have a Course model and StudentFileUpload model. For each course I have a generated slug page and that page is only available to enrolled students of the course. I just wanted to add a file upload form that will upload the files only for the course that matches the course slug. How do I achieve that ? form = StudentFileForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): form.save() redirect('courses:courses') else: form = StudentFileForm() class StudentFileForm(forms.ModelForm): class Meta: model = StudentFileUpload fields = ('files',) class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default=None) name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=150, unique=True) class StudentFileUpload(models.Model): comment = models.CharField(max_length=100) files = models.FileField(upload_to='student_files', null=True, blank=True) course = models.ForeignKey('Course', related_name='files', on_delete=None, default=None) -
Add "Save as new" button to Django foreign object edit popup
In Django we have save_as parameter for ModelAdmin, that enables "Save as new" button on the admin's site edit page of some object. But when the object (Model1 instance) is in relations with other model (Model2) by default, and I want to edit Model2 instance in following way: take default for the current relation (depends on Model2 instance fields) Model1 instance and edit some of its fields, I click edit button and the popup appears, where I can change some fields, but can't save that object as new, so I have 2 option: corrupt the default object or copy-paste each field of that related object into "Add new" popup. I want to add "Save as new" button into Edit popup. Any thoughts on how to do it? -
django-allauth multiple signup form for difference user type
I have already searched all the questions in stackoverflow. However, there is no one clearly answered this question yet. My application contain 2 user types, I added 2 user profiles. Anyone can show me how to make 2 signup form? Since I'm new to django, I have already tried a few solutions but none of them is work... I'm using python3.4 with django 2.0.2. Thanks!! -
Authenticate user in Selenium test
I'm testing user authentication in Django project with Selenium webdriver, and created a test: class EditorBlogTest(StaticLiveServerTestCase): def setUp(self): self.browser = webdriver.Chrome() def tearDown(self): self.browser.quit() def create_session_store(self): user = User.objects.create(email='a@b.com', username='TestUser', is_staff=True) engine = import_module(settings.SESSION_ENGINE) store = engine.SessionStore() store[SESSION_KEY] = user.pk store[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0] store.save() return store def test_user_authenticated(self): store = self.create_session_store() self.browser.get(self.live_server_url + '/dashboard/') # to create initial cookie self.browser.add_cookie({ 'name': settings.SESSION_COOKIE_NAME, 'value': store.session_key, }) self.browser.get(self.live_server_url + '/dashboard/blog/add/') hello_box = self.browser.find_element_by_id('hello') self.assertEqual('Hello, TestUser', hello_box.text) in template there is a line: <li id="hello">Hello, {{ request.user }}</li> But the test failed: Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_session_creation (functional_tests.dashboard.test_blog.EditorBlogTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/django/my_project/functional_tests/dashboard/test_blog.py", line 39, in test_session_creation self.assertEqual('Hello, TestUser', hello_box.text) AssertionError: 'Hello, TestUser' != 'Hello, AnonymousUser' - Hello, TestUser + Hello, AnonymousUser ---------------------------------------------------------------------- Ran 1 test in 2.406s FAILED (failures=1) Destroying test database for alias 'default'... Does anyone have an idea what's wrong with it? -
How to aliase model fields in django view?
I have a view function which retrieves some query sets. my need is how to get specific columns and alias those column to another name and then serialise the resulting query set to Json. sell_date = year_str+'-'+request.POST.get('sell_date') sell_data_dict = UsDailyStock.objects.extra(select={'sell_close': 'close', 'sell_date': 'date'}).values('sell_close' ,'sell_date').filter(ticker=request.POST.get('Ticker')).filter(date__lte=sell_date).order_by('-date')[:1] sell_data = serializers.serialize('json', sell_data_dict, fields=('close', 'date')) i could alias. but when i serialise it throws the error. -
Query to extended user model returning error
I am receiving an error when making the following query: Election.objects.all().exclude(candidate__UserID=request.user).filter(Gender=request.user.Profile.Gender).filter(CandidateReg=True) The problem is described in this error: Traceback (most recent call last): File "/home/elections/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/elections/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/elections/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/elections/elections-real/elections/views.py", line 139, in add_candidate elections = Election.objects.all().exclude(candidate__UserID=request.user).filter(Gender=request.user.Profile.Gender).filter(CandidateReg=True) File "/home/elections/venv/lib/python3.6/site-packages/django/utils/functional.py", line 239, in inner return func(self._wrapped, *args) AttributeError: 'User' object has no attribute 'Profile' It appears to show the issue is with querying my extended user model: class Profile(models.Model): UserID = models.OneToOneField(User, on_delete=models.CASCADE) GENDERS = (("M","Male"), ("F","Female")) Gender = models.CharField(max_length=1, choices=GENDERS) UserTypeID = models.ForeignKey(UserType, on_delete=models.PROTECT, blank=True, null=True) EmailConfirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(UserID=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() How do I correctly reference the Gender attribute of the logged-in user's profile if not the way outlined above? -
how to pass a file's url through Serializer
I created model like this: class Artist (models.Model): name = models.CharField(max_length=300) image=models.FileField() followers=models.IntegerField(default=0) with an image file in it and now, i want to pass every model's image url through a Serializer and post it as a json my Serializer is like this now: class ArtistSerializer (serializers.ModelSerializer): class Meta: model = Artist fields = ('name' , ) but i don't know how to do that. any suggestions?