Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django on docker; Staticfiles disappearing
I am trying to deploy my django project using docker nginx and gunicorn. My Issue is that the staticfiles I use for my project are missing from the container. when in the project: ls staticfiles/ css disconnected.html images lib nothing.css after going into the container with docker exec -it foo_web_1 /bin/sh ls staticfiles/ admin my docker-compose file: version: '3.7' services: web: build: context: ./foo-app dockerfile: Dockerfile.prod command: gunicorn foo-app.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/foo-app/web/staticfiles - media_volume:/home/foo-app/web/mediafiles expose: - 8000 env_file: - ./.env.prod nginx: build: ./nginx volumes: - static_volume:/home/foo-app/web/staticfiles - media_volume:/home/foo-app/web/mediafiles ports: - 2375:80 depends_on: - web volumes: postgres_data: static_volume: media_volume: the nginx.conf file: upstream foo-app { server web:8000; } server { listen 80; location / { proxy_pass http://foo-app; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /home/foo-app/web/staticfiles/; } location /mediafiles/ { alias /home/foo-app/web/mediafiles/; } } the part of the settings.py that relates to staticfiles: STATIC_URL = "/staticfiles/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "staticfiles") ] Inside my dockerfile I define the following: ENV HOME=/home/foo-app ENV APP_HOME=/home/foo-app/web RUN mkdir $APP_HOME WORKDIR $APP_HOME and later I simply copy the entire project in using COPY . $APP_HOME All other file show up perfectly fine, and I have tried remove and … -
How to do long running process in Django view?
I have a django web application and I have to create model for Machine Learning in a view. It takes so long time so PythonAnyWhere does not allow it and it kills the process when it reaches 300 seconds. According to that, i want to ask two questions. 1- Without celery, django bg task or something else, my view which contains the long running process does not work in order. But when I use debugger, it works correctly. Probably, some lines of code try to work without waiting for each other without debugger. How can i fix this? 2- PythonAnyWhere does not support celery or other long running task packages. They suggest django-background-tasks but in its documentation, the usage is not explained clearly. So I could not integrate it. How can i integrate django-background-tasks? Thank you. -
Many to Many relation with custom table in Django
I have two models with many to many relationships with custom table such as Clinic and Doctor and custom table DoctorClinic. how could I get the list of Doctors based on Clinics? this is my views.py class ClinicDetailView(generic.DetailView): model = Clinic def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['doctor_list'] = self.doctor_set.annotate( shift=F('doctor_list__shift'), timming=F('doctor_list__timming') return context I got the error object has no attribute doctor_set here is my models.py class Clinic(models.Model): name = models.CharField(max_length = 256) area = models.ForeignKey(Area, on_delete=models.CASCADE,default=None,null=True) city = models.ForeignKey(City, on_delete=models.CASCADE,default=None,null=True) address = models.TextField() contact = models.CharField(max_length = 18) category = models.CharField(max_length=30,choices = CHTYPE) lat = models.FloatField() lon = models.FloatField() class Doctor(models.Model): name = models.CharField(max_length = 256) speciality = models.CharField(max_length = 256) contact = models.CharField(max_length = 12) speciality = models.ForeignKey(Speciality, on_delete=models.CASCADE) clinic_hospital = models.ManyToManyField(Clinic, through='DoctorHospital') class DoctorHospital(models.Model): clinic = models.ForeignKey(ClinicHospital, on_delete=models.CASCADE) doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) shift = models.CharField(max_length=10) # time_from = models.DateTimeField(auto_now_add=False,blank=True) # time_to = models.DateTimeField( auto_now_add=False,blank=True) timing = models.CharField(max_length=20,blank=True) and here is my urls.py path('clinichospital/<int:pk>/',views.ClinicHospitalDetailView.as_view(),name = 'clinichospital_detail') please help me how can doctor list I show. -
Maintaining wagtail in production
I work at a small size agency, and we now have several sites running Wagtail in production with kubernetes hosted in containers. We are trying to figure out a way to make the maintenance of these sites as easy as possible. For example with the wordpress sites we are maintaining we have a central repo which hosts the current wordpress core that all sites are running that we can deploy to to update all sites to the latest versions at once. In wagtail this is different, we use pypi to install it as a package, and we might need to run migrations as well. Does anyone have a suggested approach to make the handling of multiple wagtail sites as easy as possible, preferably push once, update all? -
How to save image in base64 format as file in secure way?
My try: import base64 def form_valid(self, form): self.object = form.save(commit=False) if self.request.POST.get('image_as_base64', None): format, imgstr = self.request.POST.get('image_as_base64').split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(imgstr)) file_name = "'temp_name." + ext self.object.receipt.save(file_name, data, save=True) Do you see any security problems? The value in the frontend is generated in this way (Vue.js method): saveMapAsImage() { this.printPlugin.printMap('A4Portrait page', 'Miles'); self = this; this.routingMap.on('easyPrint-finished', e => { var reader = new window.FileReader(); reader.readAsDataURL(e.event); // e.event is a Blob object reader.onloadend = function () { base64data = reader.result; self.image_as_base64 = base64data; } }); } HTML <input v-model="image_as_base64" type="hidden" id="id_image_as_base64" name="image_as_base64"/> -
Why is collectstatic not copying all my directories?
Currently working on deployment for my django website. Im trying to get my static files working so obviously I used this command: python manage.py collectstatic. Once finished running it prints 119 files copied... I thought this was working until I cd'd into the newly created static directory and didn't find my css folder. Weirdly enough, I did see the admin folder. Once I saw this, I deleted my static folder entirely and attempted to directly copy the static folder using scp. I did this and all of my other folders (css, uploads, etc. And also the admin folder) appeared. I tried to collectstatic now with all of the folders there only to find out when I do that, it deletes all of my folders except for the admin folder. When I start the website up using the runserver command. There is no css on my homepage but there is in the admin page. Any help is very much appreciated!! Thanks in advance! -
How to save image in base64 format as file in secure way?
My try: import base64 def form_valid(self, form): self.object = form.save(commit=False) if self.request.POST.get('image_as_base64', None): format, imgstr = self.request.POST.get('image_as_base64').split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(imgstr)) file_name = "'temp_name." + ext self.object.receipt.save(file_name, data, save=True) Do you see any security problems? The value in the frontend is generated in this way (Vue.js method): saveMapAsImage() { this.printPlugin.printMap('A4Portrait page', 'Miles'); self = this; this.routingMap.on('easyPrint-finished', e => { var reader = new window.FileReader(); reader.readAsDataURL(e.event); // e.event is a Blob object reader.onloadend = function () { base64data = reader.result; self.image_as_base64 = base64data; } }); } HTML <input v-model="image_as_base64" type="hidden" id="id_image_as_base64" name="image_as_base64"/> -
Wagtail Inline Panel - Sort Order
So I'm struggling with ordering the choices within an InlinePanel (for an orderable) on my site. In the admin page, when adding a new item, the options are presented in the order they were added to the site (so, essentially the 'id' for that item); this is less than ideal considering there are hundreds of options presented in a manner that is not user friendly. I'm assuming this needs to be defined as ordering meta within the orderable, but I can't seem to get it to work. This is what my orderable looks like: class RelatedPeople(Orderable): service = ParentalKey('service.Services', related_name='related_person') person = models.ForeignKey('person.People', null=True, on_delete=models.SET_NULL, related_name='related_service') panels = [ FieldPanel('person') ] I've tried the following with no success: class Meta: ordering = 'person' and, trying to append the field within 'person' that I want to sort by, 'name': class Meta: ordering = 'person.name' There must be an obvious way to solve this that I'm over looking. A default sort order of the 'id' (in this case, for 'person.People') is rarely ever going to be suitable from the perspective of the content creator. Any advice would be greatly appreciated! Thanks in advance, Rob -
How do I assign an id/pk number to an existing user?
first time poster, new coder. Forgive my ignorance! I am trying to query the id/pk of users in my user table in the python shell but it is telling me that my users don't have that attribute. I thought that was created automatically? Since it is clearly not, how do I assign my existing users id numbers and how do I make sure new users are automatically assigned id numbers going forward? Thanks in advance! >>>user = User.objects.filter(username='alice') >>>user <QuerySet [<User: alice>]> >>>user.id Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'QuerySet' object has no attribute 'id' >>> user.pk Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'QuerySet' object has no attribute 'pk' -
Update html columns and tables when database is changed by using Ajax, jquery. Django
I'm new in using Ajax and javascript. I have an HTML page which will show the shopping status from customers. Like the picture below. I would like to use Ajax and jquery to implement something like when the customer gets more products or put products back, the database will be updated, and the webpage will display immediately without refresh the webpage by using ajax. Also, it will calculate the total price. And when the new customer comes in or checks out, the new column will be added or removed. I have google how to use long polling: test.js $(document).ready(function(){ pollServer(); }); var url='127.0.0.1:8000/test/' var isActive = true; function pollServer() { if (isActive) { window.setTimeout(function () { $.ajax({ url: "http://127.0.0.1:8000/test/", type: "POST", success: function (result) { // alert('TTTT'); pollServer(); }, error: function () { // alert("FFFFFFF"); pollServer(); }}); }, 3000); } } test.html <div class="container custom-container-width" style="text-align=center;" > <div class="row gap-buffer" > {% for customer in Customer %} <div class="col-sm-3 p-3 gap-buffer colsize " style="background-color:white;box-shadow: 10px 10px 5px grey; " > <div class="profilesize"> <img src="{{ MEDIA_URL }}/{{customer.uuid}}/{{customer.uuid}}.jpeg" width=192 height=108 > </div> <br> <div> <div class="table-responsive" > <table > <thead class="thead-dark " > <tr > <th>Product</th> <th>Count</th> <th>Price</th> <th>Subtotal</th> </tr> </thead> <tbody … -
Django CKEditor widget auto width
How to make my 'CKEditorUploadingWidget' from ckeditor to automatically change width? I'm using 'as_crispy_field' from 'crispy_form_tags' for vanilla django widgets, which makes them change their width automatically. Since 'CKEditorUploadingWidget' is not vanilla django widget, 'as_crispy_field' doesn't work with it. How do I make it to change width automatically? -
Get single record from db in Django
VIews.py from .models import Customer as CustomerModel class Balance_Enquiry(TemplateView): template_name = 'balance_enuiry.html' def get(self, request, *args, **kwargs): if "user_id" in request.session: try: customer = CustomerModel.objects.get(user_id=request.session["user_id"]) args = {'form': form, 'posts': customer} return render(request, self.template_name, args) except Exception as e: return HttpResponse('failed: {}'.format(e), 500) Template ` {% extends 'home.html' %} {% load crispy_forms_tags %} {% block title %}Balance Enquiry{% endblock %} {% block content %} <form method="get" > {% csrf_token %} <table border="5"> <tr> <th>Amount</th> <th>Contact</th> {% for get in customer %} <tr> <td>{{ get.amount }}</td> <td>{{ get.contact }}</td> </tr> {% endfor %} i just want to get single person record after login it show the record of that person but it not show anything on screen it show just blank and even not got any error -
MultiValueDictKeyError during form submission
Previously I checked to see that there were some double names but i checked everything and still getting a MultiValueDictKeyError in idcard,I don't know what's causing this error as soon as I submit the form I get this error. <body ng-app=""> {% extends "pmmvyapp/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content%} <div class="col-md-8"> <form method="post" action="/personal_detail/"> {% csrf_token %} <div class="form-group"> <div class=" mb-4"> <h6><u>(*Mandatory Fields)Please Fill up the details below </u></h6> </div> <legend class="border-bottom mb-4" ,align="center">1.Beneficiary Details</legend> <label for="formGropuNameInput">Does Beneficiary have an Adhaar Card?*</label> <input type="radio" name="showHideExample" ng-model="showHideTest" value="true">Yes <input type="radio" name="showHideExample" ng-model="showHideTest" value="false">No <!--logic for yes--> <div ng-if="showHideTest=='true'"> <div class="form-group"> <label for="formGropuNameInput">Name of Beneficiary(as in Aadhar Card)*</label> <input name="beneficiary_adhaar_name" class="form-control" id="formGroupNameInput" placeholder="Enter name of Beneficiary as in Aadhar Card" required> </div> <div class="form-group"> <label for="formGropuNameInput">Aadhaar Number(Enclose copy of Aadhaar Card)*:</label> <input name="adhaarno" class="form-control" id="aadhar" pattern="^\d{4}\s\d{4}\s\d{4}$" placeholder="Enter Aadhar Card number with proper spacing" required> </div> <!--<div class="custom-file"> <input type="file" class="custom-file-input" id="customFile" name="adhaaarcopy"> <label class="custom-file-label" for="customFile">Choose file</label> </div>--> </div> <!--logic for no--> <div ng-if="showHideTest=='false'"> <div class="form-group"> <label for="formGroupDistrict">Please provide any of the following Identity Card*:</label> <select name="idcard" id="formGroupDistrict" required> <option>Bank or Post Office photo passbook</option> <option>Voter ID Card</option> <option>Ration Card</option> <option>Kishan Photo Passbook</option> <option>Passport</option> <option>Driving … -
djangorestframework_simplejwt refresh token
I am trying to implement JWT authentication on a DjangoRestFramework back-end using djangorestframework_simplejwt package. I am following the steps in the following link [https://simpleisbetterthancomplex.com/tutorial/2018/12/19/how-to-use-jwt-authentication-with-django-rest-framework.html][1] The front end will be developed in Angular. My understanding: Now JWT returns an access token(short lived) and a refresh token(lives for long say 24 hrs). The access token expires say after say 5 minutes. Now we need to send the refresh token to the back-end to get a new access token with new expiry. My confusion is, will the refresh token be used to renew the access token implicitly without the knowledge of the user? If yes what kind of action should trigger this action. For e.g, if the user is idle for 5 minutes after logging in, and then clicks on some link that hits a back-end rest API, will I refresh the access token implicitly? If yes, then why not just have one token that has a long expiry duration, when we are allowing access anyway? Another question is what if I just want the token to be sent back from the back-end without any user information embedded for security reasons? Is this possible using this package? Thanks in advance -
Django cache. ManifestStaticFilesStorage
I have just started to use ManifestStaticFilesStorage and I am running into a problem I do not understand. Firstly, if I prepare and run the website without ManifestStaticFilesStorage, then everything displays properly. Within the browser I can for example, see a link to an image and if I follow that it shows the image in a resource box: Next, I add the following line of code into settings STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' and I also have: STATIC_ROOT = os.path.join(BASE_DIR, "static") I then delete the static directory and rebuild everything (migrations, collect static). This produces a website with the following link to an image, but the resource is not visible: However, when I go into the static folder in my project and look at the directory, I can see the file clearly and as far as I can tell, it appears normal: It's like Django is failing to link up correctly when I use ManifestStaticFilesStorage. I have included some other settings that may be relevant: STATIC_URL = '/static/' # STATIC_ROOT = 'static' STATIC_ROOT = os.path.join(BASE_DIR, "static") STATICFILES_DIRS = [ './ebdjango/static/', ] I'm new to this, so if you have any suggestions on how to proceed with the cache in Django, please let … -
How to get distinct results when ordering by a related annotated field?
This is a Django (2.2) project using Python (3.7). Given the following models, how would I get distinct results in the query below? class Profile(models.Model): user = models.ForeignKey(User, ...) class Location(models.Model): profile = models.ForeignKey(Profile, ...) point = PointField() class ProfileService(models.Model): profile = models.ForeignKey(Profile, ...) service = models.ForeignKey(Service, ...) Here's the query I have so far which works but I end up with duplicate 'ProfileService' objects: qs = ( ProfileService.objects .annotate(distance=Distance('profile__location__point', self.point)) .order_by('distance') ) If I add .distinct('profile') it obviously fails with SELECT DISTINCT ON expressions must match initial ORDER BY expressions. I have a feeling that the solution lies in using __in but I need to keep the annotated distance field. Thanks in advance. -
Django showing custom URLs to different users
How can I display different URLs to different users based on their user_id? For example, when the user is logged in, in the dashboard user 1 with user_id 1 should have a button with a default URL like https://www.example.com/user_id so that his URL will be https://www.example.com/1 while user 2 with user_id 2 should see the URL https://www.example.com/2. I have no idea how I could achieve that. Do I need to edit the models, views or URLS file and what do I need to add? Your help is highly appreciated. -
How to JSON serialize APIField of StreamField using a ListBlocks of PageChooserBlocks
hi guys my head is spinning trying to figure this out. I cant get a response from a streamfield api using blocks.PageChooserBlock. I need to deserialize the JSON but am out of juice. I get this error Object of type 'TimelineEvent' is not JSON serializable This is the Page class Timeline(Page): content = StreamField([ ('title', blocks.CharBlock(classname="full title")), ('time_period', TimePeriodBlock()) ]) content_panels = Page.content_panels + [ StreamFieldPanel('content') ] api_fields = [ APIField("title"), APIField("content") ] I'm able to get data from TimePeriodBlock and it looks like this class TimePeriodBlock(blocks.StructBlock): def get_api_representation(self, value, context=None): dict_list = [] for item in value: temp_dict = { 'period_name': value.get("period_name"), 'description': value.get("description"), 'duration': value.get("duration"), 'events': value.get('events') } print(value.get('events')) dict_list.append(temp_dict) return dict_list period_name = blocks.CharBlock() description = blocks.CharBlock() duration = blocks.CharBlock() events = blocks.ListBlock(EventBlock()) BUT can't get anywhere near EventBlock class EventBlock(blocks.StructBlock): def get_api_representation(self, value, context=None): dict_list = [] print('here') print(value) for item in value: temp_dict = { # 'event': item.get("event"), 'short_desc': item.get("short_desc"), } dict_list.append(temp_dict) print(dict_list) return dict_list event = blocks.PageChooserBlock(page_type=TimelineEvent) short_desc = blocks.CharBlock(max_length=250) Event looks like this [StructValue([('event', <TimelineEvent: Dance 1700 fandango and jota >), ('short_desc', 'first event')]), StructValue([('event', <TimelineEvent: Dance 1700 contredanse>), ('short_desc', '2nd event')])] [StructValue([('event', <TimelineEvent: Dance 1937 Trudl Dubsky>), ('short_desc', '3rd')])] -
Django toolbar via url?
I am trying to implement debug_toolbar, Can you tell me how to use these kinds of url ^__debug__/ ^render_panel/$ [name='render_panel'] ^__debug__/ ^sql_select/$ [name='sql_select'] ^__debug__/ ^sql_explain/$ [name='sql_explain'] ^__debug__/ ^sql_profile/$ [name='sql_profile'] ^__debug__/ ^template_source/$ [name='template_source'] I tried hitting this url localhost:8000/__debug__/sql_explain/ but am getting either a 404 or or form errors -
Django annotate field not passed to serializer
I'm a little frustrated about why this does not work. Models: class User(models.Model): ... class Group(models.Model): ... class Member(models.Model): user = models.ForeignKey(User, related_name='groups') group = models.ForeignKey(Group, related_name='members') field1 = models.IntergerField() View: def get_queryset(self): Group.objects.filter(members__user=self.request.user).annotate(field1=F('members__field1')) Serializer: field1 = serializers.SerializerMethodField() def get_field1(self, obj): return obj.field1 Getting the error object has no attribute 'field1' However, using the same query in shell window successfully retrieves value for field1 g = Group.objects.filter(members__user=self.request.user).annotate(field1=F('members__field1')) print(g[0].field1) Successfully prints field1 value -
Django template: How to pass formatted string to include tag
I am new to Django and Django template, I know Django Template is kind of restrictive compare to Rails. So I am including a template in email like: {% include "./partials/_info_row.html" with value=f'{request_count} requests' %} but this throws error: TemplateSyntaxError: Could not parse the remainder: ''{request_count} requests'' from 'f'{request_count} requests'' Is there a way to pass formatted string like this to include tag? -
In Django forms, logical validation for the field
I've three fields in my model phone number, email & passworduser model. In forms, I'm using two fields phone_number & passwordforms. I write functionality for user able to login using phone number and email also. login functionalitiesIts working fine. In Front end, I'm using Bootstrap Modal form pop up. it also working fine. Problem is my error message. If wrong password, wrong password for phone number fieldit will pop up show error message in form itself, this is working. When I give doesn't exists, here I'm facing issue. when I give email ID,email field doesn't exists its pop up but when I use phone number its not coming. I don't know, where I made mistake -
why there is like Bunch of backslash in my JSON output
I m trying to send model data as json using below code Views.py def autocomplete(request): model = NewCarModel.objects.only('car_model_new') print('model is',model) # users_list = list(model) posts_serialized = serializers.serialize('json', model) print('post is',posts_serialized) return JsonResponse(posts_serialized,safe=False) models.py class NewCarModel(models.Model): car_model_new = models.CharField(max_length=100, unique=True) def __str__(self): return self.car_model_new output: "[{\"model\": \"core.newcarmodel\", \"pk\": 1, \"fields\": {\"car_model_new\": \"swift\"}}, {\"model\": \"core.newcarmodel\", \"pk\": 2, \"fields\": {\"car_model_new\": \"wagonr\"}}, {\"model\": \"core.newcarmodel\", \"pk\": 3, \"fields\": {\"car_model_new\": \"baleno\"}}, {\"model\": \"core.newcarmodel\", \"pk\": 4, \"fields\": {\"car_model_new\": \"breeza\"}}, {\"model\": \"core.newcarmodel\", \"pk\": 5, \"fields\": {\"car_model_new\": \"spresso\"}}]" why there is bunch of backslash in my JSON output and how i can remove them and Mozilla Firefox default JSON filter is also not working, neither i am able to extract data from it using java script(as i am able to extract data from some public API so there is no problem with extract code) -
Adding objects to users in Django
I am very new to Django and I am trying to build a web app that users can add the books they read and see other users that read the same book. How can I do this in Django? What functions should I add? -
how do i send ajax request by using onclick event without form enclosed tags in django
actually i have a div content,i have apply onclick event on that div when user click on that div the text between these tags should be sent to server and then display in the table as well.i have done something guid me where is the error actually,because $.ajax not working it raising an error e.g: $.ajax is not fnction players.html <div class="selectize-control single"> <div class="selectize-input items has-options not-full"> <input type="text" autocomplete="off" tabindex="" id="select_player" style="width: 146.75px; opacity: 1; position: relative; left: 0px;" placeholder="Adauga jucator la echipa"> </div> <div class="selectize-dropdown single liststyle" id="listitems" style="display: None; width: 987px; top: 29px; left: 0px; visibility: visible;"> <div class="selectize-dropdown-content"> {% block listplayers %} {% if player is not None %} {% for p in player %} <div class="option selected curserstyle sp" id="{{p.id}}" data-selectable="" data-value="{{p.YourName}}">{{p.YourName}}1</div> <div class="option selected curserstyle sp" id="49" data-selectable="" data-value="{{p.YourName}}">{{p.YourName}}2</div> {% endfor %} {% else %} <div class="text-center"> List is Empty </div> {% endif %} {% endblock %} </div> </div> </div> javascript $("#listitems").on('submit',function(e){ // preventing from page reload and default actions e.preventDefault(); // serialize the data for sending the form data. var serializedData = $(this).serialize(); // make POST ajax call $.ajax({ type:'get', url:"/templates/dashboard/players", data:serializedData, success:function(responce){ // on successfull creating object // 1. clear the …