Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Deploying Django on Apache server: mod_wsg causing error
mod_wsgi: Compiled for Python/2.7.11. mod_wsgi: Runtime using Python/2.7.12. This causes a SIGTERM and results in a 500 error. How do I fix this?? How can I compile mod_wsgi for Python/2.7.12? OS is Ubuntu by the way. -
How to display upload multi files's count in django admin?
I can upload multi files ,but how to display multi files count at list_display... models.py class PaperManager(models.Model): ... class PaperFile(models.Model): image = models.FileField(upload_to='upload/') project = models.ForeignKey(PaperManager) admin.py class PaperFileAdmin(admin.ModelAdmin): pass class ProjectFileInline(admin.StackedInline): model = PaperFile max_num=10 extra=0 admin.site.register(PaperFile, PaperFileAdmin) class PaperAdmin(admin.ModelAdmin): inlines = [ProjectFileInline, ] list_display = ('id', ...) ... admin.site.register(PaperManager,PaperAdmin) Thanks -
two of the same instance and configuration but one keep show nginx welcome page
I have a running instances which shows the site properly on aws. what's included to run the site are django, nginx, uwsgi with elastic ip I have created an image of the instances. Launch the instance which now I have a second instance which is the same as the first one. The second instance just have normal floating ip. When I input the ip into the browser, I was expecting to see my site too else just a long loading until it timeout since I didn't do any configurations in site-available yet. Anyways, I was then able to see only the nginx welcome page. I went to the site-available, put the ip into server_name, also I setup a dns for a subdomain name. After the changes, I restarted uwsgi. I tried using ip and subdomain on browser, but still showing the nginx welcome page. There isn't even an error. Does someone have any idea why or advice what I do try? They are both the same settings, shouldn't it work properly? P.S. I then tried moving the elastic ip from first instance to the second instance...I used the domain of first instance in browser...then my site pops up not the … -
highlight bokeh plot point on div mouseover using django
I want to have points on a bokeh plot glow or light up when a mouseover event occurs on the corresponding Div element. Is this possible? Is there a better plotting library for this? Any help much appreciated. The following Github repository contains my code: https://github.com/matt002/dynamic_plot_django.git -
How to get a request object inside urls.py
I am trying to use custom template on page_not_found default handle Inside urls.py from django.views.defaults import page_not_found handler404 = page_not_found(request, None, "pages/custom/404.html") page_not found method requires request, exception and template. So how can i get the request object. I know the alternative for using it inside views.py -
django forms and javascript
I want to include a simple Javascript function in my Django ModelForm to automatically calculate the Gross by multiplying Price and Quantity but I am not able to get it done. Below is my django code and HTML Code with JS Function: class TransactionForm(forms.ModelForm): class Meta: model = Transaction fields = ['Date', 'Fruits', 'Deal', 'Price', 'Quantity', 'Gross', 'Area'] widgets = { 'Date': DateInput(), 'Price': forms.TextInput(attrs={"id": "price", "onchange": "calculate_gross();"}), 'Quantity': forms.TextInput(attrs={"id": "qty", "onchange": "calculate_gross();", }), 'Gross': forms.TextInput(attrs={"id": "gross", "disabled":"true"}), } <script> function success() { alert('Transaction added successfully'); } </script> <script> function calculate_gross() { var price = parseFloat(document.getElementById('price').value); var qty = parseFloat(document.getElementById('qty').value); var gross = price*qty; document.getElementById('gross').value = gross; } </script> <h1>Enter Transaction Below</h1> <form method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" name="Submit" onclick="success();"> </form> Any support would be much appreciated. Thank You. -
Django Rest Framework: Patching a OneToOneField
I need help with a PATCH request using Django rest framework. I have a User model that inherits from AbstractBaseUser which has 2 fields: name and email. The email field is unique. Then I have a DojoMaster model that has a OneToOne relationship with the User model: models.py class DojoMaster(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) phone = models.BigIntegerField() username = models.CharField(max_length=100, unique=True) country = models.ForeignKey(Country, on_delete=models.CASCADE) I am able to POST a "dojomaster" to the application. Let's say the "dojomaster" POST looks like this: POST payload { "user": { "name": "XYZ", "email": "xyz@mail.com", "password": "2He$8Mv*" }, "phone": 2685211, "country": 575, "username": "iAmXyZ" } Now the "dojomaster" wants to change some of these details, so a PATCH request is sent: PATCH payload { "user": { "name": "XYZ", "email": "xyz24@mail.com", #change email "password": "p@55w0rd" #change password }, "phone": 3972925, #change phone number "country": 575, "username": "iAmXyZ" } To achieve this, I created the following in my serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('name', 'email', 'password') class DojoMasterUpdateSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) def update(self, instance, validated_data): user_data = validated_data.pop('user') user = User.objects.update(**user_data) instance.user = validated_data.get('user', user) instance.username = validated_data.get('username', instance.username) instance.phone = validated_data.get('phone', instance.phone) instance.country = Country.objects.get( country=validated_data.get('country', instance.country) ) … -
Changing Tableau display name of Django model fields
I have been using Django ORM with Tableau reports without many issues, by providing the label for the fields explicitly. E.g. my_field = models.CharField("A Better Looking Name", max_length=500) So the above shows up in Tableau reports as "A Better Looking Name". However, when using the contenttype framework, I am unable to provide the labels for field columns: object_id = models.TextField('Give whatever name here it does not work') content_type = models.ForeignKey(ContentType, ...) my_field = GenericForeignKey("content_type", "object_id") I have tried providing verbose_name for object_id, renaming my_field, etc. None of them translate to a changed label in the PostgreSQL database (and hence in Tableau). Note that I am NOT attempting to label these for Admin etc, so short_description is not of use here. Any input on how to use "A Better Looking Name" for the generic ID in Tableau would be appreciated. -
Ajax and Django to get a multi-select smart panel to work
Please any idea how i can achieve something like this with Ajax and Django. Lets say a medical app. I'll like to multi-select medicine while it shows in a different panel and add the amount(s) sum and show me like the right text-boxes.. -
Issue With Same Inbox Subject as Multiple Objects
I'm using this Django Messages package. Messages in the inbox with the same subject keeps showing up more than once depending on the number of times a sender and the recipient receives messages. I want a situation whereby messages with the same subject will only show up once in the inbox and not twice or thrice. Kindly check the attached image for what I mean. I've looked into the code and I did this message_list = Message.objects.inbox_for(request.user).values('subject').distinct() But still not working. -
Django assign score to the field based on the choice and calculate the sum of field scores
I am new to django and have been breaking my head for last couple of days over this problem. So I have something similar in models.py: class RType(models.Model): rtype_name = models.CharField(max_length=10, verbose_name="Severity", default = "") rtype_score = models.IntegerField(max_length=10, verbose_name="Severity Score", default = "") def __str__(self): return self.rtype_name class Environment(models.Model): environment_name = models.CharField(max_length=100, verbose_name="Environment") environment_sensitivity = models.ForeignKey(RType, on_delete=models.CASCADE, blank=True, null=True, verbose_name="Environment sensitivity", default = "") def __str__(self): return self.environment_name class UserGroup(models.Model): user_group_name = models.CharField(max_length=100, verbose_name="User Group") user_group_sensitivity = models.ForeignKey(RType, on_delete=models.CASCADE, blank=True, null=True, verbose_name="User Group sensitivity", default = "") def __str__(self): return self.user_group_name class Subject(models.Model): name = models.CharField(max_length=500, verbose_name="Subject", blank=True) question1 = models.ManyToManyField(UserGroup, verbose_name="User group", default="", blank=True) question2 = models.ManyToManyField(Environment, verbose_name="Environment", default="", blank=True) r = ?? Here are some things I want to achieve: Sum rtype_scores for each question (question1, question2) even if there are multiple choices Count number of choices made in question1 Make other calculations like / * + - on inputs from question, question and count results Store the outcome of calculations in r Is this even possible or am I doing everything incorrectly?