Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issues playing mp4 on apple on django website
I'm building a Django website. My users can record a video and then others can see these videos. The recording is done with javascript: const mimeType = 'video/mp4'; shouldStop = false; const constraints = { audio: { echoCancellation: true, noiseSuppression: true, }, // audio: true, video: { width: 480, height: 480, facingMode: 'user', }, }; const stream = await navigator.mediaDevices.getUserMedia(constraints); const blob = new Blob(recordedChunks, { type: mimeType }); And the sent to a django view: let response = await fetch("/send-video/", { method: "post", body: blob, headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', "X-CSRFToken":csrftoken, }, }).then( ... ) In my views if request.method == 'POST': user = request.user file_name = f"{user}.mp4" if (len(sys.argv) >= 2 and sys.argv[1] == 'runserver'): file_path = file_name else: file_path = f"{your_media_root}temp/{file_name}" webm_bytes = bytes(request.body) video_file = open(file_path, "wb") video_file.write(webm_bytes) if mimetypes.guess_type(file_path)[0].startswith('video/mp4'): print(mimetypes.guess_type(file_path)) video_file.close() else: video_file.write(b"") video_file.close() Now I can save these files to a django model field. I use django-private-storage to make sure only users with the correct authentication can view the files. django-private-storage uses a FileReponse to play the video. and it generates a template with: <video controls="" autoplay="" name="media"> <source src="http://127.0.0.1:8000/play-job-video/" type="video/mp4"> </video> All works fine on any browser on android. I can record … -
How to store 2D Array in model of Django
Problem: I am in need to store 2D array in one of the field of the Table. Example id:1 Teacher_name:"Amit" time: [[9:00am, 2:00pm], [2:00pm,6:00pm], [6:00am, 9:00pm]] # Need to store 2-D array kind of multiple time stamps in a field, code is here: Model.py class ScheduleClassification(models.Model): vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, null=True) id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=1000) start_date = models.DateField(auto_now_add=True) end_date = models.DateField(auto_now_add=True) duration = models.CharField(max_length=20, default="forever") day_type = models.CharField(max_length=20) time = #how do i make this field how can i store this please let me know the best way to do this. in django models -
I don't know how to resolve this error 'RemovedInDjango110Warning'
when I created the project. And run the server I got the error django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'django.templatetags.future': cannot import name 'RemovedInDjango110Warning' -
How to reorder Wagtail admin menu items
There are some custom menu items in the admin's menu, it is easy to order them (the items marked in red below). Just set menu_order of the custom ModelAdmin object. The question is how to reorder the built-in menu items, such as Pages, Images, Media, and Settings. -
django Queryset status count between week dates inappropriate data is coming
I want to calculate the active status count between week dates. what I am trying that is given below. date_list : ['2022-04-06', '2022-04-13', '2022-04-20', '2022-04-27', '2022-05-04', '2022-05-11', '2022-05-18', '2022-05-25', '2022-06-01', '2022-06-08', '2022-06-15', '2022-06-22', '2022-06-29'] def get_status_count(date_list): status_dict = [] for i in range(0,len(date_list)): week_list = date_list[i:i-7] print(week_list,'ttttttttt') datetime_object = datetime.strptime(str(date_list[i]), '%Y-%m-%d') last_date = datetime_object + timedelta(days=-7) dateStr = last_date.strftime("%Y-%m-%d") tsts = [dateStr,date_list[i]] count = Status.objects.filter(arrival_date__range = tsts).values("arrival_date").annotate(dcount=Count('arrival_date')) status_dict.append({"date" : date_list[i],"count":count}) return status_dict Output i am getting like : {'date': '2022-04-06', 'count': <QuerySet [{'arrival_date': '2022-04-06', 'dcount': 1}]>}{'date': '2022-04-13', 'count': <QuerySet [{'arrival_date': '2022-04-06', 'dcount': 1}]>}{'date': '2022-04-20', 'count': <QuerySet []>}{'date': '2022-04-27', 'count': <QuerySet []>}{'date': '2022-05-04', 'count': <QuerySet []>}{'date': '2022-05-11', 'count': <QuerySet []>}{'date': '2022-05-18', 'count': <QuerySet []>}{'date': '2022-05-25', 'count': <QuerySet []>}{'date': '2022-06-01', 'count': <QuerySet []>}{'date': '2022-06-08', 'count': <QuerySet []>}{'date': '2022-06-15', 'count': <QuerySet []>}{'date': '2022-06-22', 'count': <QuerySet []>}{'date': '2022-06-29', 'count': <QuerySet [{'arrival_date': '2022-06-28', 'dcount': 1}, {'arrival_date': '2022-06-29', 'dcount': 1}]>} But it is not coming as I want data like : [{'arrival_date': '2022-04-06', 'dcount': 1},{'arrival_date': '2022-04-13', 'dcount': 2},{'arrival_date': '2022-04-20', 'dcount': 0}, and so on.....] In database data I have : +----+-----------+--------+-------------+--------------+--------------+--------+ | id | number | state | name | checker_name | arrival_date | locals | +----+-----------+--------+-------------+--------------+--------------+--------+ | 1 | 1665022 | close | ab | … -
Django, Heroku - [remote rejected] main -> main(pre-receive hook declined)
I am reading the Django for Beginners book to learn deploy django app. From Chapter 3: Pages App, deployment with heroku is taught. However everytime I follow the steps for deployment I get the same error everytime, similar to something shown below with different heroku url. ! [remote rejected] main -> main (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/afternoon-anchorage-50413.git' -
django: how to control user access to web content with limited allowence per day?
I have an online pricing website using django. Now I want to restrict non-vip users to use my website to obtain price. For non-vip users, after login they can only use my web to get price only 3 times per day. If they click "get price" button the fourth time during the day, there should be an alert message showing "non-vip users can only check price 3 times per day" Can we do this directly in frontend using javascripts? -
TemplateSyntaxError at /comments/10/ Could not parse the remainder: '==comm.user.id' from 'request.user.id==comm.user.id'
After using for loop I get a specific comment and its related user and only want to delete the comment if that user has written it. How to write variable inside {% if ---%}. Template error: In template C:\Users\SHAFQUET NAGHMI\socialnetwork\socialapp\templates\socialapp\comment.html, error at line 27 Could not parse the remainder: '==comm.user.id' from 'request.user.id==comm.user.id' 17 : <P>Please <a href="{% url 'login' %}">login</a> to add comment </P> 18 : 19 : {% endif %} 20 : </form> 21 : <h3>comments..</h3> 22 : 23 : {% for comm in comments %} 24 : 25 : <a class="comment-user" href="{% url 'profile' comm.user.username %}">{{comm.user}}</a> 26 : {{comm.comment}} 27 : {% if request.user.id==comm.user.id %} 28 : <a class="delete" href="/delete_comment/{{post.id}}/{{comm.id}}/">Delete</a> 29 : {% endif %} 30 : <br><br> 31 : {% endfor %} 32 : <!--{{post}} {{comm.id}}--> 33 : 34 : </div> 35 : </div> 36 : {% endblock %} -
How to store fetched data in Django?
I don't understand how to store or where to store large data when Django app is running. IDEA: I have data in postgreSQL and time to fetch it is about 10-20sek (that's not a point). Then I run Django app with Nginx and run it with some workers. And when rach worker open specific URl fetch function runs and fetch data from DB (10-20sek), but data for each worker is SAME. I want to fetch data from DB and store it somewhere, and when each worker open specific URL it doesn't need to fetch data, but it is also fetched and just return data. What is main approach on that situation? -
How to ignore some errors with Sentry (not to send them)?
I have a project based on django (3.2.10) and sentry-sdk (1.16.0) There is my sentry-init file: from os import getenv SENTRY_URL = getenv('SENTRY_URL') if SENTRY_URL: from sentry_sdk import init from sentry_sdk.integrations.django import DjangoIntegration from sentry_sdk.integrations.redis import RedisIntegration from sentry_sdk.integrations.celery import CeleryIntegration init( dsn=SENTRY_URL, integrations=[DjangoIntegration(), RedisIntegration(), CeleryIntegration()], traces_sample_rate=1.0, send_default_pii=True, debug=True, ) I have a CustomError inherited from Exception Every time I raise the CustomError sentry-sdk sends it to the dsn-url. I want to ignore some class of error or something like this. How can I do this? -
want to be able to do the post method and display the data in the table field
currently when i submit the function first takes me to the api page where i have to click on post again for the results to update in the database then click on back button and refresh the page to see the updated data, it will be nice if the reduce button could update and display the data on the table without redirecting to the api page. Thank You, Please Help. trying to render the data here @api_view(['POST']) def sRd(request, pk): sw = get_object_or_404(Swimmers,id=pk) # gets just one record current_sessions = sw.sessions + 10 sw.sessions = current_sessions # updates just the one in memory field for sw (for the one record) sw.save() # you may want to do this to commit the new value serializer = SubSerializer(instance=sw, data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, safe=False, status=status.HTTP_201_CREATED) return JsonResponse(data=serializer.errors, safe=False, status=status.HTTP_400_BAD_REQUEST) Want to render the data here on this page: return render(request, 'accounts/modals/swimming/_vw_table.html', {'sw': sw}) -
Fastest way to count Django manytomanys?
What is the fastest way to count Django manytomanys? I have hundreds of thousands rows of data, and I want to count answers. Need are: how many objects where answer is not null and answer's counts per Option. Models: class Option(models.Model): text = models.CharField(max_length=255, blank=False) class MultiChoiceAnswer(models.Model): user = models.ForeignKey(User) answers = models.ManyToManyField( Option, blank=True, verbose_name=_("options"), ) -
How to get country flag selected on edit html form?
I am trying to do get country code selected on edit form but somehow it's not appear while during update form. if field has no country code then it's showing flag icon in field but if it's county code is there then no flags icon will be there on contact field. it's working very well on For Insert User but some how it's not working for edit. I don't know what's issue is there. I am not sure there is issue of two same fields with same id's javascript is conflict or may be there is another issue? and all form element is running in for loop . in django python HTML CODE : <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.17/js/intlTelInput.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.17/css/intlTelInput.css" rel="stylesheet"/> <div class="form-row"> <div class="form-group col-md-6 smsForm2"> <label for="contact1">SMS No.<span style="color:#ff0000">*</span></label> <input type="tel" class="form-control" name="smsno2" id="smsno2" value="{{vr.sms_no}}" placeholder="SMS No." pattern="^(00|\+)[1-9]{1}([0-9][\s]*){9,16}$" required onkeyup="myFunctionsms(this)" /> <div class="custm-valid" id="sms_validate" style="display:none;color: #28a745;font-family: 'Inter',sans-serif;font-weight: 400;font-size: 80%;">Valid.</div> <div class="custm-invalid" id="sms_ntvalidate" style="display:none;font-family: 'Inter',sans-serif;font-weight: 400;font-size: 80%;color: #dc3545;">Please enter valid contact no.</div> </div> <div class="form-group col-md-6 whatsappForm2"> <label for="contact2">WhatsApp No.<span style="color:#ff0000">*</span></label> <input type="text" class="form-control" name="whtspno2" id="whtspno2" value="{{vr.whtsp_no}}" placeholder="WhatsApp No." pattern="^(00|\+)[1-9]{1}([0-9][\s]*){9,16}$" required onkeyup="myFunctionwhtsapp(this)" /> <div class="custm-valid" id="whts_validate"style="display:none;color: #28a745;font-family: 'Inter',sans-serif;font-weight: 400;font-size: 80%;">Valid.</div> <div class="custm-invalid" id="whts_ntvalidate" style="display:none;font-family: 'Inter',sans-serif;font-weight: 400;font-size: 80%;color: #dc3545;">Please enter valid contact … -
django-elasticsearch-dsl NestedField not syncing with database
I've created a django-elasticsearch-dsl document with NestedField but for some reason data for this NestedField is not fetched from the database, even though data is fetched from the base model. Mapping for index is also correct including the nested field: { "mappings": { "properties": { "addresses": { "type": "nested", "properties": { "pk": { "type": "integer" }, "postal_code": { "type": "text" }, "street_name": { "type": "text" }, "street_no": { "type": "integer" } } }, "country": { "type": "text" }, "name": { "type": "text" } } } } I did everything according to the official docs, I don't know what am I missing. models.py from django.db import models # Create your models here. class City(models.Model): name = models.CharField(max_length=100) country = models.CharField(max_length=100) def __str__(self): return f"{self.name}, {self.country}" class Address(models.Model): city = models.ForeignKey( City, on_delete=models.CASCADE, related_name="related_city" ) street_name = models.CharField(max_length=300) street_no = models.PositiveIntegerField() postal_code = models.CharField(max_length=6) def __str__(self): return f"{self.street_name} {self.street_no} ({self.city.name})" documents.py from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry from .models import City, Address @registry.register_document class CityDocument(Document): addresses = fields.NestedField( properties={ "street_name": fields.TextField(), "street_no": fields.IntegerField(), "postal_code": fields.TextField(), "pk": fields.IntegerField(), } ) class Index: name = "cities" class Django: model = City fields = ["name", "country"] related_models = [Address] def get_queryset(self): return … -
Set django url using jquery
How can I set url with params in django temple from jquery ? My template.html <div id="buynow"> <div> <a id="myLink" href="" class="btn btn-outline-secondary">Buy now</a> </div> </div> My jquery.js var fee = "200"; var total = "1000"; $('#buynow').click(function(){ $('#myLink').prop('href', '/payment/'+parseInt(getAmounts)+'/'+parseInt(totals)+'/'); }); My urls.py urlpatterns = [ path('payment/<int:fee>/<int:total>/', views.payment, name='payment'), ] -
Python django project unable to use .scss files in my project
I am using pre built template in python django project it has .css and .scss files . I am not able to style the project and use use .scss file in my project -
The current path, didn’t match any of these
Hi I am new to django and I have been making a CRUD project,while pressing the 'EDIT' button the below error comes heres the code in views.py def edit_cat(request,id): if request.method == 'GET': print('GET',id) editcategory = Categories.objects.filter(id=id).first() s= CategoriesSerializer(editcategory) return render(request,'edit_cat.html',{"Categories":s.data}) else: print('POST',id) editcategory = {} d = Categories.objects.filter(id=id).first() if d: editcategory['name']=request.POST.get('name') editcategory['description']=request.POST.get('description') print(editcategory) # Updateemp = EmpModel.objects.get(id=id) #print(Updateemp) form = CategoriesSerializer(d,data=editcategory) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') return redirect('categories:show_cat') else: print(form.errors) urls.py from django.urls import path from categories import views from django.urls.conf import include from django.conf import settings from django.conf.urls.static import static urlpatterns=[ path('',views.show_cat,name="show_cat"), path('insert_cat/',views.insert_cat,name="insert_cat"), path('edit_cat/<int:id>/',views.edit_cat,name="edit_cat"), path('del_cat/',views.del_cat,name="del_cat") ] is there a silly mistake I have made in the codes? please help -
How to call Dajngo render view from another APP render view template
I have two apps with one render view in each. First view. This selector HTML have the drop-down boxes with the options for the user to choose nothing else than this. def selectionView(request, *args, **kwargs): return render(request, 'selector.html') Second view def dataView(request, *args, **kwargs): //code here to look into the database and then use the data in the HTML. //The filter will be taken from the dropdown box created in the above //selector.HTML FILE. return render(request,'tableContent.html', {'users': users}) My question here is there any way I can call the data view with values of dropdown box passed using JQuey or javascript or python from the first view. What I am looking for? Use the selection view as a landing page with the drop-down options and then use that dropdown option to call the data view and show the results. The records received are in thousands. Question? Is there any way I can do this like calling the render view from the HTML template of other Django view and passing the dropdown values as parameters to the view I want to call -
Running django tests in github actions causes Error code 137
I have an app made up of multiple containers that I run with docker-compose. I've tried adding a .yml file to my .github/workflows folder in order to run unit tests on every push to the repo. The containers start up fine but when it comes to the step for running the tests, there is an error: Error: Process completed with exit code 137. After looking up that exit code online, I found that this is a memory error but I can't figure out what is causing it and how to fix it. Here is my .yml file for running the tests. name: django-tests on: push: branches: [develop] jobs: start_docker: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Create env file run: | touch .env echo POSTGRES_ENGINE=${{ secrets.POSTGRES_ENGINE }} >> .env echo POSTGRES_DATABASE=${{ secrets.POSTGRES_DATABASE }} >> .env echo POSTGRES_USER=${{ secrets.POSTGRES_USER }} >> .env echo POSTGRES_PASSWORD=${{ secrets.POSTGRES_PASSWORD }} >> .env echo POSTGRES_HOST=${{ secrets.POSTGRES_HOST }} >> .env echo POSTGRES_PORT=${{ secrets.POSTGRES_PORT }} >> .env echo SECRET_KEY=${{ secrets.SECRET_KEY }} >> .env cat .env mv .env project/db - name: Start containers run: docker-compose -f "docker-compose.yml" up -d --build - name: Run tests run: docker exec my_app python manage.py test - name: Stop containers run: docker-compose -f … -
Django - importing data from an external file
I have a question: I have a code in views that does the same thing (displays 2 arrays) only in an external file I have it done a little better and I would like to display this data from an external file. How to do it? Thx for your help. views. def calculate(request): ... elif request.GET.get('Automatic'): ans1 = ([x for x in range(0, 100, 1)]) # X ans2 = ([(randint(1, 100) * y) for y in range(0, 100, 1)]) # Y ans = np.concatenate([ans1, ans2]) calculate.py from random import randint import time t = time.time() class Calc: def __init__(self): pass def position(self): self.positionX = [] self.positionY = [] self.positionX.append([(randint(1, 100) * x) for x in range(1, 2, 1)]) self.positionY.append([(randint(1, 100) * y) for y in range(1, 2, 1)]) return self.positionX, self.positionY def __str__(self): return {self.positionX, self.positionY} if __name__ == '__main__': t = 0 while t < 20: hear = Calc() print('X: ', hear.position()[0], 'Y: ', hear.position()[1]) time.sleep(0.4) t += 1 template: !DOCTYPE html> <meta charset="utf-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/light.css"> <title>{% block title %}{% endblock %} </title> </head> <div class="container container-fluid text-center "> <h1>Answer is</h1> {# <h3>{{answer}}</h3>#} {% for answers in answer %} {{ answers }} {% endfor %} <br> <br> <button … -
form is not valid but Django didn`t return any error
there is two attribute 'name' and 'slug' as you can see in code I send wrong data to 'slug' and 'name' is empty but validation didn`t work. Models class Tag (models.Model): name = models.CharField(max_length=50, db_index=True) slug = models.SlugField(unique=True, help_text='a label for url config') class Meta: ordering = ['name'] def __str__(self): return self.name.title() def get_absolute_url(self): return reverse('organizer:tag_detail', kwargs={'slug': self.slug}) forms class TagForm (forms.Form): class Meta: model = Tag fields = '--all--' def clean_name (self): return self.cleaned_data['name'].lower() def clean_slug (self): new_slug = (self.cleaned_data['slug'].lower()) if new_slug == 'create': raise ValidationError('slug may not be "create".') else: return new_slug shell In [11]: from organizer.forms import TagForm In [12]: tf = TagForm({'slug': 'create'}) In [13]: tf.errors Out[13]: {} -
Create subdomains like Shopify in pythonanywhere
My domain name is 'example.com' and I need to create subdomain for every store created in that site like 'store1.examaple.com', 'store2.examaple.com'. Code for every subdomain is the same. currently my project is deployed on pythonanywhere and I already have custom domain. So is it possible to dynamically create multiple subdomain in pythonanywhere same as Shopify ? -
Adding a transient ranking field to djangorest class and serializer
I am new to djangorest and am not sure how to even go about this. I have a Rest API that takes a post-request (with a list of parameters) and returns a list of items from a model via a serializer. It all works great. I need to add a "rank" or rather a "relevancy score" to the items in my returned list. I can calculate the rank fine - I am doing it in the REST view - what I don't understand is how to pass the rank back with the serialized model class in the response. I could create an entirely new object and pass it with the item ids.... but what I would rather do is attach a transient field: {"rank": value } to each item in my list. Can I do this? -
How to apply filtering after serialization with Filter backend in DRF?
For the context I will explain the current flow: The model Document has a field document_signing_status which has 2 possible values: SIGNED/NOT_SIGNED. However, in the serializer, I override this field by having a custom SerializerMethodField() which applies some modification and instead of returning 2 values it can return 4: "EXPIRED", "WAITING_FOR_ME", "WAITING_FOR_OTHERS", "SIGNED" I don't want to store these values on the database level, but I need to apply filtering. Right now I use filters.FilterSet, but it uses QuerySet so I can't simply specify filtering fields and pass "EXPIRED" since, in the model field there is only "SIGNED" or "NOT_SIGNED". How should I approach this issue? I thought about iterating the query set and applying modifications for that field to have one from possible 4 options, instead of 2, but not sure if it is a valid point and if even possible. -
the image not displayed when i want to retrieve it from database : Django -xhtml2pdf
I need to get an image from database (entered by me on Django-admin interface), and i need to display it in my pdf generated. I have first get the image for each specifc user logged in like that in the views.py: image1_full = CustomerPersonalData.objects.get(user_related=request.user) obj_image1 = CustomerPersonalData._meta.get_field('image1') value_image1 = str(obj_image1.value_from_object(image1_full)) in the pdf_generated.html, I have define it like that: <img src={{value_image1.url}} /> ----> but like that there is no image displayed. PS: am using xhtml2pdf