Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Postgres: Aggregate on RangeField
Is it possible to perform aggregation functions on Django's RangeField? Let's say we have 3 objects with BigIntegerField price_range. 1st obj: price_range = [10,5000] 2nd obj: price_range = [1,5000] 3rd obj: price_range = [100,9000] The result of Max and Min aggregation of these three objects would be: min = 1 and max = 9000 I'm trying to aggregate Max and Min this way: MyModel.objects.aggregate(Min('price_range'),Max('price_range'),) Which raises error: ProgrammingError: function min(int8range) does not exist LINE 1: SELECT MIN("app_mymodel"."price_range") AS "price_range__min" FROM "app... Do you know what to do? -
How can I use "add_fields" in django?
I was reading django docs and found "add_fields" methtod https://docs.djangoproject.com/en/2.0/topics/forms/formsets/#adding-additional-fields-to-a-formset. Docs say: "If you need to add additional fields to the formset this can be easily accomplished. The formset base class provides an add_fields method.", I want to use it but there is no example or explanation how it can be used in views and templates.Can you provide me a small example of using this method. -
convert_datetimefield_value() takes 4 positional arguments but 5 were given using django with mongodb
Django Admin login page, I am using mongodb for django, after that only I got error Click Here -
SOLVED - window.onpopstate not triggered after page reload
I have two basic pages with the urls http://localhost:8000/page-a and http://localhost:8000/page-b. I'm using html5 history api and following this tutorial. The only difference is that I add the api endpoint of the data, like http://localhost:8000/api/page-a and http://localhost:8000/api/page-b, in pushState(). I can easily go back and forth in history but when reloading the page and go back and forth, window.popstate does not trigger anymore. Rather, it directly navigates to page-a and page-b as it says in the console. In the demo, I reloaded the pages but it still works fine. Is this because the data has to be fetched with AJAX? (but in the tutorial it says the AJAX is fine) EDIT I forgot to mention that the pages are created dynamically (with Django). Is it because of the dynamic nature of the pages? SOLVED I should have added the url of the state like http://localhost:8000/api/page-a/. On page reload, Django always resolves the url http://localhost:8000/page-a to http://localhost:8000/page-a/ so when I click the back button the onpopstate is never triggered. It was just a '/' and costed me like two days. Hope no one makes this mistake again. () -
Accessing the time where a field has been updated (Django models)
I need to create a system where the user have to change his password every "x" number of days. I managed to achieve this by saving a UTC timestamp representing the time when the user has created/modified his password. My question is, instead of saving the timestamp in the database, is it possible to get a timestamp representing the time when the field has been changed through some of django's built-in functions? This way I could access when was the last time the user has updated his password without having to add a dedicated field in the model to save the timestamp in it. -
Django persistent ldap_user object
I have a custom AbstractUser model which looks like this: class User(AbstractUser): organization = models.CharField(max_length=64) organization_cgkprimarykey = models.PositiveIntegerField() def clean(self): ldap_prefix_1, ldap_prefix_2 = 'AUTH_LDAP_1_', 'AUTH_LDAP_2_' ldap_user_object = self.ldap_user usd = UsdDBActions() username = self.username if ldap_user_object.backend.settings_prefix == ldap_prefix_1: # do something elif ldap_user_object.backend.settings_prefix == ldap_prefix_2: # do something else def save(self, *args, **kwargs): self.clean() super(User, self).save(*args, **kwargs) Now, I use the multiconfig to authenticate the user against 2 LDAP backends which works great. The problem comes when I try to update the permissions of the user via shell (after the user first logged in to the app): In [1]: from backend.apps.base.models import User In [2]: u = User.objects.first() In [3]: u.is_staff = True In [4]: u.save() The above throws the following error when the save() method is called: AttributeError Traceback (most recent call last) <ipython-input-4-36670e5dc5d1> in <module>() ----> 1 u.save() ~/main/apps/Order/backend/apps/base/models.py in save(self, *args, **kwargs) 48 49 def save(self, *args, **kwargs): ---> 50 self.clean() 51 super(User, self).save(*args, **kwargs) ~/main/apps/Order/backend/apps/base/models.py in clean(self) 21 def clean(self): 22 ldap_prefix_1, ldap_prefix_2 = 'AUTH_LDAP_1_', 'AUTH_LDAP_2_' ---> 23 ldap_user_object = self.ldap_user 24 usd = UsdDBActions() 25 username = self.username AttributeError: 'User' object has no attribute 'ldap_user' I'm not sure if I did anything wrong but IMO … -
ValueError: The 'photo' attribute has no file associated with it
I'm using react and django together and I seem to be hitting a big problem. Most of the solutions I found on this site recommend checking the templating for repetitions but I'm not using django's default templating engine. This error shows up when I use model_to_dict(driver_object). The driver object has a photo that I set to null=true in models. Please help me I dont know how to fix it models.py class Person(SoftDeletionModel): name = CharField(max_length=64) email = CharField(blank=True, null=True, max_length=64) contact_no = PositiveIntegerField() address = CharField(max_length=256) birth_date = DateField() sex = CharField(max_length=1, choices=SEX) photo = FileField(default='client/src/images/users.png') class Driver(Person): user = OneToOneField(User, on_delete=models.CASCADE, null=True) application_date = DateField() views.py user_type = SignInView.get_user_type(user) user_staff = SignInView.get_user_staff(user_type, user) return Response(data={ "token": token.key, "user": model_to_dict(user), "user_type": user_type, "user_staff": model_to_dict(user_staff) }, status=200) @staticmethod def get_user_staff(user_type, user): if user_type == "system_admin": return user if user_type == "driver": return Driver.objects.get(user=user) if user_type == "supervisor": return Supervisor.objects.get(user=user) if user_type == "operations_manager": return OperationsManager.objects.get(user=user) if user_type == "clerk": return Clerk.objects.get(user=user) I think the problem is rooted from django throwing an error instead of returning None if the photo is null. Are there any workarounds? pls help -
Cache invalidation is not working in browser using or app Rest API?
from django.utils.cache import get_cache_key from django.core.cache import cache from django.views.decorators.cache import cache_page @api_view(['GET', 'POST', 'PUT', 'DELETE']) @permission_classes((IsPermittedWithoutAuth,)) @cache_page(60 * 5) def extra_facility(request): if request.method == 'POST': "code.............." key = get_cache_key(request) if cache.has_key(key): cache.delete(key) return Response({'status': {'code': status.HTTP_200_OK, 'error': None, 'message': 'Extra facility has been added.' }, 'data': None, 'id': extra.id}) if request.method == 'GET': facility = ExtraFacility.objects.all() if params.get('is_active'): facility = facility.filter(is_active=get_boolean(params['is_active'])) result = paginator.paginate_queryset(facility, request) serializer = ExtraFacilitySerializer(result, many=True, context={'request': request}) # next_page = paginator.get_next_link() return Response(serializer.data) if request.method == 'PUT': "code logic " key = get_cache_key(request) if cache.has_key(key): cache.delete(key) return Response({"data": serializer.data, "status": {"code": status.HTTP_200_OK, "message": "Extra facility has been updated.", "error": None}}) if request.method == 'DELETE': "code logic" key = get_cache_key(request) if cache.has_key(key): cache.delete(key) return Response({"status": {"code": status.HTTP_200_OK, "message": "Extra Facility has been deleted", "error": None}}) This API is used in fronted using Reactjs and android app. Caching is working perfectly on GET request. Caching invalidation is also working using POSTMAN on POST, PUT, and DELETE request. But Caching invalidation is not working on POST, PUT, and DELETE request when this API is called in browser using Reacjs and Caching invalidation is also not working in Android app -
Django 'Cannot add foreign key constraint' error while doing makemigrations operation
I am using Django 1.9.5 and python 2.7. I am also using MySQL as db. When i try to make migrations i get below "Cannot add foreign key constraint" error. I get this error as i am trying to add many to many field to an existing table. When i make migration and migrate, the many to many relation table is created but without foreign key constraint. While runserver it also says; "You have unapplied migrations; your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them." I can add new data to this table ,but without foreign key constraint, through the web site. But i need the table fields to be created with foreignkey constraint for the relations. The operation will create many to many relation between Worker and Workerduty tables. MySQL is InnoDB configured. Error Logs : # python manage.py migrate Operations to perform: Apply all migrations: authtoken, sessions, admin, auth, reversion, contenttypes, company Running migrations: Rendering model states... DONE Applying company.0005_Worker_duty_type...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/dataproj/Env/dataproj/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/dataproj/Env/dataproj/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/dataproj/Env/dataproj/lib/python2.7/site-packages/django/core/management/base.py", line 348, in … -
django UUID validation error while update record
I am using Django 1.11 randomly getting UUID validation error on server. Error: validation error [u"'ab201230-9fca-449e-ab89-f9becb0e65b3' is not valid uuid"] I am using eb to host on aws. -
Why should we use three migration commands to migrate our database succesfully?
I was working on models in django and after creating classes for models and when migrating them I was supposed to use three commands for completing migration of models. The commands are :python manage.py migrate,python manage.py makemigrations <app_name>,python manage.py migrate So my question is that why should we use three commands like this ? -
How do I resolve following: TypeError: __init__() missing 1 required positional argument: 'on_delete' [duplicate]
This question already has an answer here: Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries 5 answers CODE from django.db import models from django.contrib.auth.models import User class Game(models.Model): first_player = models.ForeignKey(User, related_name="games_first_player") second_player =models.ForeignKey(User,related_name="games_second_player") start_time = models.DateTimeField(auto_now_add=True) last_active = models.DateTimeField(auto_now=True) class Move(models.Model): x = models.IntegerField() y = models.IntegerField() comment = models.CharField(max_length=300, blank=True) by_first_player = models.BooleanField() game = models.ForeignKey(Game, on_delete=models.CASCADE) -
foreign key relationship in Django REST FRAMEWORK
I would like to create an employee object whose attributes include pre-existing foreign key (Department).when i see employee api.. i am getting department id instead of department name.... please help models.py class Department(models.Model): name = models.CharField(max_length= 20) def __str__(self): return self.name class Employee(models.Model): employee_name = models.CharField(max_length= 20) surname = models.CharField(max_length= 20) address = models.CharField(max_length = 50) qualification = models.CharField(max_length = 30) contact_num = PhoneNumberField() department = models.ForeignKey(Department, on_delete=models.PROTECT) def __str__(self): return self.employee_name serialize.py class DepartmentSerializer(serializers.ModelSerializer): """ Serializer to represent the Chain model """ class Meta: model = Department fields = '__all__' class EmployeeSerializer(serializers.ModelSerializer): """ Serializer to represent the Chain model """ class Meta: model = Employee fields = '__all__' -
django-viewflow Error:sqlite3.OperationalError: no such table: frontend_module
I run viewflow_quickstart code(http://docs.viewflow.io/viewflow_quickstart.html), it shows how to create basic Hello World application where one person starts “Hello, world” request, another one approves it, and when approved the request sent out. but error comes, it is:django.db.utils.OperationalError: no such table: frontend_module Errors as below: Internal Server Error: / Traceback (most recent call last): File "E:\django_learn_0623\django_learn_env\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "E:\django_learn_0623\django_learn_env\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: frontend_module -
Django-cms object duplication when page is published
I'm using Django-cms app for my project where I'm getting the duplicate data in Django-admin of my model. I have tried a couple of solutions but somehow it didn't work I have referred Django-CMS 3.0.3 Publishing a page duplicates data from plugin django-cms-saq class Event(CMSPlugin, TimeStampedModel): title = models.CharField(verbose_name=_('Event Title'), max_length=255) description = models.TextField(verbose_name=_('Description'), null=True, blank=True) image = models.ImageField(upload_to='images/', null=True, blank=True) date_time = models.DateTimeField(verbose_name=_('Event date & time'), ) above listed is my model, I'm Using that model with Django rest framework, so when I call API I'm getting duplicate data I have tried Event.objects.filter(placeholder__page__publisher_is_draft=True) but It is giving me a null query set. when I debug my code I came to know that I'm getting page=None but I don't know the reason. Thanks in advance -
Accessing Radio/Checkbox button selection in Django form post request
I have a webpage form in django. I have some radio button on my webpage. After user selects the radio button and on submit I need to know which radio button was selected in my views. I tried using following code: Html Template: <form action= "{% url 'rec:opt' %}" method="post"> {% csrf_token %} {% for name in features %} <tr> <td>{{ name }}</td> <td> <input type="checkbox" name="is_obj" id={{ name }} + "_is_obj" > <br> </td> <td> Lower Limit <input type="text" name="ll" id={{ name }} + "_ll"> Upper Limit <input type="text" name="ul" id={{ name }} + "_ul"> </td> </tr> {% endfor %} <input type="submit" value="Submit" /> </form> View.py def opt(request): print(request.POST['is_obj']) #'on' The request.POST only returns 'on' and doesn't say which radio/check box was selected. Also the getlist returns following request.POST.getlist['is_obj'] # ['on'] -
Django: How do validate an street address upon entry?
If I wanted a model field (or set of fields) to contain a person's US street address, how would I go validating whether this is an actual street address? I want to be able to later use it with google apis to get geolocation coordinates. I have an idea of how to do that, but I can't do it if the street address doesn't exist. -
Django Channels Push live database updates
I have a database table displayed on the HTML page but the database is continually updated. I wish to display these updates in real-time with django channels. I have already written a receiver function with django signals. My question is: what django channels code should I write in the receiver function, to update the database table on the HTML page to show the changes in real time? For example, when I visit the HTML page, I would be greeted with a database table. I should see the table updated live, every time there are any changes to the database. Is it possible to do that with the group_send method: async_to_sync(channel_layer.group_send)("chat", {"type": "chat.message", "text": "updated queryset"}) But instead of sending text, could it send a queryset that is drawn from the database table? Or is this not the best way to show live updates of a database? Any guidance would be appreciated! -
Update a Model value in database: django
I've created a model in Django which is as follows: class LatestSavedKeyPassword(models.Model): key_password = models.CharField( max_length=20, default='', blank=True, help_text="<b><a>System Generated, Do Not Alter</a></b>") def __str__(self): return self.key_password Now I want to save value passwordval to the field. Also I want that when I use this model again, then the previous value gets updated and don't want a new entry to be created. How to do it? I'm using Django 2.0 and python 3.5 -
Editing navbar using django admin
I have select group. When I select one of the options the data related to that should be displayed. I tried many times but the django just iterating over all the fields? -
Separating the settings.py data out
In my Django project. I have a requirement of settings.py: in my settings.py, there is a CORS_ORIGIN_WHITELIST variable: CORS_ORIGIN_WHITELIST = ( 'http://10.10.10.102', 'http://10.10.10.102:8000', 'http://10.10.10.102:8080', 'http://10.10.10.102:8081', 'http://10.10.10.102:8888', 'http://10.10.10.103', 'http://10.10.10.103:8000', 'http://10.10.10.103:8080', 'http://10.10.10.103:8081', 'http://10.10.10.103:8888', ..... I want to set it flexibly, I mean I can in my user interface for add/update/delete the items. but it is settings up in settings.py, how can I implements my requirement? -
How do I get the latest post in a topic?
I was wondering how to get the latest post for my topic in Django for my forum. I have listed my code below. forum.html: {% for category in categories %} <h5 class="blue-text">{{ category.title }}</h5> <table> <thead> <tr> <th>Icon</th> <th>Name</th> <th>Latest Post</th> </tr> </thead> {% for topic in category.topic_set.all %} <tbody> <tr> <td><i class="material-icons black-text">{{ topic.icon }}</i></td> <td><a href="/forum/topic/{{ topic.slug }}">{{ topic.title }} </a><br> <span class="grey-text">{{ topic.description }}</span></td> <td><a href="#!">post_title</a> <br> <span class="grey-text">post_author</span> <br> <span class="grey-text">post_created_at_timesince</span></td> </tr> {% empty %} <p>No topics in {{ category.title }}</p> {% endfor %} </tbody> </table> {% empty %} <p>No categories.</p> {% endfor %} views.py: def post(request, slug, topicslug, postid): post = Post.objects.get(slug=slug) replies = Reply.objects.filter(post=post) if request.method == "POST": form = AddReplyForm(request.POST) if form.is_valid(): addreply = form.save(commit=False) addreply.author = User.objects.get(username=request.user.username) addreply.post = post addreply.created_at = timezone.now() addreply.save() messages.success(request, 'You have successfully added a reply.') return render(request, 'post.html', {'post': post, 'replys': replies, 'form': form}) elif request.method == "GET": form = AddReplyForm(request.POST) return render(request, 'post.html', {'post': post, 'replies': replies, 'form': form}) If you need anymore details let me know. Thanks, Cameron. -
Triggering a django rest framework update() function using HTTP Requests
I just started to learn django last week so please excuse my ignorance if I'm completely approaching this problem the wrong way. So I've been following a thinkster tutorial on setting up a User model that allows the change of a password in the model. So far I have a url (/api/user) that leads to this view: class UserRetrieveUpdateAPIView(RetrieveUpdateAPIView): permission_classes = (IsAuthenticated,) renderer_classes = (UserJSONRenderer,) serializer_class = UserSerializer def retrieve(self, request, *args, **kwargs): #turns the object recieved into a JSON object serializer = self.serializer_class(request.user) return Response(serializer.data, status=status.HTTP_200_OK) def update(self, request, *args, **kwargs): serializer_data = request.data serializer = self.serializer_class( request.user, data=serializer_data, partial=True ) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) I understand that this section : serializer = self.serializer_class( request.user, data=serializer_data, partial=True ) serializer.is_valid(raise_exception=True) serializer.save() will call upon a serializer class along the lines of: class UserSerializer(serializers.ModelSerializer): #This class handles serialization and deserialization of User objects password = serializers.CharField( max_length=128, min_length=8, write_only=True ) class Meta: model = User fields = ('email', 'username', 'password', 'token',) read_only_fields=('token',) def update(self, instance, validated_data): #performs an update on the user password = validated_data.pop('password', None) #have to take out password because setattr does not handle hashing etc for (key, value) in validated_data.items(): #for the keys after taking out password … -
Dynamically alter image within a div through conditionals
I am working on a website that uses purely Django, but I want one of two images to appear under a conditional, Exactly like this VueJs example. Is this possible without a frontend framework, if so what is the best approach to get it done? -
How to add session expired/inactivity timeout in signup_form.html or other - Django-crispy-forms
I use path('accounts/', include('django.contrib.auth.urls')) for Signup Login and Logout, signup_form.html is as below, if user didn't click Logout he will login on that web all the time, and it's not safe if user forgot to click 'Logout', how to add a function of Session expired / Inactivity timeout and logon again? {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="row"> <div class="col-md-8 col-sm-10 col-12"> <form method="post" novalidate> {% csrf_token %} <input type="hidden" name="next" value="{{ next }}"> {{ form|crispy }} <button type="submit" class="btn btn-success">Sign up</button> </form> </div> </div> {% endblock %}