Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Apps and Python Packages Dependencies
I am new to web development. I am not familiar with Django. I have written some Python scripts which do some intense calculations and graphs plotting using Python packages such as numpy, matlibplot and so on. I want to publish it as a web application on a server to be accessed by other computers. So I am wondering, do I need to copy all the required packages into the project directory before deploying the application to a server? Or Django will automatically handle the Python packages dependencies upon deploying? -
Why " <link href="{% static "css/base.css" %}" rel="stylesheet">" occurred? And my css cite is fail?
I use django to write a html and cite a css model,but i find it fail and the visuaulstudio remind me that " <link href="{% static "css/base.css" %}" rel="stylesheet">" Here is my html code {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/base.css" %}" rel="stylesheet"> </head> <body> <div id="header"> <span class="logo">Bookmarks</span> </div> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> Could somebody tell my why? -
pdf not generated using django restframework
class GeneratePublisherPdf(APIView): #View def get(self, request, args, *kwargs): reviewer_id = request.GET.get("user") export_date = datetime.date.today() - datetime.timedelta(1) profile = UserProfile.objects.filter(user_id=reviewer_id).first() users = [profile.user.id, ] for up in UserProfile.objects.filter(publisher=profile.user, user__register_type='5'): users.append(up.user.id) if not len(users): result = { "status": False } return Response(data=result) queryset = ProductCertificate.objects.filter(user__id__in=users, created__date=export_date).order_by('-created') if queryset.count(): instance = PDFFile.objects.create(user_id=reviewer_id, export_date=export_date) obj = PDFFile.objects.get(id=instance.id) objes = [] for e in queryset: dict_rep = { "workflow_id": e.workflow_step.workflow.workflow_id, "step": e.workflow_step.step, "role": e.workflow_step.role, "organization": e.user.profile.organization if e.user.profile.organization else "-", "product": e.product.title if e.product else "-", "in_batch_id": e.in_batch_id, "out_batch": e.out_batch_id, "transaction_address": "<br>".join(textwrap.wrap(e.transaction_address, 13)), "trans_add":e.evidence } objes.append(dict_rep) data = { 'export_date': export_date, 'record': objes } pdf = render_to_pdf('pdf/invoice.html', data) filename = "%s.pdf" % (datetime.datetime.now().strftime("PDF%y%j%H%M%s%f")) obj.pdfurl.save(filename, File(BytesIO(pdf.content))) result = { "export": export_date, "id": str(instance.id), "pdf": str(obj.pdfurl).split("/")[-1], "status": True } else: result = { "status": False } return Response(data=result) plz help..i cannot able create pdf file .. -
like() got an unexpected keyword argument 'story_id'
Episode has GenericRelation with Like model class Episode(models.Model): likes = GenericRelation(Like) Viewset: class EpisodeViewSet(viewsets.ModelViewSet, LikedMixin): serializer_class = EpisodeSerializer permission_classes = (IsOwnerOrReadOnly,) def get_queryset(self): queryset = Episode.objects.filter(story=self.kwargs.get('story_id')) return queryset urls: router.register(r'(?P<story_id>\d+)/episodes', views.EpisodeViewSet, basename='episodes') LikedMixin has function for performing like action: @action(detail=True, methods=['POST']) def like(self, request, pk=None): obj = self.get_object() services.add_like(obj, request.user) return Response() When I try post request with url 0.0.0.0:3000/stories/1/episodes/1/like/, i recieve error like() got an unexpected keyword argument 'story_id'. -
JQuery Slider in django templates
I'm trying to add a JQuery slider in a Django template but it doesn't work... My main template: ... <div> <dt class="nav-header">Size</dt> <dd> {% include 'catalogue/slider_size.html' %} </dd> </div> ... The template slider_size.html : <link rel="stylesheet" href="slider.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function() { $( "#slider-range" ).slider({ range: true, min: 0, max: 500, values: [ 75, 300 ], slide: function( event, ui ) { $( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] ); } }); $( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) + " - $" + $( "#slider-range" ).slider( "values", 1 ) ); } ); </script> <p> <label for="amount">Price range:</label> <input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;"> </p> <div id="slider-range"></div> The error in the console: Error in the console Any ideas? Thank you in advance. -
Save a charfield column with prefix and primary key combined in django model?
i created a model "PurchaseRequest". the pk is autocreated. Now, i created a charfield column which would store a value like "PR# + pk" during save process. def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.pr_number = 'PR #' + str(self.id) super(PurchaseRequest, self).save() BUT, it returns PR#None . once i edit and save it , it returns correct answer as obviously it fetches id now. -
Sys.path.insert inserts path to module but imports are not working
I want to import a module in a project and it gives me lots of troubles because of an import error. So I decided to write a little test to see where the problem lies. I add a folder to my sys path and try to import it. And I get an Import Error: no module found named xyz Like this: import sys import os sys.path.insert(0, os.path.abspath('../../myfolder')) import myfolder print(sys.path) The sys.path is ['/Users/myuser/myproject/mywebsitefolder/myfolder/', ...] myfolder contains an __init__.py file. Hardcoding the path to myfolder has same results. Other questions on the web solve the problem by either adding the correct path or by adding an init. But I have both I think and the problem remains. I was under the impression that python looks in the system path for importable modules or do I misunderstand how this is supposed to work? If I understand correctly, is there any way I can debug this further? Or could this be a problem with python versions? Help is very much appreciated. Thanks in advance! -
Weird behaviour of django REST APIs
We are having django application, which is hosted on AWS Elastic Beanstalk. It is connected to RDS. Application Server: c5.4xlarge RDS: postgreSQL 9.5 (m5.4xlarge) The issue is APIs are sometimes returning 500 and sometimes 200 even thought the request params are exactly same. That is causing Elastic Beanstalk to degrade every now and then. I tested the APIs with all possible requests on my local by connecting to Cloud database. But did not receive a single 500 error. Same app is there on Test environment and it is not causing a single 500. There is no load on the RDS when EB degrades. So, it seems application is not the issue here. Could it be due to Application Server resources? Please help. Cloudwatch References: -
Python IOError: push_notifications.apns in _apns_create_socket
We are using django-push-notifications==1.6.0. We confirmed that the file is existing in the docker container. The pem file is valid because we abled to sent device notification manually using the file. Below is the actual log: IOError: [Errno 2] No such file or directory File "demoapp/tasks_helpers/notification.py", line 216, in push certfile=apns_certfile File "push_notifications/models.py", line 167, in send_message **kwargs File "push_notifications/apns.py", line 113, in apns_send_message certfile=certfile, **kwargs File "push_notifications/apns.py", line 66, in _apns_send client = _apns_create_socket(certfile=certfile, application_id=application_id) File "push_notifications/apns.py", line 38, in _apns_create_socket use_alternative_port=get_manager().get_apns_use_alternative_port(application_id) File "apns2/client.py", line 41, in __init__ self.__credentials = CertificateCredentials(credentials, password) File "apns2/credentials.py", line 29, in __init__ ssl_context = init_context(cert=cert_file, cert_password=password) File "hyper/tls.py", line 131, in init_context context.load_cert_chain(cert, password=cert_password) Why is the system always looking for the pem file directory when in fact the actual file exist? -
verify FCM registration token using python
I have Firebase Cloud Messaging registration token from client. and i want to verify this registration token before I send push notification. btw, I have tried https://firebase.google.com/docs/auth/admin/verify-id-tokens but I think this is for Auth tokens not for push notification. how to verify registration token before send push notification ? -
Java installation error in Ubantu 18.4 LTS
I have to run Django CRM in my local machine.I followed all commands and tried to install every requirements. I stuck in the following command. sudo apt-get install oracle-java8-installer -y java -version I got the following error when i tried above command. E: Command line option 'e' [from -version] is not understood in combination with the other options. The link of Github CRM Django CRM Documentation Please someone help me. -
Is there a way to combine two django projects into one?
I have two django projects, now i have to combine this into single project is there any that i can achieve this. -
Django Ajax - Getting KeyError while trying to access session variable
I'm trying to develop custom Django Login Form. While Signing up a user, I'm setting the value of the Session variable request.session['un'] = username But, when I'm trying to get the value of request.session['un'] using print(request.session.get('un')) I'm getting the value as None, and a KeyError. I'm using Axios from VueJS Front End to send Ajax Post request to Django backend. -
How to use variables from backend in .scss files
I have a site built with Django, Python and Wagtail. What I want is that I'm able to add some styles in the backend and then use it in my frontent's .scss files. For example I want to be able to set a primary color to #fff via backend and then use it in my .scss file as: $g-color-primary: primary_color_from_backend; $g-font-size-default: primary_font_size_from_backend; I do not have any idea how I can do that and if it's possible at all? Thanks for the help. -
Object has no attribute 'items` while writing api test case?
Here I am trying to write TestCase for my PackageCreateView and I did the following.But it is not working. File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\test\client.py", line 535, in post response = super().post(path, data=data, content_type=content_type, secure=secure, **extra) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\test\client.py", line 346, in post post_data = self._encode_data(data, content_type) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\test\client.py", line 305, in _encode_data return encode_multipart(BOUNDARY, data) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\test\client.py", line 194, in encode_multipart for (key, value) in data.items(): AttributeError: 'Package' object has no attribute 'items' models class Country(models.Model): name = models.CharField(max_length=255, unique=True) class Package(models.Model): name = models.CharField(max_length=255) package_description = models.TextField() package_start_date = models.DateTimeField() country = models.ManyToManyField(Country) tests.py from rest_framework.test import APITestCase class CreateProductTest(APITestCase): def setUp(self): self.country = Country.objects.create(name='name') self.package = Package.objects.create(name='package',package_description='description',package_start_date='2019-11-12 11:11') self.package.country.add(1) self.package.save() self.client = Client() def test_create(self): url = reverse('package:create_package') response = self.client.post(url, data=self.package,format='json') print(response.status_code) self.assertEqual(response.status_code, status.HTTP_201_CREATED) views.py class CreatePackage(generics.CreateAPIView): serializer_class = PackageSerializer queryset = Package.objects.all() -
Django Aggregation Get Count of Users per Project View
I have a model for tracking users viewing a project, it has foreign key references to user and project. An example looks like project user 1 1 1 2 1 3 2 1 2 2 What I want to achieve is a view count per projects so project 1 will be 3 and project 2 will be 2 in the example above. I am trying below, but it counts every user instance, how do I get every user instance per project? projects = ProjectViews.objects.all().annotate(view_count=Count('user')) -
How to show different entries from data tables on as a dropdown box option?
Hi this is my DB table for job title https://www.screencast.com/t/tse1qsnJI And this from employee table https://www.screencast.com/t/uMtmowCg How could I show the job titles on the drop down box and not the job_title_id as options? https://dpaste.de/SpAe -
Get permission to access google sheet on backend server Django from frontend
I want to read the data of google sheet in django server, which may not be shared with me. In front-end (angular 7) I want to give user an option, when he selects the google sheet, from where he can directly approve the permission to allow server to read the sheet data. Is there any possible way to do this? -
how can I write a custom link for activation?
I am trying to make my activation url like activate/096715d5a428c3d84dd142711f025d68963cc45ec29d4ddd8007506e00af13a3/ . my origial url looks like path('activate/<slug:uidb64>/<slug:token>/', views.activate, name='activate') , and I tried to remove <slug:uidb64> it doesnt work any tips to achieve this? -
How t properly use default django password validators in DRF
This is the serializer for registering users.I have two password fields here password1 and password2.For the password validation I would like to use django default AUTH_PASSWORD_VALIDATORS and for this I have tried like this.But the problem here is when I used only def validate_password1 then the def validate() function always returns ValidationError so I write another function for password2 also.Now if the password matches and it is valid, it register the user but when the password is not valid it displays validation errors on both password1 and password2 field and which I doesn't want.How can I solve it ? And also another problem here is with function def validate_username() which is not implementing while registering the user. serializers.py import django.contrib.auth.password_validation as validators class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer(required=True) email = serializers.EmailField(validators=[UniqueValidator(queryset=get_user_model().objects.all())]) password1 = serializers.CharField(required=True, write_only=True) password2 = serializers.CharField(required=True, write_only=True) class Meta: model = get_user_model() fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2', 'profile'] def validate_password1(self, password): validators.validate_password(password=password) def validate_password2(self, password): validators.validate_password(password=password) def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError("The two password fields didn't match.") return data def validate_username(self, value): data = self.get_initial() username = data.get("username") if len(username) < 6 and len(username) > 15: raise ValidationError('Username must be between 6 and … -
How to populate Django form dynamically with a dictionary of lists and dictionaries?
I've been stuck on this for over a day now and was hoping I could get some help. I've read a bunch of different SO posts and Django docs on forms, formsets, bound and unbound forms, but still cant figure this out. I'm pulling in some data from a model which is a JSONField. It's a nested mess of dictionary (dict) like so: dict= { <br> &nbsp;'A' : 'data1', <br> &nbsp;'B' : [ { <br> &nbsp;&nbsp;&nbsp; 'one': [ <br> &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;{'x': 'data2', 'y': 'data3', 'z': 'data4'},<br> &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;{'x': 'data5', 'y': 'data6', 'z': 'data7'},<br> &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;{'x': 'data8', 'y': 'data9', 'z': 'data10'} <br> &nbsp;&nbsp; &nbsp;], <br> &nbsp;&nbsp;&nbsp;'two': 'val',<br> &nbsp;&nbsp;&nbsp;'three': { <br> &nbsp;&nbsp;&nbsp; &nbsp; 'color':'red',<br> &nbsp;&nbsp; &nbsp; &nbsp;'size':'big',<br> &nbsp;&nbsp; &nbsp; &nbsp;'order':'new'<br> &nbsp;&nbsp; &nbsp;}<br> &nbsp;&nbsp; &nbsp;'four':'someVal',<br> &nbsp;&nbsp;}]<br> &nbsp;'C' : 'moreData'<br> } The inner list, one, will have a dynamic amount of dictionaries in it, in this example there are just 3. The key's for one will always be the same (x, y, and z), but the values will change. I need to create an editable form, that has each key in it's own charfield with the initial data set as the value. I've looked into and tried some packages (django-entangled, django-json-widget, … -
Django model field dynamic in column
I am working on a Django model which could load an excel file as all the fields in that model, but the number of columns is dynamical(such as Years), which means I can not define each field by myself. Is there any library that could build the fields by providing the information inside the excel file, such as the name and length of the file? -
Failed to load resource: the server responded with a status of 403 (Forbidden) when i set DEBUG=FALSE and use nginx
I am new on develop django. I have to deploy it to manual server and my website cant load img in summernote django editor and img in ImageField(). I check on my server, it's uploaded. But it's not displayed. I tried set up my nginx.conf like location /media/{ alias /root/website-django/mysite/mysite/media/;} and try chmod for media/ folder in my django folder. on my console tab in url like www.example.com/media/my-img-1.png: It's notice me: "Failed to load resource: the server responded with a status of 403 (Forbidden)" when i turn DEBUG=TRUE -> All img will display. But i dont want to set DEBUG=TRUE because it's very risk. Please anyone help me. Thank you so much -
Django Queryset filter by relevance
So I'm looking to extract entries from a Queryset that contain a set of search words in a list. I need to then append the extracted entries to another list and sort them by word relevance, that is, the extracted entries that contain more of the search words are found earlier in the list. For example, something along the lines of: search_words=['this', 'is', 'a', 'test'] filtered_results=Test.objects.filter(content__names__icontains=search_words) where filtered_results would contain results starting with all four words, then a combination of 3/4 words, then a combination of 2/4 words, and so on. Is there a way to do this? -
Django Displays Password Field in User Edit Form
I am currently constructing a basic login functionality. While doing so, I encountered a hiccup. The method I am using displays the password field in the template. I believe I understand why it does that, but am unsure how to prevent it from appearing. I have the following view @method_decorator(login_required, name='dispatch') class UserUpdateView(UpdateView): form_class = CustomUserChangeForm #model = User #fields = ('first_name', 'last_name', 'email', 'profile_picture') template_name = 'user_accounts/profile.html' success_url = reverse_lazy('user_accounts:user_profile') def get_object(self): return self.request.user The pertinent Django form is class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('first_name', 'last_name', 'email', 'profile_picture') The profile.html is {% extends 'base.html' %} {% block title %}My account{% endblock %} {% block breadcrumb %} <li class="breadcrumb-item active">My account</li> {% endblock %} {% block content %} <div class="row"> <div class="col-lg-7 col-md-8 col-sm-10"> <form method="post" novalidate> {% csrf_token %} {% include 'includes/form.html' %} <button type="submit" class="btn btn-success">Save changes</button> </form> </div> </div> {% endblock %} Lastly, the form.html is {% load widget_tweaks form_tags %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} <p{% if forloop.last %} class="mb-0"{% endif %}>{{ error }}</p> {% endfor %} </div> {% endif %} …