Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting the class from a model instance in Django
I have a model where I want to get the class name and create a queryset from the instance of the model as it is being saved. Right now, Im doing it like this: class MyModel(models.Model): .... def my_method(self): if self.__class__.__name__.objects.filter(...).exists(): # Do something This does not really work as it says that a string object does not have the objects property, but hopefully, it makes it clear what I want to do. This is for a base abstract class where the method can be re-used for all the child classes with different names. Anyway, is there a way to do this in Django? -
How to use update_fields in django signals post_save
I hope my title is enough to understant what i am trying to say if not then sorry in advance. I dont have problem on inserting data, but how about when the admin update the section of student were the student have already record?, I just want to update the current data not add another data this is my code in my model.py(post_save).. @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, **kwargs): teachers = SubjectSectionTeacher.objects.filter(Courses=instance.Courses, Sections=instance.Section) if created and teachers.exists(): StudentsEnrolledSubject.objects.create( # This should be the instance not instance.Student_Users Students_Enrollment_Records=instance, # The below is also not an instance of SubjectSectionTeacher Subject_Section_Teacher=teachers.first()) -
Django/Bootstrap 4: How to align elements inside of multiple parent divs
So I am developing a website and for the life of me I cant figure out how to align the description, price, stock and add cart button in multiple versions of the same div. I know it is to do with the size of the image I am using but I'm not sure how to fix this. Here is a diagram of how I want it to look: But when I apply a 'h-100' class to the card div this is what happens: I want the images to keep their positions but for the descriptions, add cart button and price/stock to all be horizontally aligned, as well as the height of the overall cards to be the same. Here is my Django template code: {% extends 'base.html' %} {% block content %} <div class="container-fluid"> <div class="jumbotron"> <h2>Welcome to MyTea</h4> <p>Here we have teas of all varieties from all around the globe</p> </div> <div class="row"> <div class="col-sm-3"> <h4>Categories</h4> <ul class="list-group"> <a href="{% url 'products' %}" class="list-group-item">All Categories</a> {% for c in countcat %} <a href="{{ c.get_absolute_url }}" class="list-group-item catheight">{{c.name}} <span class="badge badge-light">{{c.num_products}}</span> </a> {% endfor %} </ul> </div> <div class="col-sm-9"> {% for product in products %} {% if forloop.first %}<div class="row">{% … -
Wrong column sizes in latex generated pdf when running pdflatex via subprozess in django
I'm generating a Latex document on my Django page with pdflatex. When i compile my tex-file from the Terminal or with subprocess in python it has the right col widths but when I compile it with subprocess in my django site the columns have wrong widths. e.g.: wrong - https://docdro.id/gsHMoQX right - https://docdro.id/HLIQAEE .tex content: \documentclass{article}% \usepackage[T1]{fontenc}% \usepackage[utf8]{inputenc}% \usepackage{lmodern}% \usepackage{textcomp}% \usepackage[margin=0.5in]{geometry}% \usepackage{longtable}% \usepackage{graphicx}% % \usepackage{colortbl}% % \begin{document}% \pagestyle{empty}% \normalsize% \begin{Large}% 1 MAK {-} 4AHWII% \end{Large}% \begin{longtable}{l | l | >{\columncolor[rgb]{1, 0.6, 0.42}}l | >{\columncolor[rgb]{1, 1, 0.6}}l | >{\columncolor[rgb]{1, 0.6, 0.6}}l}% \textbf{Nachname}&\textbf{Vorname}&\textbf{{\rotatebox{ 90 }{ Gesamt (None) } }}&\textbf{{\rotatebox{ 90 }{ Prozent } }}&\textbf{{\rotatebox{ 90 }{ Note } }}\\% \hline% \endhead% Musterschüler&Max&0&0\%&5\\% Siegele&Noah&0&0\%&5\\% Widerin&Alexander&0&0\%&5\\% Hilber&Georg&0&0\%&5\\% \end{longtable}% \begin{figure}[b]% \centering% \includegraphics[width=240px]{/tmp/fig.png}% \end{figure} % \end{document} -
How to serve protected video file on Django production?? Nginx help needed
I need a serve a protected video file on production in a super quick easy way, but it's not working. No models are required. I only need to upload ONE video, have it display on a django template page, and that's it. So no true password with salting / hashing is required (which I know how). With my current setup the video serves fine from static, but not as a protected file because it's easy to copy/paste from the source html. Every article I've checked only shows how to download a specific file as a forced download, but I need some clarity on what's happening... This and this are the best articles I've found. Everything else is either wrong, or not as complete as those. Problems: On production I'm getting a 404 not found error when setting the header for response['X-Accel-Redirect'] = '/protected_files/' in the view, And a 403 forbidden error when setting the response['X-Accel-Redirect'] = protected_url in the view. What's happening?? I think the problem is with my location /protected_videos/ {...} directive, but I don't know why. Maybe it's my secret_page/ url??? Project structure: projectcontainer/ project/ settings.py ... static/ public-video.mp4 # all static serves fine PROTECTED/ videos/ private-video.mp4 # … -
Django: Sort articles by hourly/daily views (trending)
Suppose we have a blog with 100 articles. How can we let the users sort articles (objects) by the number of views (field) in the last hour/day/week/month? Can we implement something that makes the field views_today such that it becomes 0 every hour? -
Django how to serialize multiple file upload with validation using forms.ModelForm?
I have file upload model that saves the files based on it's md5 checksum: # models.py class File(models.Model): # use the custom storage class fo the FileField orig_file = models.FileField( upload_to=media_file_name, storage=file_system_storage) md5sum = models.CharField(max_length=36, default=timezone.now, unique=True) created = models.DateField(default=timezone.now) def save(self, *args, **kwargs): print('Saving new raw file.', self.md5sum) if not self.pk: # file is new md5 = hashlib.md5() for chunk in self.orig_file.chunks(): md5.update(chunk) self.md5sum = md5.hexdigest() if not self.id: self.created = timezone.now() print('Saving new raw file.', self.md5sum) super(RawFile, self).save(*args, **kwargs) The form I use to upload files looks like this: # forms.py from django import forms from .models import File class UploadRawForm(forms.ModelForm): orig_file = forms.FileField( widget=forms.ClearableFileInput(attrs={'multiple': True}) ) class Meta: model = File fields = ['orig_file'] I can upload single files, but when I use multiple files only the last file in the list is saved. According to other threads I have to serialize this process. So that the files are processed one by one. Do I need extra packages? -
Can I filter objects in forms.ManyToManyField to equal value selected in another field?
I want to set a queryset on a ManyToManyField to get all objects that have a ForeignKey equal to ForeignKey set in another formfield. class ProductAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProductAdminForm, self).__init__(*args, **kwargs) self.fields['variants'].queryset = Variant.objects.filter(variantCategory__productCategory__name_single='test') This works, It selects all "Variant"'s where value of "name_single" of productCategory in its variantCategory is equal to 'test'. I want to replace 'test' to be equal to "name_equal" of productCategory set in this very form. Here is some code to ilustrate how the objects relate to eachother. class Variant(models.Model): variantCategory = models.ForeignKey('VariantCategory') class VariantCategory(models.Model): productCategory = models.ForeignKey('ProductCategory') class ProductCategory(models.Model): name_single = models.CharField() https://imgur.com/a/OLah8at This shows the field that should define the productCategory to equal to. I realize this is kind of hard to explain, if any of you need extra code/info let me know! Also, I just need the query to get all objects where productCategory equals to another productCategory. The "name_equal" part doesn't really matter, could be the id of the object to! -
How to setup a JQuery Datatable
So I was trying to set-up a JQuery Datatable as in this example: http://plnkr.co/edit/b8cLVaVlbNKOQhDwI2mw?p=preview But I keep getting a "No matching records found" pop-up when I try to implement it. How would I be able to fix it? Here is my JS script: $(function() { otable = $('#amdta').dataTable(); }) function filterme() { //build a regex filter string with an or(|) condition var types = $('input:checkbox[name="item"]:checked').map(function() { return '^' + this.value + '\$'; }).get().join('|'); //filter in column 0, with an regex, no smart filtering, no inputbox,not case sensitive otable.fnFilter(types, 1, true, false, false, false); //build a filter string with an or(|) condition var frees = $('input:checkbox[name="website"]:checked').map(function() { return this.value; }).get().join('|'); //now filter in column 2, with no regex, no smart filtering, no inputbox,not case sensitive otable.fnFilter(frees, 2, false, false, false, false); Here is my HTML <p> <label> <input onchange="filterme()" type="checkbox" name="website" class="filled-in" value="canadacomputers" /> <span>Canada Computers</span> </label> <label> <input onchange="filterme()" type="checkbox" name="item" class="filled-in" value="$2299.0" /> <span>Item</span> </label> </p> <input type="text" id="amdin" onkeyup="amdfun()" placeholder="Search for CPU.."> <table id="amdta"> <thead> <tr> <th class="th-sm">Item</th> <th class="th-sm">Price</th> <th class="th-sm">Website</th> </tr> </thead> {% for item in items %} {% if item.brand == 'amd' %} <tbody> <tr> <td>{{ item.item }}</td> <td>${{ item.price }}</td> <td> <a href="{{ item.website … -
Gunicorn seems to slow down response time by ~30x
I have a Django app. It uses Nginx, sits on an EC2 instance, and uses an AWS load balancer in front of that. Nginx serves static files right from disk as well as using proxy_pass for everything else to route to the WSGI app server. It is the choice of WSGI server that I'm seeing puzzling results for. When I use Django's development server, ./manage.py runserver 0.0.0.0:8000, the average response time for the resulting HTML document at / is 60-70 ms: Blocked: 1 ms DNS resolution: 0 ms Connecting: 0 ms TLS setup: 0 ms Sending: 0 ms Waiting: 68 ms Receiving: 0 ms Now when I replace this with a "proper" Gunicorn server, the average response time for the same request/doc is now 1800 ms! Blocked: 1 ms DNS resolution: 0 ms Connecting: 0 ms TLS setup: 0 ms Sending: 0 ms Waiting: 1859 ms Receiving: 0 ms Here I'm running Gunicorn as: gunicorn \ --log-level DEBUG \ --bind 0.0.0.0:8000 \ --workers 4 \ project.wsgi And, notably, the response time does not change regardless of whether the number of workers is much higher e.g. --workers 64 (nor would I expect it to, since this is not about concurrent requests). … -
Django - Saving SNS Notifications
I need to receive a notification every time an object is saved in my S3 Bucket. According to the S3 documentation it is possible to enable event notifications in the bucket when an object is created in S3. SNS is one of the options. I'm looking at the AWS documentation and see that SNS can be used for: http – delivery of JSON-encoded message via HTTP POST https – delivery of JSON-encoded message via HTTPS POST That tells me that I should be able to get this notifications in my Django app using POST and I should be able to save the notifications once I receive them. However, I'm confused as to what the endpoint is. SNS requires an endpoint to send notifications to. I'm in development and my app is not in an EC2 instance yet, so I don't think I have and endpoint? Can someone provide some guidance into how I can save SNS notifications in my Django app? I saw this package but it doesn't specify what the SNS endpoint should be. -
Model field to automatically store total club members
I am building an app for a charity club that has many different users each belonging to a single club. I want to automatically increment the 'total_members' field of the class 'Club_Chapter' each time a user registers their account for a particular school (hence the User foreign key 'chapter'). models.py class Club_Chapter(models.Model): club_id = models.IntegerField(primary_key=True) school_name = models.CharField(max_length=30) state = models.CharField(max_length=4) total_members = models.IntegerField(null = False, default = 0) def __str__(self): return self.school_name # User Model class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' chapter = models.ForeignKey('Club_Chapter',on_delete=models.PROTECT) ranking = models.CharField(default='member', max_length=20) REQUIRED_FIELDS = [] objects = UserManager() forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=True) last_name = forms.CharField(max_length=30, required=True) email = forms.EmailField(max_length=254, required=True) chapter = models.ForeignKey('Club_Chapter',on_delete=models.PROTECT) password2 = None # below is my failed attempt to solve this problem Club_Chapter.objects.update(total_members=F('total_members') + 1) class Meta: model = User fields = ('first_name', 'last_name', 'chapter','email', 'password1',) I know this seams like a trivial problem but I have been searching everywhere with no luck. Any input will be greatly appreciated for the solution to this problem will help greatly with other aspects of this project. -
Django: How to pass a primary key from one view to another view?
I am using django and django-paypal for my hotel reservation system to accept payments. I am having problems with sending a primary key from one view which has the app_name system to another view in a different app called payments. I will now explain what I want to happen here: The Primary key of the room is retrieved when the user clicks on the room (reserve function) The user will press reserve, this will call the confirm function which will check if the room is available in the reservation database. (confirm function) Display a message to the user saying that the room can be reserved and automatically redirect the user to go to the process function. Process function uses paypal to allow the user to pay the price of that room.(process_payments functions) The user pays for the room via paypal and that's it Happy days!! However, I am having a problem from step 3 to step 4 because I get the this error: Reverse for 'process' with arguments '('',)' not found. 1 pattern(s) tried: ['payments/(?P[0-9]+)/process/$']. When I remove the pk from the parameters of the function and the url it works but I won't be able to charge the user … -
Django, change view from PK to slug
in my case im using a combination between PK and slug in the url. In my models, I have connect to some databases to one main database class Memories(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='remember_user') timestamp = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=200, null=True, blank=True) status = models.CharField(max_length=1, choices=STATUS, default=DRAFT) image = models.ImageField(_('Image'), upload_to=upload_to, default=False) def clean(self): if not self.is_natural: raise ValidationError('Please confirm, this is natural person and not victiv') class Meta: ordering = ["-timestamp"] verbose_name = _("Question") verbose_name_plural = _("Questions") def save(self, *args, **kwargs): if self.slug: # edit #self.title = slugify(f"{self.firstname}-{self.lastname}", to_lower=True, max_length=80) if slugify(self.firstname+"-"+self.lastname) != self.slug: self.slug = generate_unique_slug(Memories, self.firstname+"-"+self.lastname) else: # create self.slug = generate_unique_slug(Memories, self.firstname+"-"+self.lastname) super(Memories, self).save(*args, **kwargs) def __str__(self): return self.id class Content(models.Model): question = models.ForeignKey(Memories, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='remember_content_user') content = MarkdownxField() uuid_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ["-timestamp"] verbose_name = _("Content") verbose_name_plural = _("Content") def __str__(self): return self.content def get_markdown(self): return markdownify(self.content) In my URLs, at this moment is based on PK urlpatterns = [ url(r'^$', views.MemoriesIndexListView.as_view(), name='index'), url(r'^add-memories/$', views.CreateMemoriesView.as_view(), name='add_memories'), url(r'^(?P<slug>[-\w]+)/$', views.MemoriesDetailView.as_view(), name='detail'), url(r'^add-content/(?P<question_id>\d+)/$', views.CreateContentView.as_view(), name='add_content'), ] And on the end, the view class CreateMemoriesView(LoginRequiredMixin, CreateView): form_class = MemoriesForm template_name = "remember/memories_form.html" message = _("saved") def form_valid(self, … -
Using windows authentication for a Django app served by linux box
I have Windows users that access a Django app that runs on a linux server. The question was asked, can that Django app use windows authentication to verify users? Or is it impossible since Django runs on a linux server. -
How to cross-check data stored in separate models?
I'm fairly new to python. I'm making a form that has a few fields from my model. The first field of this model, called EmployeeWorkAreaLog is Employee#/adp number, which is just a regular ID#. I have another model, called Salesman that is used as the main database with all the employees, and has each person's info, along with their employee #. What I was trying to achieve is that the form doesn't submit if the employee # is not valid, meaning is not currently in Salesman model. Below is what I tried to do, but I noticed that this is tying the Employee # to the auto-generated ID in the database, not the adp_number. I tried to make some changes with how the relation is but every time I ended up having to modify the Salesman model, which I cannot do, because it said something about the field being unique. Note that, in my EmployeeWorkAreaLog, the same employee can have multiple entries, so I don't know if that's what might be causing this. How could I approach this without changing Salesman? And, secondary question, not as crucial, is there any way that, upon submission, I can copy the slsmn_name from … -
Could not unpickle django-rq job
Ive setup a system for long running processes using django-rq. My worker seems fine and it says that the job runs ok: rq_1 | 19:29:24 default: league.jobs.sync_league(league_id=492233) (43c98835-7a6f-42b8-ba58-c9253781786f) rq_1 | 19:29:24 default: Job OK (43c98835-7a6f-42b8-ba58-c9253781786f) But my data from the job does not show up in the system and when clicking on finished jobs i get the message: ('Could not unpickle', UnpicklingError('pickle data was truncated')) The view that enques the job looks like this: from .jobs import sync_league django_rq.enqueue(sync_league, league_id=league_id) And the job itself, a bit shortened: async def sync_league(league_id): async with aiohttp.ClientSession() as session: #more code.... for team in page_results: team = Team.objects.get_or_create( name=team["entry_name"], fpl_id=team["entry"] ) team.save() league.teams.add(team) league.sync_team_standings() Ive also tried changing the job to only print("test") but that gives the same pickling error. -
How to fix missing values in id field after adding and removing primary key in django model?
I added a primary key for a model but then ran into some downstream problems because the automatically generated id field was gone. Now, I removed that key again, but the id column was deleted apparently and I guess all the values are gone. So, setting a default value does not really make sense because other models need to know the old values. How can I fix that? Currently, I still get the error when I try to migrate: django.db.utils.ProgrammingError: column "id" of relation "pipeline_file" does not exist -
How to override empty_label in filter django based in SimpleListFilter?
I'm making a filter on django based on SimpleListFilter, I would like to know if there is a way to replace the label all in the filter. I tried ovveride empty string but not works class IgnoreAttendanceReportFilter(admin.SimpleListFilter): title = 'Aulas ignoradas pelo extrato de frequência' parameter_name = 'aula__status__ignore_in_attendance_report' def lookups(self, request, model_admin): return ( ('yes', 'Sim'), ('', 'No'), ) def queryset(self, request, queryset): if self.value() == 'yes': return queryset.filter(aula__status__ignore_in_attendance_report=True) # return queryset return queryset.filter(aula__status__ignore_in_attendance_report=False) This way in my display list: all, Yes and No, I want to change all for No, this way default filter is will be No, and my display only Yes and No. -
how to setup x server & set display key stroke events from pynput on AWS ec2
m able to get the keystroke event on my local system when using pynput package. But it doesn't work same on AWS EC2 instance giving error Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/Xlib/support/unix_connect.py", line 119, in get_socket s = _get_unix_socket(address) File "/usr/local/lib/python3.7/site-packages/Xlib/support/unix_connect.py", line 98, in _get_unix_socket s.connect(address) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/Xlib/support/unix_connect.py", line 123, in get_socket s = _get_tcp_socket(host, dno) File "/usr/local/lib/python3.7/site-packages/Xlib/support/unix_connect.py", line 93, in _get_tcp_socket s.connect((host, 6000 + dno)) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./demo.py", line 10, in import pynput File "/usr/local/lib/python3.7/site-packages/pynput/init.py", line 40, in from . import keyboard File "/usr/local/lib/python3.7/site-packages/pynput/keyboard/init.py", line 49, in from ._xorg import KeyCode, Key, Controller, Listener File "/usr/local/lib/python3.7/site-packages/pynput/keyboard/_xorg.py", line 39, in from pynput._util.xorg import ( File "/usr/local/lib/python3.7/site-packages/pynput/_util/xorg.py", line 40, in _check() File "/usr/local/lib/python3.7/site-packages/pynput/_util/xorg.py", line 38, in _check display = Xlib.display.Display() File "/usr/local/lib/python3.7/site-packages/Xlib/display.py", line 89, in init self.display = _BaseDisplay(display) File "/usr/local/lib/python3.7/site-packages/Xlib/display.py", line 71, in init protocol_display.Display.init(self, *args, **keys) File "/usr/local/lib/python3.7/site-packages/Xlib/protocol/display.py", line 89, in init self.socket = connect.get_socket(name, protocol, host, displayno) File "/usr/local/lib/python3.7/site-packages/Xlib/support/connect.py", line 87, in get_socket return mod.get_socket(dname, protocol, host, dno) File "/usr/local/lib/python3.7/site-packages/Xlib/support/unix_connect.py", … -
Django/Postgres ORM Model
I have this done in other languages but currently beating my head on the table in this one. The goal of what I am doing is that data is not deleted (ever) just masked by a newer record for history logging. Before anyone asks, this is a requirement not an option. The three fields look like follows: | id | row_id | update_id | |------|--------|-----------| | uuid | uuid | uuid | The concept of this is for a single record the id will never change throughout the history of that record and will be used as the official reference of that record. The row_id is the primary key and and always exists The update_id is null for the latest update of the record and in the history it always is updated to the record row_id that replaced it. There are other fields to these tables but they aren't relevant to what I am trying to accomplish. import uuid from django.db import models class MyObject(models.Model): id = models.UUIDField( auto_created=True, default=uuid.uuid4, editable=False, null=False, ) row_id = models.UUIDField( auto_created=True, default=uuid.uuid4, editable=False, primary_key=True, null=False, unique=True, ) update_id = models.UUIDField( editable=False, unique=True, ) Now I gather that the MyObject.save() will insert or update the … -
How i fix this Unable to import 'django.urls' error?
Errors are: 1. No name 'urls' in module 'django'pylint(no-name-in-module) Unable to import 'django.urls' 2. No name 'test' in module 'django'pylint(no-name-in-module) Unable to import 'django.test'pylint(import-error) 3. No name 'http' in module 'django'pylint(no-name-in-module) Unable to import 'django.http'pylint(import-error) When I start the server the terminal shows me this - Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\aviba\appdata\local\programs\python\python38-32\Lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\users\aviba\appdata\local\programs\python\python38-32\Lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\aviba\Envs\test\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\aviba\Envs\test\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\aviba\Envs\test\lib\site-packages\django\core\management\base.py", line 387, in check all_issues = self._run_checks( File "C:\Users\aviba\Envs\test\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\aviba\Envs\test\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\aviba\Envs\test\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\aviba\Envs\test\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\aviba\Envs\test\lib\site-packages\django\urls\resolvers.py", line 399, in check for pattern in self.url_patterns: File "C:\Users\aviba\Envs\test\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\aviba\Envs\test\lib\site-packages\django\urls\resolvers.py", line 584, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\aviba\Envs\test\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\aviba\Envs\test\lib\site-packages\django\urls\resolvers.py", line 577, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\aviba\Envs\test\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", … -
Django Download third party video instead of opening in new/same tab
I am currently trying to make a user download a video on clicking a link . But everytime on clicking the URL(href) it opens it a new tab. The video URL is a third-party URL(Instagram CDN). Here is my code snippet in my template.html for the page . padding: 20px 0px;color: rgb(38, 38, 38); font-size: 16px; font-weight: 500; transition: all 0.2s ease 0s;" download>DOWNLOAD</a> ``` I intentionally added '&amp;dl=1' to the URL part hoping it might make some impact but to no avail. Removing/Adding the attribute 'download' seems to have no impact. What should I do to force download it and not open in new tab. -
Django and Javascript to pass a variable to another page
I am trying to build a chatroom using Django and Django Channels. What I would like to do is set an input element to accept a user alias and then carry that username into the chatroom. I am not using a data model and would like to pass this variable from the chatroom select page to the chatroom just using JavaScript without utilizing the URL to Post username data. I do not want to use the User module in Django because I don't want to require authentication, just allow the user to set a name. Here is the code I am currently using, I know it is not syntactically correct, but should give an idea of what I am trying to do. I will asterisk the sections that break the code. The HTML: <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Rooms</title> </head> <body> *Enter an alias:<br> *<input id="username-name-input" type="text" size="100"/><br/> Enter a chatroom name:<br/> <input id="room-name-input" type="text" size="100"/><br/> <input id="room-name-submit" type="button" value="Enter"/> <script> document.querySelector('#room-name-input').focus(); document.querySelector('#room-name-input').onkeyup = function(e) { if (e.keyCode === 13) { // enter, return document.querySelector('#room-name-submit').click(); } }; document.querySelector('#room-name-submit').onclick = function(e) { var roomName = document.querySelector('#room-name-input').value; *var userName = document.querySelector('#username-name-input').value; window.location.pathname = '/' + roomName + '/'; }; </script> … -
Display block datatable - django-tables2
I am using django-tables2 and i want to display my data of table in block form. Just like in this question. I know how the css would be changed and how the html file would be called but i am unable to handle custom css which would display current the table format into block format. Undermentioned is the code which i am trying to alter. It is django_tables2/bootstrap4.html of django-tables2 {% block table.tbody %} {# <tbody {{ table.attrs.tbody.as_html }}>#} {% for row in table.paginated_rows %} {% block table.tbody.row %} <tr {{ row }}> {% for column, cell in row.items %} <td {{ column.attrs.cell }}>{% if column.localize == None %}{{ cell }}{% else %}{% if column.localize %}{{ cell|localize }}{% else %}{{ cell|unlocalize }}{% endif %}{% endif %}</td> {% endfor %} </tr> {% endblock table.tbody.row %} {% empty %} {% if table.empty_text %} {% block table.tbody.empty_text %} <tr><td colspan="{{ table.columns|length }}">{{ table.empty_text }}</td></tr> {% endblock table.tbody.empty_text %} {% endif %} {% endfor %} </tbody> {% endblock table.tbody %}