Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serialize queryset based on individual field values using Django Rest Framework
Goal If an object has revealed=true it serializes into: { "id":1, "info":"top secret info", "revealed":true } If an object has revealed=false it omits the info field: { "id":2, "revealed":false } So for a queryset of objects: [ { "id":1, "info":"top secret info 1", "revealed":true }, { "id":2, "revealed":false }, { "id":3, "info":"top secret info 3", "revealed":true } ] Is it possible to achieve this inside of a Django Rest Framework Model Serializer class? class InfoSerializer(serializers.ModelSerializer): class Meta: model = Info fields = ('id', 'info', 'revealed') Background The DRF docs discuss some advanced serializer usage, and this other post dives into an example. However it doesn't seem to cover this particular issue. Ideas A hacky solution would be to iterate over the serialized data afterwards, and remove the info field for every object that has revealed=false. However 1) it involves an extra loop and 2) would need to be implemented everywhere the data is serialized. -
Passing HTML Template Multiple Checkboxes to a new Django form
I'm knew to Django and i'm still learning the ropes. I have the following template, that allows the user to select multiple check boxes. <div class="container"> <div class="row"> <div class="col"> <h3>Financial</h3> <ul> {% for app in fingrouplist %} <li><input type="checkbox" name="request_reports" value ="{{app.report_id}}" > {{ app.report_name_sc }}</li> {% endfor %} </ul> </div> <div class="col"> How would I pass the result of my checkboxes on report_id to a new form and have it pre-populated with these items after hitting my input/submit button. </br></br> <input class="btn btn-primary" type="button" value="Request Access"> </div> Below is my view and as you'll see I have a lot more grouplists that all use report_id and I want all them to be passed to the form that is generated based on these checkboxes. def profile(request): owner = User.objects.get (formattedusername=request.user.formattedusername) reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername, active = 1).values('report_name_sc') reportIds = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_id', flat=True) reportaccess = QvReportList.objects.filter(report_id__in= reportIds).values_list('report_name_sc', flat = True) reportGroups = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_group_id', flat=True) reportlist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).exclude(active=0) allreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 100) bhreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 200) cereportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 500) finreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 600) careportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 800) pireportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1100) screportgrouplist = … -
Django form with inputs populated from database
I have a simple Django model structure with Products and Orders, linked by an intermediary table that determines the quantity of each product within a given order: models.py: class Product(models.Model): name = models.CharField() class Order(models.Model): id = models.IntegerField() products = models.ManyToManyField(Product, through='OrderProduct') class OrderProduct(models.Model): order=models.ForeignKey(Order, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField() I'd like to design a form in my forms.py file that 1) pulls a list of every product in the database; 2) gives the user the option to adjust the quantity of each product ordered (e.g., in a CharField input), and 3) creates new Order and OrderProduct objects that store a record of the quantity of each Product ordered by the user. However, I can't figure out a good way to create a form that will automatically pull all Products from the database and add fields to represent the quantity ordered of the given Product. Ideally the result would look something like this, but coded automatically: forms.py: class OrderForm(forms.Form): product_1_quantity = forms.IntegerField() product_2_quantity = forms.IntegerField() product_3_quantity = forms.IntegerField() ....etc., for each product. What's the best way to do this? Does it involve a 'for' loop that creates a new field for each product found in the database? -
Ajax function is not getting the id
I am trying to fix this problem for about 3 days and can not do it. I need to take the id from which is auto incremented in the django. Can you guys help me please. function add_product(){ event.preventDefault(); var name = $("#name").val(); var price = $("#price").val(); var description = $("#description").val(); var dataString = [name, description, price]; var n = dataString.length; $.ajax({ type: "POST", url: "add/", data: { csrfmiddlewaretoken: '{{ csrf_token }}', name: $('#name').val(), email: $('#price').val(), description: $('#description').val(), }, dataType: "json", success: function(){ var button = $('<button class="reo" onclick="delete_product('+ I need to take the id from the database+')" id="my" value="">Delete</button>'); var row = $('<tr>'); for(var i = 0; i < n; i++) { row.append($('<td>').html(dataString[i])); } $('#tableForm').append(row); $('#tableForm').append(button); } }); }; -
Django query many2any self referenced
Currently I have this model: class Group(models.Model): dependency = models.ManyToManyField('self') name = models.TextField() Django create a table with this fields: id from_group_id to_group_id I want to get all rows of model Group that are not in from_group_id. In short I want to get the parent groups -
ValidationError on related model created in inline admin causes 500
I'm creating a one-to-one model to extend the functionality of an existing model type, but I want it to only allow creating the extension model in certain cases. I enforce this constraint by throwing a ValidationError in the full_clean on the new Extended model. This works great when I create Extended models using Extended's ModelAdmin directly (it highlights the a field if it's the wrong type), but when I use StackedInline to inline Extended creation in As ModelAdmin, and A is the wrong type, the form fails to catch the ValidationError and I get the message A server error occurred. Please contact the administrator. This is how I have the models set up: # models.py from django.db import models class A(models.Model): type = models.IntegerField(...) class Extended(models.Model) a = models.OneToOneField(A) def clean_fields(self, **kwargs): if self.a.type != 3: raise ValidationError({'a': ["a must be of type 3"]}) def save(self, *args, **kwargs): self.full_clean() super(Extended, self).save(*args, **kwargs) # admin.py from django.contrib import admin class ExtendedInline(admin.StackedInline): model = Extended @admin.register(A) class AAdmin(admin.ModelAdmin): inlines = (ExtendedInline,) The full traceback: Traceback (most recent call last): File "/usr/local/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/usr/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/usr/local/lib/python2.7/site-packages/whitenoise/base.py", line 66, … -
How to find Postgres version from Django?
I want to know version of the default Postgres database. How to find it using Django? -
Django on Nginx help needed
I am trying to deploy my website to aws ec2. It's in python/django and I want to learn how to deploy websites myself. I had some issues with aws's EBS so first I'd like to know how to do that manually. I decided to use gunicorn and nginx for this. I can run the website using gunicorn on a virtual env and I created the following script in /home/ec2-user/gunicorn_start.bash: #!/bin/bash NAME="davidbiencom" # Name of the application DJANGODIR=/home/ec2-user/davidbien # Django project directory SOCKFILE=/home/ec2-user/virtual/run/gunicorn.sock USER=ec2-user GROUP=ec2-user NUM_WORKERS=3 DJANGO_SETTINGS_MODULE=davidbiencom.settings DJANGO_WSGI_MODULE=davidbiencom.wsgi echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /home/ec2-user/virtual/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn # Programs meant to be run under supervisor should not daemonize themselves (do$ exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- This runs fine I believe as there are no errors. Next I install nginx and start the service. I confirm it's running as I get the welcome page. Next I do the following: Go to /etc/nginx/nginx.conf and add the following to … -
Django-Python3-LDAP Direct Bind
Is it possible to direct bind to AD with django-python3-ldap? I know search and bind is possible, but this requires someone's AD password to be accessible to other members of the team (i.e. in an environment variable on the server where the Django app is hosted). -
Django: Changed AUTH_USER_MODEL and now getting IntegryErrors when updating other model that references it
I'm using the django-hitcount app on my web app to count hits on some pages, and the hit model references the AUTH_USER_MODEL on a foreign key (the settings variable that defines which model is used as user model). When I started, my webapp wasn't using login, so django-hitcount defaulted to the default user model from Django when I ran the migrations. But now, I've created a custom user model, and the app is throwing integrity errors because, as far as I can tell, the hitcount app ForeignKey is still pointing to the default django user model. IntegrityError at /category/28/22 (1452, ‘Cannot add or update a child row: a foreign key constraint fails (`detdb`.`hitcount_hit`, CONSTRAINT `hitcount_hit_user_id_10387956e3370b97_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`))’) Is there any way I can update the foreign key without losing all my hit instances? (using Django 1.11 and MySQL) -
How can I set up Django Crontab in Docker container?
I have in management/commands file myfile.py and I set it up in this way TIME_ZONE = 'UTC' CRONJOBS = [ ('21 22 * * *', 'django.core.management.call_command', ['myfile']), ] I have added django-crontab to the requirements.txt and 'django_crontab' in INSTALLED_APPS. This file should add data to the PostgreSQL database however it doesn't work. Any ideas why? -
How to change Azure Git CI deployment default python version
Azure only supports Python version 2.7 and 3.4 in the Application settings, and I installed newer Python 3.6.2 via App Service for my django application. I followed the setup for continuous integration with Azure & GitHub and found out that deployment failed when Azure is running deployment command. Below is part of the log that shows Azure decided to use default 2.7 even tho I specified to use 3.6.2 in web.config file Detected requirements.txt. You can skip Python specific steps with a .skipPythonDeployment file. Detecting Python runtime from site configuration Detected python-2.7 Creating python-2.7 virtual environment. Azure will determine the version of Python to use for its virtual environment with the following priority: version specified in runtime.txt in the root folder version specified by Python setting in the web app configuration (the Settings > Application Settings blade for your web app in the Azure Portal) python-2.7 is the default if none of the above are specified I can't specify the version using runtime.txt since 3.6.2 is not a valid value for the content. It looks like Azure ignored my web.config and just jump to use 2.7 as the default since none of the above are specified. As of now, I … -
Django - Custom Authentication & correct way to user Managers
This my first post here, so exciting. I've hacked my way to getting my code to work, but I'm pretty sure I'm not doing it as it was intended. My constraint is I want to have separate DB and UI layers, so I have all the DB-logic encapsulated in SPs/functions that are called from Django's view layer. I tried doing this using the included managers, but kept getting this error: Manager isn't accessible via %s instances" % cls.name) So, I just removed the manager sub-class and kept going. It works with some extra hacks, but it doesn't feel right. My question -- how do I get my code to work, but still inheriting the stuff from the appropriate managers (i.e. BaseUserManager). Here's the code: class MyUserManager(BaseUserManager): # Create new user def create_user(self, password, usertype = None, firstname = None, lastname = None, phonenumber = None, emailaddress = None): user = MyUser( # TO-DO: Replace MyUser with "get_user_model" reference userid=None, usertype=usertype, firstname=firstname, lastname=lastname, phonenumber=phonenumber, emailaddress=emailaddress ) # Hash and save password user.set_password(password) # Save user data user.save() return user def upsertUser(self, myUser): return saveDBData('SP_IGLUpsertUser', ( myUser.userid, myUser.usertype, myUser.firstname, myUser.lastname, myUser.phonenumber, myUser.emailaddress, myUser.password, myUser.last_login, None, ) ) Create custom base user class … -
Python sorted: properly groups categories, but doesn't alphabetize
I am chaining multiple querysets together and then sorting them by a common field (category). It succeeds at placing everything from the same category next to each other, but the categories themselves are not sorted alphabetically. Any ideas? from itertools import chain from operator import attrgetter downloadable_forms = DownloadableForm.objects.all() email_forms = EmailForm.objects.all() linked_forms = LinkedForm.objects.all() all_forms = sorted(chain(downloadable_forms, email_forms, linked_forms), key=attrgetter('category', 'name')) Here is an idea of what it returns: C Category A form, B form, C form A Category A form, B form, C form B Category A form, B form, C form -
Eclipse has set a directory as derived and I cannot turn it off
I have a django project in eclipse, and I am using git as the repository. I have looked online for an answer, and I can't find one. I have suddenly discovered that one entire directory of my templates has been marked as derived, and it seems that new files in the directory are not being committed/pushed to the repository. I have opened the properties window for this directory several times, and unchecked the derived checkbox, clicked save, and the change is not saved. The next time I open the properties for this directory, it is marked as derived. With even brand new files I get the warning that the file is derived, do I want to edit it. And the files do not appear in git. I need to turn this off. It is still there when I restart eclipse. These are normal django template files, they are not derived from anything, and I need them in the project. What am I doing wrong? Eclipse Neon version 4.6.0 Ubuntu 14.04 Thanks in advance for any help. -
Django - PasswordResetView always defaulting to the admin page
I'm using Django's default password reset system, but no matter what I do, I can't get Django to load my custom HTML templates. It always goes to the default admin page. I have tried using the default folder location and default files names. Placing 'password_reset_form.html' and 'password_reset_email.html' into the registration folder. url(r'^password_reset/$', auth_views.PasswordResetView.as_view(), name='reset_password'), I have also tried using a custom folder location and custom HTML names. url(r'^password_reset/$', auth_views.PasswordResetView.as_view(template_name='change_password/password_reset.html', success_url='../password_reset_done/', email_template_name='change_password/password_reset_email.html'), name='reset_password'), Here is my HTML tag: <p><a href="{% url 'reset_password' %}">Forgot Password?</a></p> Whatever I try Django always loads the default admin page for password reset. Any tips? EDIT: settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['bungol/templates', './templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] tree ├───bungol │ ├───accounts │ │ ├───migrations │ │ │ └───__pycache__ │ │ ├───templates │ │ │ ├───accounts │ │ │ ├───change_password │ │ │ ├───registration │ │ │ └───teams │ │ ├───templatetags │ │ │ └───__pycache__ │ │ └───__pycache__ │ ├───accountsext │ │ └───migrations │ ├───coresite │ │ ├───migrations │ │ │ └───__pycache__ │ │ ├───templates │ │ └───__pycache__ │ ├───databases │ │ ├───migrations │ │ │ └───__pycache__ │ │ ├───templates │ │ │ └───databases │ … -
Bot didn't return an HttpResponse object. It returned None instead
I write bot for the telegram with telebot and Django . And when i running him on the server and watch the full log, I have next text: Internal Server Error: /bot/ Traceback (most recent call last): File "/home/fishbot/env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/fishbot/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 198, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view bot.views.bot didn't return an HttpResponse object. It returned None instead. Somebody help me? P.S i can not attach telebot on the tags 0: -
Google App Engine Django WSGI Error
System Info: Windows 10 Running VMWare Player 12 Unbuntu 16.04 Python 2.7 Django 1.2. I have installed Google App Engine Python SDK on VMWare Player 12 running Ubuntu. Every time I run dev_appserver.py I receive this message ImportError: No module named django.core.handlers.wsgi. I can load the admin page for Django but cannot load the app. I have intstalled apache2 and mod_wsgi according to other stackoverflow posted solutions but I am still getting the same error. Would be a problem with the VM? Thanks in advance! -
Using unaccent with SearchVector and SearchQuery in Django
I have installed UnaccentExtension in Django but I'm having problems using it with this search: vector = SearchVector('title__unaccent', 'abstract__unaccent') query = SearchQuery(word) | SearchQuery(word2) files = Doc.objects.annotate(rank=SearchRank(vector, query)).order_by('-rank') This is the error: Cannot resolve keyword 'unaccent' into field. Join on 'title' not permitted. Whit a simplest search it works fine: Doc.objects.filter(title__unaccent=word) So, what am I doing wrong? -
Django not working after moving directory. Do I have a path/Python installation issue?
Background: I installed Python 3.5.2 on my Mac (which already contained 2.7.10) and have been apparently running the two installations side-by-side without any apparent issues. Everything works fine until I move the project folder somewhere else, and then when I try to do anything I get the following error: Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No module named django.core.management My normal setup workflow is as follows: Install a virtual environment in the directory containing the Django project folder (not the directory containing manage.py - one level up from that) with python3 -m venv <venv-name> Activate the virtual environment and install Django, Pillow, whatever I need for the project. I know I'm missing something because I thought the way virtual environments worked was that you installed them locally and then as long as all of that accompanied your project folder, everything would be a-okay. But everything stops working when I move the directory, and if I move it back it works again. Can anyone tell me what kind of issue I'm dealing with here based on this? Is this just normal behavior and I just need to get used to not … -
Django admin - verbose_name has an object referenced
I have extended the user model with this: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) biography = models.TextField(max_length=500, blank=True, default='Tell us about you...') tagline = models.CharField(max_length=200, blank=True, default=' ') And appended the admin.py: class UserProfileInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'User Profile' verbose_name = 'Additional Info' # Define a new User admin class UserAdmin(BaseUserAdmin): inlines = (UserProfileInline, ) # Re-register UserAdmin admin.site.unregister(User) admin.site.register(User, UserAdmin) # Register your models here. admin.site.register(Product) In the admin panel where verbose_name is being displayed, it is showing Additional Info: UserProfile object - not sure where UserProfile object is coming from. I've attached a screenshot below: Is there a way to remove that, other using CSS to hide it? -
Django faced with Object of type 'ObjectId' is not JSON serializable
I'm working on Django with MongoDB, I have the simple query to find a Doc by _id but faced with Object of type 'ObjectId' is not JSON serializable , db = connection[type] ads = db['ads'] all_items = ads.find().count() item = ads.find_one_and_update({"_id": ObjectId("5a059d60418312cf33f448f5")},{"$set": {"visited": "0"}}) return JsonResponse({'type':type}) But when I tried it outside the Django it works correctly without any error, I put them in test.py and run it with python3 test.py db = connection['mytype'] ads = db['ads'] item = ads.find_one_and_update({"_id": ObjectId('5a059d60418312cf33f448f5')},{"$set": {"visited": "1"}}) note I run the Django server with python3 manage.py runserver. It seems some wired, why this happens and how can I resolve it? -
Bootstrap col won't align horizontally after putting in my code
I have everything imported in my header on the base.html (site developed with django). I copied and pasted the example code from the bootstrap docs for the cols here: <div class="container"> <div class="row"> <div class="col"> 1 of 3 </div> <div class="col-6"> 2 of 3 (wider) </div> <div class="col"> 3 of 3 </div> </div> <div class="row"> <div class="col"> 1 of 3 </div> <div class="col-5"> 2 of 3 (wider) </div> <div class="col"> 3 of 3 </div> </div> </div> This works fine, as the divs with col classes are aligned in the row properly. However, when I put in the HTML that I am working with the divs with col classes no longer align properly as now the sidebar in not aligning on the right of the main content as it should be... it also seems to be inside of the the cards... Here is my actual code. Please excuse the weird template tags/if statements those have to do with Django and everything is in a container div but that's taken care of with Django as well so you can't see that here: <div class="row"> <div class="col-8"> {% if user.is_authenticated %} <a class="" href="{% url 'feed:new_post' %}">New Post</a> {% endif %} {% for … -
Django - SystemCheckError: System check identified some issues:
I wanted to create user models but I could not understand if I got a terminal error After making the necessary adjustments, I made migrate but I got an error. When defining the models I wanted to use the standard model of django and translate it into models I wanted by playing it. but I got an error that I did not know why. I can not find the cause of this error when I look at it. project name sites apps name users models.py # Django from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin ) # Local Django from users.managers import UserManager def set_user_images_upload_path(instance, filename): return '/'.join([ 'users', 'user_%d' % instance.id, 'images', filename ]) class User(AbstractBaseUser, PermissionsMixin): # Base email = models.EmailField( verbose_name=_('Email'), max_length=255, unique=True ) first_name = models.CharField(verbose_name=_('First Name'), max_length=50) last_name = models.CharField(verbose_name=_('Last Name'), max_length=50) # Permissions is_active = models.BooleanField(verbose_name=_('Active'), default=True) is_staff = models.BooleanField(verbose_name=_('Staff'), default=False) is_verified = models.BooleanField(verbose_name=_('Verified'), default=False) # Image image = models.ImageField( verbose_name=_('Image'), upload_to=set_user_images_upload_path, null=True, blank=True ) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] class Meta: verbose_name = _('User') verbose_name_plural = _('Users') def __str__(self): return self.get_full_name() def get_full_name(self): return '{first_name} … -
Django templatetags seem to make the prefetch_related useless
When I add a filter based on a template tag ("provinceonly") to my Django template, debug-toolbar indicates that the database is hit 115 time instead of 5 previously. Is it a well-known issue ? I cant' find a way to prefetch correctly the required information to reduce the number of hits. Is there something I can do about it ? Template: {% for country in allcountries %} {% for province in country.fkcountrysecondaries.all|provinceonly %} {{ province.basicname }} {% for populatedplace in province.fkprovince.fkprovincesecondaries.all %} {{ populatedplace.basicname }} {% endfor %} {% endfor %} {% endfor %} Template tag: from django import template register = template.Library() @register.filter def provinceonly(thelist): return thelist.filter(type="province") View: def indexconsistencycheck(request): allcountries = NaturalEarthCountry.objects.all().prefetch_related('fkcountrysecondaries__fkprovince__fkprovincesecondaries').select_related('fkcountrymain') Model: class NaturalEarthAll(models.Model): fkcountry = models.OneToOneField(NaturalEarthCountry, blank=True, null=True, on_delete=models.SET_NULL, related_name="fkcountrymain") fkprovince = models.OneToOneField(NaturalEarthProvince, blank=True, null=True, on_delete=models.SET_NULL, related_name="fkprovincemain") fktouristicarea = models.ForeignKey(TouristicArea, blank=True, null=True, related_name='relatednatmerged', on_delete=models.SET_NULL) fkcountrysecondary = models.ForeignKey(NaturalEarthCountry, blank=True, null=True, on_delete=models.SET_NULL, related_name="fkcountrysecondaries") fkprovincesecondary = models.ForeignKey(NaturalEarthProvince, blank=True, null=True, on_delete=models.SET_NULL, related_name="fkprovincesecondaries") debug-toolbar report: