Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django- get all model instances with overlapping date ranges
Lets say I have the following model: class DateRange(models.Model): start = models.DateTimeField() end = models.DateTimeField() Is there a way to get all pairs of DateRange instances with any overlap in their start to end range? For example, if I had: id | start | end -----+---------------------+--------------------- 1 | 2020-01-02 12:00:00 | 2020-01-02 16:00:00 # overlap with 2, 3 and 5 2 | 2020-01-02 13:00:00 | 2020-01-02 14:00:00 # overlap with 1 and 3 3 | 2020-01-02 13:30:00 | 2020-01-02 17:00:00 # overlap with 1 and 2 4 | 2020-01-02 10:00:00 | 2020-01-02 10:30:00 # no overlap 5 | 2020-01-02 12:00:00 | 2020-01-02 12:30:00 # overlap with 1 I'd want: id_1 | id_2 ------+----- 1 | 2 1 | 3 1 | 5 2 | 3 Any thoughts on the best way to do this? The order of id_1 and id_2 doesn't matter, but I do need it to be distinct (e.g.- id_1=1, id_2=2 is the same as id_1=2, id_2=1 and should not be repeated) -
Opencv How to Overlay Text on Video with audio file and audio and text should be in sync
I am new to OpenCV. I have created a video with text and image. it's working fine. but when I am trying to add audio to the file then audio is not getting sync with the text. I am using OpenCV and FFmpeg. also tried MoviePy but did not work. class CreateVideoFromMP3AndText(object): default_path = "new_filename.mp4" def __init__(self, text, audio, video=None): self.text = text self.audio = audio self.video = video def get_paragraphs(self): return tokenize.sent_tokenize(self.text) def convert_image_2_video(self): img_array = [] for text in self.get_paragraphs(): for filename in glob.glob(os.path.join(settings.STATIC_ROOT, "images/bg-head-01.jpg")): img = cv2.imread(filename) height, width, layers = img.shape size = (width, height) font = cv2.FONT_HERSHEY_SIMPLEX fontScale = 1 font_size = 1 color = (255, 0, 0) thickness = 2 for i in range(50): img_array.append(img) wrapped_text = textwrap.wrap(text, width=35) i = 0 for text in wrapped_text: textsize = cv2.getTextSize(text, font, font_size, thickness)[0] gap = textsize[1] + 10 y = int((img.shape[0] + textsize[1]) / 2) + i * gap x = int((img.shape[1] - textsize[0]) / 2) org = (x, y) image = cv2.putText(img, text, org, font, fontScale, color, thickness, cv2.LINE_AA) i += 1 img_array.append(image) out = cv2.VideoWriter(self.default_path, cv2.VideoWriter_fourcc(*"DIVX"), 50, size) for i in range(len(img_array)): out.write(img_array[i]) out.release() cmd = "ffmpeg -i {} -i {} -map 0:0 … -
How to present the children of a model in django html
I have a blog listing page that displays some header text and then a list of individual blog pages. models.py class BlogListingPage(Page): ... def get_context(self, request, *args, **kwargs): """Add custom content to our context.""" context = super().get_context(request, *args, **kwargs) context['blog_pages'] = self.get_children().live() return context views.py def blog(request): ... context = {'data': BlogListingPage.objects.all()} return render(request, url, context) blog_listing.html {% for obj in data %} <h2>{{ obj.blog_listing_title }}</h2> {% for post in obj.blog_pages.all %} {{ post.specific.blog_title }} <br> {% endfor %} {% endfor %} The blog_listing_title appears correctly, but I cannot find out how to access the set of blog_titles What should I do? I do not understand the structure of the PageQuerySet and how it is used by django to express the html elements -
What should I use to build a calendar web app with data from sql? [closed]
I am building a website that lists events stored in a mysql database in a calendar like: https://lectures.london/ I only know a bit of python so I am open to any other language but the simpler the better. What should I use? Can I stick with python with flask or something else? -
How to delete file from a static folder?
I have this code that deletes all the files saved in a folder and the files in the database table: def delete(request): folder = '../f2candon/andon/static/media/fileupload' for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: print(e) delet = Media.objects.all() delet.delete() return HttpResponseRedirect('/mediafile/') But I must place another one where only one file is deleted, whether it is deleted by the id, to delete it from the database I do it this way: def delete_media(request, id): delete_file = Media.objects.get(pk=id) delete_file.delete() return HttpResponseRedirect('/mediafile/') Is there a way to delete the same file from the static folder that has just been deleted in the database? The same files are found in the database and in the folder. Regards. -
Django/BooleanField: how to add space between case and label?
I have a django project I have an models with a booleanField -> checkbox in the form But I don't know why the checkbox is sticked to the label. I try to select the html element to add specific css but the 2 elements move together... current result: [ ]I have read... (the 2 elements are sticked) expected result: [ ]......I have read... models.py class Aveugle(models.Model): unb_ide = models.AutoField(primary_key=True) unb_val = models.BooleanField("I have read ITBM procedure and want to unblind treatment", null=True, blank=True) forms.py unb_val = forms.BooleanField(label = _("I have read ITBM procedure and want to unblind treatment")) -
Saving data from multiple forms in template
I have a page that has two forms. One form appears as a popup after a user clicks the edit button. I cannot save information from the form that pops up after clicking the edit button. Not sure what I am doing wrong. This is what I have in views def payment_view(request): form = MentorPaymentForm() if request.method == 'POST': form = MentorPaymentForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): user,mentor = form.save(commit=False) return redirect('teachers:payment_view') else: form = MentorPaymentForm(instance=request.user) return render(request, 'classroom/teachers/app-instructor-billing.html', {'form': form}) my template: <form id="billing_details", method="post"> {% csrf_token %} <label class="col-md-2 control-label">Account Number</label> <div class="form-group form-control-material"> {{ form.account_num }} </div> <label for="bankname" class="col-md-2 control-label">Bank Name</label> <div class="form-group form-control-material" id="bankname"> {{ form.bank_name }} </div> <label for="acc_num" class="col-md-2 control-label">Branch Code</label> <div class="form-group form-control-material"> {{ form.branch_code }} </div> <button type="submit" class="btn btn-success paper-shadow relative" data-z="0.5" data-hover-z="1" data-animated data-dismiss="modal">Update Payment Details</button> </form> and the edit button <a href="#modal-update-credit-card" data-toggle="modal" class="btn btn-white btn-flat"><i class="fa fa-pencil fa-fw"></i> Edit</a> here is what i have in urls path('payment_view', teachers.payment_view, name='payment_view'), -
The annotation '...' conflicts with a field on the model
I want to write the django equivalent to select coalesce(product_id, -1) as product_id from my_table in django. However, trying MyTable.objects.values(product_id=Coalesce('product_id', -1)) gives me the error: The annotation 'product_id' conflicts with a field on the model. This forces me to use a different name, and rename the resulting dicts in python, which is much slower than doing it in the database. Is there any way to tell django "I know what I'm doing, go on"??? -
How to pass extra kwargs to form in django modelformset factory?
How can i pass extra kwargs to django modelform in modelformset factory I want for example, disable all form fields in detail view. forms.py: class ConceptForm(forms.ModelForm): class Meta: model = app_models.Concept fields = '__all__' def __init__(self, *args, **kwargs): self.action = kwargs.pop('action', None) super(ConceptForm, self).__init__(*args, **kwargs) if self.action is not None: if self.action == 'detail': for field in self.fields: self.fields[field].widget.attrs['readonly'] = True views.py modelformset = modelformset_factory( model = model, fields = show_fields, form = ConceptForm(kwargs={'action': 'detail'), <-- I would like something like this ) The error is: 'ConceptForm' object is not callable Without call init not errors showed but the form fields not are disabled modelformset = modelformset_factory( model = model, fields = show_fields, form = ConceptForm ) Thanks in advance -
quizgame randomize getting duplicates in production
one way that'd probably work "well enough" is (assuming you can afford to do a count): pick a random indexed column to order by. Order the whole queryset by that. Pick a range between the top and the bottom of the resultset (eg: 1234:1254) and take 1 random result from there. At 50K rows it's ~probably~ a blip in terms of query time (though tbh so might rand() be, at that), however I am trying to translate it into my own codebase as far as I am creating the poc for production code, and I know order_by("?") will kill my db @api_view(['GET', 'POST']) def questions_view(request): if request.method == 'GET': questions = Question.objects.all().order_by('?').first() serializer = QuestionListPageSerializer(questions) return Response(serializer.data) -
Django send API request best practice: inside model save or serializer?
I have a model called Customer, and in the model save method, I send a request to the Stripe API to create a customer whenever a customer instance is created on my application. Another way I could do it is in the serializer.py file. That is, when a user creates a Customer instance on my application, it will automatically send a request to stripe to create a customer on that end. Which of these is the better practice? I believe, for "updating" customers, I will have to send the request to stripe from my serializers.py file. So might as well do the create customer from that file too. Any help would be appreciated. -
Specify order of columns in SELECT with UNION using Django ORM
How could I specify the order of columns in SELECT query in Django ORM? I am trying to union elements from two tables, but apparently elements in union are matched by the order of columns in SELECT, instead of the names of the columns (even if name of the columns are the same). Consider following Models: class Person(models.Model): first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) age = models.IntegerField() class Car(models.Model): number = models.IntegerField() brand = models.CharField(max_length=256) name = models.CharField(max_length=256) and following piece of code: Person.objects.create(first_name="John", last_name="Smith", age=25) Car.objects.create(number=42, name="Cybertruck", brand="Tesla") q1 = Person.objects.all().annotate(name=F('first_name'), group=F('last_name'), number=F('age')).values( 'name', 'group', 'number') q2 = Car.objects.all().annotate(group=F('brand')).values('name', 'group', 'number') data = q1.union(q2) print(data.query) assert list(data) == [ {'name': 'John', 'group': 'Smith', 'number': 25}, {'name': 'Cybertruck', 'group': 'Tesla', 'number': 42}, ]) As you can see I put correct order in .values(). What one could expect is that columns in union would be matched in the order passed to values (or by column names), but this is what happens: SELECT "testunion_person"."first_name" AS "name", "testunion_person"."last_name" AS "group", "testunion_person"."age" AS "number" FROM "testunion_person" UNION SELECT "testunion_car"."name", "testunion_car"."number", "testunion_car"."brand" AS "group" FROM "testunion_car" In the queries "testunion_car"."number" is before "testunion_car"."brand", which makes the Car in UNION have a values: {'name': 'Cybertruck', 'group': … -
How to link User model and User profile between schemas in django?
I am trying to build a multi-tenant application using django-tenant-schemas. I have successfully created the tenant and custom user model. I want all of the user's to be globally authenticated but create their profile inside the tenant they are associated with. I have included the userProfile model inside the tenant apps. The user accounts are created successfully but upon receiving signals to create a profile(one-to-one related), it throws an error. Can any one help me on this, please? Can I maintain the foreign-key constraint across schemas ? -
Django Admin: Use TabularInline on big screen and StackedInline on mobile
I really like StackedInline on mobile screens and TabularInline on big screens for most information. Is there an easy way to basically let TabularInline collapse to StackedInline when the screen is only a certain width? -
Custom filter to return last 4 digits in django
I am trying to create a custom filter that will return the last 4 digits of a number and stars preceding those digits. This is the structure of my project (and where I added the templatetags folder) django -->project ---->classroom ---->migration ---->views ---->templates decorators.py forms.py models.py urls.py ---->templatetags __init__.py app_filters.py Here is the code I wrote in app_filters: from django import template register = template.Library() @register.filter(name='cut_accountnum') def cut_accountnum(value): return print( '**** ****', int(str(value)[-4:])) However this is what I get when I apply the filter Number: None -
Wagtail: Edit handling of GeoJSON field in a snippet vs. Page model
I am trying to implement Django Leaflet into my Wagtail app. The underlying form field is a GeoJSON field. I only get it to work properly when registering my model as a snippet not as a Page model, though. I can add instances of my model based on the Page model and the GeoJSON value is written correctly to the database. I can also edit a features geometry but the geometry won't be displayed on the leaflet map. When Wagtail renders the edit view for the Page based model the GeoJSON turns into a string and deserialization fails: Error creating geometry from value '"{\"type\":\"Point\",\"coordinates\":[-322.276779,59.41526]}"' (String input unrecognized as WKT EWKT, and HEXEWKB.) Loading the edit view for the same model registered as a snippet works, the JSON stays a dict and the geometry gets rendered on the leaflet map. So I suspect somewhere Wagtails edit handler does something to the context it doesn't do when handling snippets. Where to look and how to prevent it? -
how to draw charts/graphs on plotlib on web pages using MTV Django Framework?
Django Framework I am working on a Web-based, Sales Forecasting Project. someone guide whether I use the JS charts or the Plotlib library graphs and charts? Django 3.0.2 Python 3.7.3 -
Django inlineformset_factory display validation errors
I want to validate and display an error message above the field on a formset when a certain condition is triggered after submitting the formset. The validation error is triggering correctly and is preventing the form submission,but the error message is not displayed above/below the field. How can i get it to display? Thanks. views.py def create_quote(request,project_id): project = get_object_or_404(ProjectDetails, id=project_id) if request.method == 'POST': formset = QuoteFormSet (request.POST,request.FILES,instance=project) if formset.is_valid(): formset.save() return redirect("viewBudgets",project_id=project.id) else: formset = QuoteFormSet (instance=project) formset = QuoteFormSet (instance=project) context = { "project": project, "formset": formset} template = "projects/create_quote.html" return render(request,template,context) forms.py class QuoteForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.label_suffix = "" def clean(self): cleaned_data = super(QuoteForm, self).clean() cost_desc = cleaned_data.get("cost_description") total_amount = cleaned_data.get("total") #Condition if cost_desc == None and total_amount > 0: raise forms.ValidationError("Cost Description is a required field.") return cleaned_data class Meta: model = FinanceBudget QuoteFormSet = inlineformset_factory(Projects,FinanceBudget,fields="__all__",form=QuoteForm,extra=10) quote.html <table class="table table-light"> <tbody> <form method="POST" autocomplete="off"> {{formset.management_form}} {%csrf_token%} {{ formset.non_form_errors.as_ul }} <table id="formset" class="form"> {% for form in formset.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle row1 row2 %}"> {% for field in … -
causing the error while Importing the course from Git
I took a clone of edx-demo course (hawthorn version) from the following link: https://github.com/edx/edx-demo-course/tree/open-release/hawthorn.master while importing the course in my open edx(installed with hawthorn version). it is creating the error at the updating of the course stage during importing. enter image description here -
Django filter many to many model's JSON field with the given
I have Movies and Participants model and it is like this, class Movie(models.Model): something something participants = models.ManyToManyField(Participant) class Participant(models.Model): something something type = models.CharField(max_length=127, null=True, blank=True) What I would like to do is, check the Participants type field with the given list and according to it list the Movies or not. For example, I have type_list=["Adults", "Children", "Senior"] but Movie object has 2 Participant objects and one of them is type="Adults" and the other one is type="Children" In example I would expect not to show that Movies since it doesn't have all the required Participants type. What have I tried so far; movie.participants.filter(type__in=["Adults", "Children", "Senior"]) however, this returns a two participants object movie.participants.filter(Q(type="Adults") | Q(type="Children") | Q(type="Senior")): this one also returns the two participant object. I also cant use the & operator. The only idea I left with is to check the count of the participants. Query returned two but I have three participant so I can't show this movie but the problem is in here list is variable that coming from front end. So my both query and if statement should be generic and I don't know how to do both and also I am %100 sure that … -
Why my django project not runing on ngnix?
I'm trying to run my django project on subdomain, my nginx configuration is, server { listen 80; server_name subdomain.example.me www.subdomain.example.me; location /static/ { root /home/gagan/webmash/blog; } location /media/ { root /home/gagan/webmash/blog; } location / { include proxy_params; proxy_pass http://my_ip:9000; } } While my supervisor configuration is, [program:webmash] command=/home/gagan/webmash/env/bin/gunicorn --workers 3 --bind unix:/home/gagan/webmash /blog/blog.sock blog.wsgi --env DJANGO_SETTINGS_MODULE=blog.settings.production directory=/home/gagan/webmash/blog autostart=true autorestart=true stderr_logfile=/var/log/saporawebapp.err.log stdout_logfile=/var/log/saporawebapp.out.log when i run supervisor using, sudo supervisorctl restart webmash It doesn't show any error. On restarting nginx, it too doesn't show any error.But my project is not runing either at https://subdomain.example.com or my_ip:9000. What can be the possible causes for such behaviour -
Django DB operations
I have run into a situation where I need to execute some methods which include DB Operations concurrently in a django application. The thing is all the processes are using the default connection. Which raises exception in the methods. I have read in other blogs and answers on this site and others to close connections by db.connections.close() and it works. But using this solution has lead to another issue, the other methods which are using the db raises exception. What I need to do is open a new db connection for all the processes, and close the connection before exiting the process. This is how far I have come. import time from django.db import connections from django.db.utils import DEFAULT_DB_ALIAS, load_backend # Multithreading related Imports import threading from threading import Thread # Multiprocessing related Imports import multiprocessing as mp from multiprocessing import JoinableQueue as jQueue from multiprocessing import Pool as mp_pool from multiprocessing import Process class DBConnector(object): def __init__(self): print("Created a New Connection with DB--") # creats new connection def create_connection(self, alias=DEFAULT_DB_ALIAS): connections.ensure_defaults(alias) connections.prepare_test_settings(alias) db = connections.databases[alias] backend = load_backend(db['ENGINE']) return backend.DatabaseWrapper(db, alias) # For explicitly opening database connection def __enter__(self): self.dbconn = self.create_connection() return self.dbconn def __exit__(self, exc_type, exc_val, exc_tb): … -
Streaming download chunk_size in response.iter_content not respected
I implemented some custom django logic to upload / download files from blob storage in a streaming way. In django the Fileresponse is used to return a custom subclass of File as streaming response. When using the django development server this works fine, but when using uwsgi + nginx some unexpected things start to happen in downloads using the requests library. response = requests.get(url, stream=True, headers=headers) iterator = response.iter_content(chunk_size=int(1024*1024*10)) chunk = next(iterator) len(chunk) >>>4096 I really expect at least to read 16Mi before any timeouts occur. When using the urllib library similar code works fine. resp = urlopen(request) chunk = resp.read(20*1024*1024) len(chunk) >>>20971520 Any suggestions? -
why it is giving error TypeError: 'NoneType' object is not callable
def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all().first().name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to view this page') return wrapper_func return decorator -
iam trying to use single url for put delete post get in django api with python application
def delete_resource(id): data={ 'id':id } resp=requests.delete(BASE_URL+ENDPOINT,data=json.dumps(data)) print(resp.status_code) print(resp.json()) delete_resource(1) def delete(self,request,*args,**kwargs): data=request.body valid_json=is_json(data) if not valid_json: json_data = json.dumps({'msg': 'please send valid json data'}) return self.render_to_http_response(json_data) p_data=json.loads(data) id=p_data.get('id',None) if id is None: json_data=json.dumps({'msg':'id rquired'}) return self.render_to_http_response(json_data) emp=self.get_object_by_id(id) if emp is None: json_data=json.dumps({'msg':'no resource available with matched id'}) return self.render_to_http_response(json_data) t=emp.delete() print(t) json_data = json.dumps({'msg': 'resource deleted'}) return self.render_to_http_response(json_data)