Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I tell Django not to cache when there is a an "Authorization" Header
I am using django with a DRF and JWT token to authenticate users. I am using caching to cache api response, but I do not want to do that for the logged in users. What I have in mind is something like using the from vary_on_headers which checks the request header Authorization and then not cache the response, but I cannot programmatically find a way to do this in python/django. Current way of doing caching is through a mixing class CacheMixin(viewsets.ViewSet): @method_decorator(cache_page(60*60)) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) -
OpenWRT automate configuration over ssh
I'm trying to build simple web based wifi controller for OpenWRT devices using django framework and sqlite database. Unfortunately I can not find any information about this kind of projects (openWisp is too complex for me). For that instance, how can I build a script file and save it each time when user saves configuration? is it possible to have a template of file with variables for user input and then save it? Example: user going to web page, typing device SSID, new device password and hitting save should generate script file on server side, after that i would take that device ssh information from another data table, connect to it and pass the script over SCP protocol. Is it even possible? Maybe there are different ways that I am not familiar with. Would really appreciate any information and ideas on this topic! -
Django filter object for multiple args
The issue currently is filtering for all users that Are not the user Where model field == True If I remove the ".filter(model="True")" than the first requirement is met. How can I add more filters to the users? Current error message: FieldError at /explore/ Cannot resolve keyword 'model' into field. Choices are: date_joined, email, emailaddress, favorite, first_name, groups, id, images, is_active, is_staff, is_superuser, last_login, last_name, logentry, owner, password, profile, socialaccount, user_permissions, username, webhook I understand that the error means. However, I'm not sure how to implement it in the code. view.py def explore(request, pk=None): template_name = 've/cp/explore.html' users_list = User.objects.exclude(id=request.user.id).filter(model="True") paginator = Paginator(users_list, 16) # Show x per page page = request.GET.get('page') users = paginator.get_page(page) try: favorite = Favorite.objects.get(current_user=request.user) favorites = favorite.users.all() except Favorite.DoesNotExist: favorites = None args = { 'favorites': favorites, 'users': users, } return render(request, template_name, args) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True, null=True) model = models.BooleanField(default=False) ... -
Django - Call API url that has Param
for example I need to call this API: /v2/json/status/{flight}/{date} and i have follow this Example Code But how can i get my code to read param flight and date to get the response/data. -
How to access raw ForeignKey value directly in Django ORM and use it in search_fields?
Let's say I have these models: class First(models.Model): id = models.SlugField(primary_key=True) class Second(models.Model): foo = models.ForeignKey('First') This technically means that Second.foo is a SlugField that points to the primary key of First model. The question is how can I access that raw value in foo without referencing and working with First model? Bonus question: How to make this field searchable in Django Admin panel without pointing to a sub model field? So how to do something like this? @admin.register(Second) class SecondAdmin(admin.ModelAdmin): search_fields = ['foo_id',] Instead of this? @admin.register(Second) class SecondAdmin(admin.ModelAdmin): search_fields = ['foo__id',] -
Libraries and extensions to make editable, interactive graphics in Django web app?
I'm building a Django app and would like a library, extension or way to create interactive graphs- bar, line, pie charts aside, I need to be able to move some things within the graph and lock those changes to be implemented into my system. For example, in a line chart, I need to be able to move and shift some of those lines within an allowable area by mouse-point-click-drag and set it in a new place where it needs to be set- and its new position needs to be interpreted and stored by my app. What options are available for this? -
How to make some authors post in a blog
Good afternoon! Now I understand with something like a blog on django. But I do not understand how you can make it so that you can put not one author of the post, but two, three, four, etc. Thank you so much -
How does djangoproject.com do its deploy to prod? Should I package my django project to deploy it?
I know this isn't exactly a SO-style question, but I think it would be very instructive to know the answer. The source for djangoproject.com is very helpful for understanding a possible layout for a Django project. However, the lack of a setup.py file suggests that this project is not "packaged" to put it into production. I am not interested in any of "how to setup nginx", "which DB to use", "how to <insert detail of hosting>". What I am interested in knowing includes: How do they deploy the djangoproject.com part to their production servers? Do they just do a git pull on their box to get the files in place? Or an scp/rsync/ftp? Who/what executes this step? I'm guessing it is automated, but does it trigger based on tags? or off .tar.gz files placed in a special location? (Given there are no tags/releases and only one master branch in the github project I'm guessing that whatever makes it onto master gets deployed?) How to they manage rolling back if they need to? / Is it automated?(the actual details are not necessary, but the general info would be good) Should I package my applications for deployment or not? I have always … -
how to mention password field in serializer?
I have a custom user for authentication and want to create a serializer class for it my custom user's model is like this : class User (AbstractUser): bio = models.TextField(max_length=500, blank=True) birth_date = models.DateField(null=True, blank=True) image=models.FileField(null=True , blank=True) and my serializer is : class UserSerializer (serializers.ModelSerializer): class Meta: model = User fields = ('username' ,'email' ,'password' ,'firstname' , 'last name' ) how could I mention that the password field is a password and its content must be hashed? -
auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserManage.groups'
In my Django project I have a user_manage app. I create a model named UserManage in my user_manage app's model.py: from django.db import models from django.contrib.auth.models import AbstractUser class UserManage(AbstractUser): username = models.CharField(max_length=12) Then I run: $ python3 manage.py makemigrations There comes the error: ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserManage.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'UserManage.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'UserManage.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'UserManage.user_permissions'. users_management.UserManage.groups: (fields.E304) Reverse accessor for 'UserManage.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'UserManage.groups' or 'User.groups'. users_management.UserManage.user_permissions: (fields.E304) Reverse accessor for 'UserManage.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'UserManage.user_permissions' or 'User.user_permissions'. -
AttributeError: 'tuple' object has no attribute 'permissions'. DJango groups
I did a bit of research and it seems that this is the correct code according to Django documentations but for some reason it returns. AttributeError: 'tuple' object has no attribute 'permissions'. DJango groups. Here is the code. admin_group = Group.objects.get_or_create(name='Admin') admin_group.permissions.add( add_token_permission, add_user_detail_permission, change_user_detail_permission, add_user_location_permission, ) admin_group.user_set.add(self.user) admin_group.save() -
How we user progressive web apps with django web project
I have to use progressive web apps with django web project like caching, metallic effect. Is it impact on web performance ? -
Modify LDAP user via a GUI in Python (Django)
I am working on a webapplication for LDAP users to login and edit their attributes such as username, description etc. And I was wondering if there is a way to modify the attributes of the logged in user. The modify operator of the python-ldap3 library is the way to go, but I can only modify a specified user in the code itself. Is it even possible to make this a general function for a logged in user or not? I searched for solutions, but I could not find anything. This is my modify operator (modify.py): from ldap3 import Server, Connection, ALL, MODIFY_REPLACE s = Server('192.168.1.154', get_info=ALL) c = Connection(s, 'cn=ldap_user,cn=Users,dc=domain,dc=com', 'Password', auto_bind=False) c.bind() c.modify('cn=ldap_user,cn=Users,dc=domain,dc=com', {'givenName': [(MODIFY_REPLACE, ['Test'])], 'sn': [(MODIFY_REPLACE, ['User'])]}) print(c.result) c.unbind() By the way, I am using Django, so at this point, I do not even know where and what I have to do. Anything can be helpful, so do not hesitate to post it. Thanks in advance. -
Left join in django model query?
I want to use left join of mysql query in django model query. MY mysql query that i want to use is :- select U.id,B.id as boardId, count(BJ.id) as countBoardMember, count(NM.id) as newsCountInBaord from users as U left join boards as B on B.userId= U.id left join board_join as BJ on B.id = BJ.boardId left join news_mappings as NM on NM.boardId = B.id where B.isArchived=false group by B.id having countBoardMember <10 and newsCountInBaord<5 limit 10 but what Django model query is making is using left outer join and then inner join:- SELECT `users`.`id`,COUNT(`board_join`.`joinedBy`) AS `countBoardMember`, COUNT(`news_mappings`.`id`) AS `newsCountInBaord` FROM `users` LEFT OUTER JOIN `boards` ON (`users`.`id` = `boards`.`userId`) LEFT OUTER JOIN `board_join` ON (`boards`.`id` = `board_join`.`boardId`) LEFT OUTER JOIN `news_mappings` ON (`boards`.`id` = `news_mappings`.`boardId`) INNER JOIN `boards` T6 ON (`users`.`id` = T6.`userId`) INNER JOIN `board_join` T7 ON (T6.`id` = T7.`boardId`) WHERE (T7.`requestStatus` = approved AND T6.`isArchived` = False) GROUP BY `users`.`id` HAVING (COUNT(`board_join`.`joinedBy`) > 10 AND COUNT(`news_mappings`.`id`) > 5) ORDER BY NULL limit 10; it is taking much longer time to achive my result. My django model query is this:- user_ids = Users.objects.using('cms').annotate(countBoardMember=Count('boards__boardjoin__joinedBy'), newsCountInBaord=Count('boards__newsmappings__id')).filter( boards__isArchived=0, boards__boardjoin__requestStatus='approved', countBoardMember__gt=10, newsCountInBaord__gt=5).all() what i am doing wrong in my djnago model query. -
django query set exclude, with postgres array, makes hard request
Client.objects.filter(Q(taggeds__tag_id__in=[1,2]), Q(taggeds__company_ids__contains=[2]), Q(taggeds__member_ids__contains=[2])) generates to SQL: SELECT "account_client"."id" FROM "account_client" INNER JOIN "interest_taggedclient" ON ("account_client"."id" = "interest_taggedclient"."client_id") WHERE ("interest_taggedclient"."tag_id" IN (1, 2) AND "interest_taggedclient"."company_ids" @> ARRAY[2]::integer[] AND "interest_taggedclient"."member_ids" @> ARRAY[2]::integer[]); That's good, BUT when: Client.objects.filter(Q(taggeds__tag_id__in=[1,2]), ~Q(taggeds__company_ids__contains=[2]), ~Q(taggeds__member_ids__contains=[2])) generates to SQL: SELECT "account_client"."id" FROM "account_client" INNER JOIN "interest_taggedclient" ON ("account_client"."id" = "interest_taggedclient"."client_id") WHERE ("interest_taggedclient"."tag_id" IN (1, 2) AND NOT ("account_client"."id" IN ( SELECT U1."client_id" FROM "interest_taggedclient" U1 WHERE (U1."company_ids" @> ARRAY[2]::integer[] AND U1."id" = ("interest_taggedclient"."id")))) AND NOT ("account_client"."id" IN ( SELECT U1."client_id" FROM "interest_taggedclient" U1 WHERE (U1."member_ids" @> ARRAY[2]::integer[] AND U1."id" = ("interest_taggedclient"."id"))))); The results with this request is the same with expected generation: SELECT "account_client"."id" FROM "account_client" INNER JOIN "interest_taggedclient" ON ("account_client"."id" = "interest_taggedclient"."client_id") WHERE ("interest_taggedclient"."tag_id" IN (1, 2) AND NOT "interest_taggedclient"."company_ids" @> ARRAY[2]::integer[] AND NOT "interest_taggedclient"."member_ids" @> ARRAY[2]::integer[]); This is the bug from django, or i do something wrong? -
Django loading the wrong template
I am reading Django Unleashed. In chapter 19 (pg 464), the author says: By default, our site-wide /templates/ directory is the last place Django will load a template from. To use our template, we could move the file into an app such as core and ensure that core appears before admin in the INSTALLED APPS settings list. However, then the admin app would be using our template too. This is clearly not the case when I tried to visit http://127.0.0.1:8000/user/logout/, Django uses logout.html template stored in site-wide templates directory instead of the one provided by auth app. Why is that? I haven't changed anything. I just check out the 8c2972bf62 commit and started the server. -
how i can integrate a bootstrap theme on admin side in python django 2.0
I am developing a website with front-end and back-end in python django 2.0. I have integrated bootstrap theme on front-end and now i want to integrate bootstrap theme on admin side. How can i add static files in admin templates. Can you guide me to integrate theme in admin side. Thanks in advance -
TypeError the JSON object must be str, not 'bytes'
when i try to send a json using an django rest framework i get this error TypeError at /usermanagement/user/ the JSON object must be str, not 'bytes' And my post fuction is code below. def post(self,request): user=json.loads(request.body) m_user= user.get('m_name', None) m_email = user.get('m_email', None) m_age=user.get('m_age', None) m_status = user.get('u_status_id', None) user = M_User(m_name=m_name, m_email=m_email, m_age=m_age, u_status_id=m_status) user.save() if user.save: user=M_User.objects.filter(m_user=m_user) serializer = M_Userserializer(user,many=True) context = { 'success': "true", 'user': serializer.data } elif not user.save: context={ 'success':"false" } else: context={ 'success':"false" } return Response(context) -
How paginate a list with python django
I have a code that call a rest-full service that return a list,i want make the pagination but i have some problems. this is my code: results = requests.get(url) col = results.json() page = request.GET.get('page', 1) paginator = Paginator(tuple(col), 10) try: proc = paginator.page(page) except PageNotAnInteger: proc = paginator.page(1) except EmptyPage: proc = paginator.page(paginator.num_pages) When i run my code the variable proc do not has any information. -
insert or update on table "page_content_pagesection" violates foreign key constraint
I just made some changes to my Django models locally, made migrations for them, and pushed up those migrations to my production server. Everything works fine locally, but when I try and perform a migrate in the production server, I get this error. The zero index is throwing me off. The model its dependent on, teamsafetytracker is new, and page sections have never depended on it up until now, so I'm not sure why it would even be looking for instances in the teamsafetytracker table ? django.db.utils.IntegrityError: insert or update on table "page_content_pagesection" violates foreign key constraint "page_co_safety_tracker_id_f30c4360_fk_team_teamsafetytracker_id" DETAIL: Key (safety_tracker_id)=(0) is not present in table "team_teamsafetytracker". relevant migrations class Migration(migrations.Migration): dependencies = [ ('team', '0037_remove_teampagesection_multi_tracker_one'), ] operations = [ migrations.RemoveField( model_name='team', name='safety_clock_start', ), ] class Migration(migrations.Migration): dependencies = [ ('team', '0038_remove_team_safety_clock_start'), ('page_content', '0017_auto_20170926_1436'), ] operations = [ migrations.RemoveField( model_name='webpage', name='safety_clock_start', ), migrations.AddField( model_name='pagesection', name='multi_tracker_three', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='page_multi_three', to='team.TeamSafetyTracker'), ), migrations.AddField( model_name='pagesection', name='multi_tracker_two', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='page_multi_two', to='team.TeamSafetyTracker'), ), migrations.AddField( model_name='pagesection', name='tracker_side', field=models.CharField(choices=[(b'L', b'Left'), (b'T', b'Three Section'), (b'R', b'Right')], default=b'R', max_length=20), ), migrations.AlterField( model_name='pagesection', name='safety_tracker', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='page_section', to='team.TeamSafetyTracker'), ), ] Models class TeamSafetyTracker(models.Model): name = models.CharField(max_length=255) label = models.CharField(max_length=200) team = models.ForeignKey('Team') safety_clock_start = models.DateTimeField(help_text="Date Since Last … -
Deploying Django on Apache: Internal server error
I can run Django locally just fine, but I can't deploy it using Apache. My error logs: [time 2018] [mpm_event:notice] [pid 23027:tid 140623621068672] AH00491: caught SIGTERM, shutting down [time 2018] [wsgi:warn] [pid 23278:tid 139675061790592] mod_wsgi: Compiled for Python/2.7.11. [time 2018] [wsgi:warn] [pid 23278:tid 139675061790592] mod_wsgi: Runtime using Python/2.7.12. [time 2018] [mpm_event:notice] [pid 23278:tid 139675061790592] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal operations /etc/apache2/sites-enabled/000-default.conf: <VirtualHost *:80> ServerName xxx.yyy.zzz #https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04 Alias /static /home/user/project/app/static <Directory /home/user/project/app/static> Require all granted </Directory> <Directory /home/user/project/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess project python-path=/home/user/project python-home=/home/user/project/env WSGIProcessGroup project WSGIScriptAlias / /home/user/project/project/wsgi.py WSGIApplicationGroup %{GLOBAL} ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> I don't have any http.conf file or log. -
Django Rest Framework: Uploading a Image
I can't save the image to the image field. Error "image": [ "No file was submitted." ] models.py class MyImages(models.Model): name = models.CharField(max_length=255) image = models.ImageField(upload_to='myphoto', null=False, max_length=255, blank=False) views.py class ImageList(APIView): parser_classes = (MultiPartParser, FileUploadParser,) def post(self, request): file_serializer = MyImageSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) serialiser.py class MyImageSerializer(serializers.ModelSerializer): class Meta: model = MyImages fields = ('id', 'name', 'image') when using postman for file upload the file name is returned in view.py instead of the file object. I have also seen these threads but not working 1 2 -
Django ImageField.path returns path without upload_to within save method
Django ImageField.path returns path without upload_to within save method: # models.py class Message(models.Model): image = models.ImageField(upload_to='mes-img', null=True, blank=True) def image_tag(self): if self.image: # Printing "/base-dir/media/mes-img/image.png" print(self.image.path) # src=/media/mes-img/image.png return mark_safe('<img src="{0}" width="100" />'.format(self.image.url)) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): # Returns "/base-dir/media/image.png", should return "/base-dir/media/mes-img/image.png" print(self.image.path) # Returns "/media/image.png", should return "/media/mes-img/image.png" print(self.image.url) OS: Windows 10 64-bit Python 3.6.4 Django 2.0.2 -
Using Foreign Keys as attributes not as relations django error
I have a attributes section of the database example: class VenueApplicationDeclineReason(models.Model): reason = models.CharField(max_length=200) I use them to mark certian attributes in another database table: example: class Venue(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=1000, null=True, blank=True) streetaddress1 = models.CharField(max_length=150) streetaddress2 = models.CharField(max_length=150 ,null=True, blank=True) declinereason = models.ForeignKey(VenueApplicationDeclineReason, on_delete=models.DO_NOTHING, blank=True, null=True) When I try and access the declinereason I get the fk which is expeected now if I was using the VenueApplicationDeclineReason model I could use the venue_set property but since I am using foreign relations in a different way, is there a way to follow the relation with the Venue model? I did this, but then I got a valueerror def put(self, request, *args, **kwargs): serialized = self.get_serializer(data=request.data) serialized.is_valid(raise_exception=True) validatedData = serialized.validated_data instancepk = kwargs.get('pk', None) venueobject= Venue.objects.get(pk=instancepk) venueobject.declined = validatedData.get('declined') venueobject.declinereason = validatedData.get('declinereason') venueobject.declinetext = validatedData.get('declinetext') date = datetime.date.today() # for python to auto delete venueobject.declineddate = date # for display venueobject.declineddatestring = date.strftime() venueobject.save(update_fields=['declined','declinereason', 'declinetext']) return Response({}) self.raise_uncaught_exception(exc) File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/local/lib/python2.7/site-packages/rest_framework/views.py", line 491, in dispatch response = handler(request, *args, **kwargs) File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/venues/views.py", line 72, in get venue.declinereason = venuedeclinereasonshashmap.get(venue.declinereason, '') File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 216, in __set__ self.field.remote_field.model._meta.object_name, ValueError: Cannot assign "u''": "Venue.declinereason" must be a "VenueApplicationDeclineReason" instance. -
Defining right condition to check equality of integer fields
Sorry maybe my title is not so clear but i have no idea how to write it. I have a Tournament model that saves the results of matches like: class Tournament(model.Model): team_1_score = models.PositiveSmallIntegerField(blank=True, default=0) team_2_score = models.PositiveSmallIntegerField(blank=True, default=0) team_1_point = models.PositiveSmallIntegerField(blank=True, default=0) team_2_point = models.PositiveSmallIntegerField(blank=True, default=0) @receiver(pre_save, sender='tournament.Tournament') def my_callback(sender, instance, *args, **kwargs): if instance.team_1_score > instance.team_2_score: instance.team_1_point += 2 elif instance.team_2_score > instance.team_1_score: instance.team_2_point += 2 elif instance.team_2_score == instance.team_1_score: instance.team_2_point += 1 instance.team_1_point += 1 And I created pre_save method that should automatically update of team_1_point and team_2_pointvalues. But the problem is that my default value is set to 0 and of course my pre_save method gives 1 point to both teams. Could you help me to make such an algorithm that will work correctly? Even if i set default to "" or just leave it, it means they are equal and my method will give point anyway.