Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does the mp3 player work correctly in FireFox, but does not work in other browsers?
The problem is rewinding the duration of the track. This works in FireFox, but doesn't work in other browsers. I even reset the cache, everything works correctly in FireFox. Why is this happening and how to fix it? JavaScript let audio = document.getElementById('audio'); let progress = document.getElementById('progress'); let progressBar = document.getElementById('progressBar') //Progress bar audio.ontimeupdate = function (){ progress.value = parseFloat(Math.floor(audio.currentTime * 100 / audio.duration) + "%") } //Set progress bar progress.addEventListener('click', function(e){ res = (e.offsetX / progress.clientWidth) * audio.duration document.getElementById("audio").currentTime = res; console.log("e.offsetX: " + e.offsetX + "\nprogress.clientWidth: " + progress.clientWidth + "\naudio.duration: " + audio.duration + "\nres:" + res + "\naudio.currentTime: " + audio.currentTime) }) HTML <a class="aTrigger" data-title="{{ beat.title }}" data-active="" data-audio="{{ beat.beat.url }}"><i class='fa fa-play'></i></a> <div class="time-control" id="progressBar"> <input id="progress" type="range" style="height: 5px; border-radius: 5px;"> </div> -
django project not loading static files for every user from different regions
I have deployed my project to server and it is not loding static files in my region but working perfect in other regions, what is the problem? Who can explane me? Thanks a lot)) I checked nginx settings but did not find anything -
How I can translate text on buttons in Django?
I try to make bilingual site on Django. Frontend wasn't written by me, and, unfortunatelly, I cannot ask this question for person who did it. const configButton = { purchases: { attr: 'data-out', default: { class: 'button_style_blue', text: '<span class="icon-plus button__icon"></span>Add to purchase list' }, active: { class: 'button_style_light-blue-outline', text: '<span class="icon-check button__icon"></span>Recipe in purchase list' } } } How I can add translation of text on the button using Django internalization tools? -
Error en python django Could not parse the remainder: '['fields']['Nombre']' from 'record['fields']['Nombre']'
hello i am new to python and django what i am trying to do is to connect to airtable through api, and i want to display that data in a table in html but at the time of displaying it i have that error, i need help pls, I already made the connection correctly to airtable. I tried to connect to another database, I checked the html tags and the names of the variables but I didn't find anything concrete. Error during template rendering <table> <thead> <tr> <th>Nombre</th> <th>Apellido</th> <th>Email</th> </tr> </thead> <tbody> {% for record in data %} <tr> <td>{{ record['fields']['Nombre'] }}</td> <td>{{ record['fields']['Apellido'] }}</td> <td>{{ record['fields']['Email'] }}</td> </tr> {% endfor %} </tbody> </table> -
How to get values from mutiple dropdown list and insert to the array list in model?
Any one know how to get values from mutiple dropdown field and then put those selected quantities into an arraylist in model? Also how to make those quantity >=1 items into a list so I can add them into another arraylist in the model? [enter image description here]enter image description here enter image description here Can anyone solove this? -
How to download and upload Django, Python App From DIgitalocan to Any server
Back in few months I hired someone to do a OTT project for me and he did it well but is has many errors and when I try to connect him he didn't respond. He don't even give me the source code which was the deal and also he was about to maintain the site for a monthly fee but heisn't responding at all even his phone is ringing and I try to contact for last 3 months each and every day, Now can you please please tell me is it possible to extract "Download" the database and website files from the Droplets in Digitalocan? and If yes how is it possible? And then what I will need to secure it and install on a vps or another droplets if needed and hire someone to fix the error. Sorry Maybe I made it massy but It will be really really helpful if someone can seve me from this. I just have time issue otherwise I may hire someone to do it from stratch. I have auto backup activated in Digitalocan, I tried to access the file via FTP and it works but don't know how to figure it out and … -
How can I add OR conditions in Django filters but with conditions
So let's say I have a interface that has a filters section (not django filters but just normal filters that we see on product listings etc). Now what I want is that: If Individual is checked, then only show Individual which is very easy. But things get messy when you choose two, let's say individuals and couples. Then I would need alot of if statements for this and changing the filters accordingly. I'm doing this currently like this: if individual and not couple and family: query = query.filter(Q(partner="individual") | Q(partner="family")) if individual and couple and not family: query = query.filter(Q(partner="individual") | Q(partner="couple")) if not individual and couple and family: query = query.filter(Q(partner="family") | Q(partner="couple")) if individual and not couple and not family: query = query.filter(partner="individual") if not individual and couple and not family: query = query.filter(partner="couple") if not individual and not couple and family: query = query.filter(partner="family") which is very messy. Basically I need something like this (PHP Code). $sql = "SELECT * FROM abc WHERE"; if($individual){ $sql .= " partner=individual"; } if($couple){ $sql .= " OR partner=couple"; } if($family){ $sql .= " OR partner=family"; } $sql .= " order by id desc"; now I know the php part above … -
How do i access the value of a table cell value rendered from python backend (HTMLcalender) in javascript front end #django_project
i want to get the value of a table cell from a Calendar rendered from python backend into html frontend, i want JavaScript to highlight the date as of today, by getting the value of the cell and match with today's date maybe by querySelector('id'); from django.shortcuts import render import calendar from ControlPanel.models import Subject, receipts, reportBook from calendar import HTMLCalendar import time def events(request, year, month, day): month = month.capitalize() month_num = list(calendar.month_name).index(month) month_num = int(month_num) year = int(year) name = "student user" cal = HTMLCalendar().formatmonth(year, month_num) return render(request, "events.html", { "name": name, "year": year, "month": month, "monthnum": month_num, "cal": cal, "day": day, }) {% extends 'header.html' %} {% block content %} <html lang="en"> <head> <meta charset="UTF-8"> <title>this is the html page to view the calendar rendered from python</title> </head> <body> <h1>Hello, {{ name }} events for {{ day }} {{ month }} {{ year }}</h1> <section class="container mt-5"> {{ cal|safe }} </section> </body> </html> bellow id the javascript code <script type="text/javascript"> const cal = document.querySelector('table'); cal.setAttribute('class', 'table table-striped'); const tds = document.querySelectorAll('td'); for (var i = 0; i < tds.length; i++){ tds[i].style.cursor="pointer"; console.log({{ day }}) console.log(tds[i].value) //this is returning undefined console.log(tds[i].innerTEXT) //this is returning undefined console.log(tds[i].innerHTML) //this is … -
Django: Remove db rows not present in JSON
As part of the Django project, I would like to mirror API data to local database. I have managed to update data on unique key, however I am struggling how to remove data from the database NOT anymore present in the API file. To illustrate this, let's have current API data like so: [ { "foo": "Lorem", "bar": "ipsum", }, { "foo": "dolor", "bar": "newvalue" }, { "foo": "adipiscing", "bar": "elit" } ] and existing database records (foo is a unique key column): | id | foo | bar | ----------------------------- | 1 | Lorem | ipsum | | 2 | dolor | sit | | 3 | amet | consectetuer | In this case the lines with id 1 & 2 will be updated (rewriting sit to newvalue in the process) and a new line for adipiscing, elit will be inserted. The question is: Is there any good practice how to determine and remove (in bulk) lines such as id 3 (e.g. unique key amet), which are no longer present in the (newly updated) input? -
AttributeError: 'NoneType' object has no attribute 'rsplit'
I'm getting AttributeError: 'NoneType' object has no attribute 'rsplit' error when trying to run this code self.client.get("/"). Test running in Docker on Windows 10 machine. Other simple model tests are running good, just like the application itself. Also tried running this test in another project, and there wasn't any problems. Feel free to ask for more information if needed. The whole error: Traceback (most recent call last): File "/usr/src/app/app/tests/test.py", line 5, in test_test resp = self.client.get("/") ^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/test/client.py", line 836, in get response = super().get(path, data=data, secure=secure, **extra) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/test/client.py", line 424, in get return self.generic( ^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/test/client.py", line 541, in generic return self.request(**r) ^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/test/client.py", line 805, in request response = self.handler(environ) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/test/client.py", line 140, in __call__ self.load_middleware() File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 61, in load_middleware mw_instance = middleware(adapted_handler) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/whitenoise/middleware.py", line 105, in __init__ self.add_files(self.static_root, prefix=self.static_prefix) File "/usr/local/lib/python3.11/site-packages/whitenoise/base.py", line 107, in add_files self.update_files_dictionary(root, prefix) File "/usr/local/lib/python3.11/site-packages/whitenoise/base.py", line 119, in update_files_dictionary self.add_file_to_dictionary(url, path, stat_cache=stat_cache) File "/usr/local/lib/python3.11/site-packages/whitenoise/base.py", line 130, in add_file_to_dictionary static_file = self.get_static_file(path, url, stat_cache=stat_cache) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/whitenoise/base.py", line 202, in get_static_file self.add_cache_headers(headers, path, url) File "/usr/local/lib/python3.11/site-packages/whitenoise/base.py", line 223, in add_cache_headers if self.immutable_file_test(path, url): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/whitenoise/middleware.py", line 177, in immutable_file_test static_url = self.get_static_url(name_without_hash) … -
How to implement Django QuerySet filter on Cartesian product/List of lists?
I want to implement queryset filtering in Django depending on values of nested list, e.g. titles = [ ['nike', '38', 'blue'], ['nike', '38', 'grey'], ['adidas', '38', 'blue'], ['adidas', '38', 'grey'], ['salmon', '38', 'blue'], ['salmon', '38', 'grey'] ] The queryset is: queryset = Attribute.objects.all() What are your suggestion to do something like below dynamically: # | mark means OR queryset.filter(title='nike').filter(title='38').filter(title='blue') | queryset.filter(title='nike').filter(title='38').filter(title='grey') | queryset.filter(title='adidas').filter(title='38').filter(title='blue') | ... queryset.filter(title='salmon').filter(title='38').filter(title='grey') I appreciate your help. -
django many to many through forms
I have a many to many relationship, with an intermediate table with extra fields. I want to create a form that allows me to enter a product, and to be able to choose a price for 1 or more markets. I can't figure out the views to create this form and print it in a template. Can you help me? How the form should look like: Relation: Models: class Market(models.Model): name = models.CharField(max_length=100) class Product(models.Model): name = models.CharField(max_length=250) market = models.ManyToManyField(Market, through='Link') class Link(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) market = models.ForeignKey(Market, on_delete=models.CASCADE) link = models.CharField(max_length=250) class Meta: unique_together = [['producto', 'supermercado']] Forms: class MarketForm(ModelForm): class Meta: fields = ['name'] model = Market class ProductForm(ModelForm): class Meta: fields = ['name'] model = Product class LinkForm(ModelForm): class Meta: fields = ['market','product','link'] model = Link -
Static files not appearing when going live django project
I have the correct settings to get static files live, but no static files work even though I do collectstatic My Settings.py: `STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles/') MEDIA_ROOT = os.path.join(BASE_DIR,'media/')` Debug is False -
django.db.utils.OperationalError: (1074, "Column length too big for column 'audio_file' (max = 16383); use BLOB or TEXT instead")
when I do python manage.py makemigrations it take the change but when I do python manage.py migrate it throw error django.db.utils.OperationalError: (1074, "Column length too big for column 'audio_file' (max = 16383); use BLOB or TEXT instead") I have models.py where my audio_file field is class RadioFile(models.Model): audio_file = models.FileField( upload_to='radio/', validators=[validate_file_extension], max_length=200, help_text="Only wav,mp1,mp2,mp3,m4p,.m5p,wma,pdf and voc files are allowed.", ) I tried to remove max_length completely from audio_file field,it is still giving me this error. I check in other models.py , I don't have max_length set to max = 16383 anywhere neither field name audio_file. from where this error is coming? -
How to make a form field required only if another field is filled and vice versa in Django?
I made the following form in Django. class SearchTimeSlotsForm(forms.Form): available_from = forms.TimeField(widget=TimeInput()) available_till = forms.TimeField(widget=TimeInput()) In the above form the user can either fill both the fields or may not fill any field but he cannot fill only one field. How can I implement this? -
Django server Google Id_token verification using google.oauth2.id_token.verify_oauth2_token() not working
I'm trying to build a flutter app with django backend and need to implement google authentication as well. After receiving the Id_token from google, I send it to my django server. Whilst trying to verify google Id_token from my django server using google.oauth2.id_token.verify_oauth2_token(), it's always showing bad request. I'm passing id_token, requsts.Request() and Client_id of my flutter fronted app as the arguments. Is there any problem with the arguments passed? Is there anything I should do related to google, like creating an Oauth id for my backend server, or something like that.? I tried the solution given here but still not working. -
Run external application using Django
I am creating a django backend. In it I want to run an external Python application I wrote, when someone clicks a button. My project is distributed as follows: external_application_folder main_django_project_folder django_app_folder The way I am currently doing it is, I have created a html file which has a form in it <!DOCTYPE html> <html> <head> <title> ABM TRY </title> </head> <body> <form method="POST">{% csrf_token %} <button type="submit" name="run_external_code"> Run</button> </form> </body> </html> Inside the django_app's views.py I have from external_application_folder.run import external_function def ex_view(request): if request.method=='POST' and 'run_external_code' in request.POST: external_function() return render(request,"html_file.html",{}) whenever I run python manage.py runserver I get the following Watching for file changes with StatReloader Performing system checks... and then everything works. I am new to django, is this the best way to run external application using backend? -
Create a relation without a foreign key
How can I create a "belongs to" relationship in Django without creating a foreign key on the DB layer? -
EC2 .bashrc and .bash_profile re-setting
Reason I'm asking: pycurl requires both libcurl-devel and openssl-devel. To install these, I have these two lines the my .bash_profile: sudo yum install libcurl-devel sudo yum install -y openssl-devel Previously, I just ran those commands in the terminal while ssh'd into the EC2 instance. However, it seems that at random times those lines are cleared from the .bashrc and .bashprofile, and the packages no longer exist in the instance. Why is this happening? Is the EC2 instance refreshing to a clean version at some point? If so, why? And how can I ensure those two packages are default installed on every instance? When I eb deploy I still see the .bashrc and .bash_profile contain the yum install commands. The timing the files are refreshed seems random, and I can't figure out why. -
django many to many through forms
tengo una relación muchos a muchos, con una tabla intermedia con campos extra. Quiero crear un formulario que me permita ingresar un producto, y poder elegir un precio para 1 o más mercados. No logro resolver las views, para crear este formulario e imprimirlo en un template. Podrán ayudarme? Como debería quedar el formulario: Relación: Modelos: class Market(models.Model): name = models.CharField(max_length=100) class Product(models.Model): name = models.CharField(max_length=250) market = models.ManyToManyField(Market, through='Link') class Link(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) market = models.ForeignKey(Market, on_delete=models.CASCADE) link = models.CharField(max_length=250) class Meta: unique_together = [['producto', 'supermercado']] Formularios: class MarketForm(ModelForm): class Meta: fields = ['name'] model = Market class ProductForm(ModelForm): class Meta: fields = ['name'] model = Product class LinkForm(ModelForm): class Meta: fields = ['market','product','link'] model = Link -
Django App on Elastic Beanstalk not Inserting to Specific Model in Deployed Version (works locally)
I have a Django web application that is hosted on AWS Elastic Beanstalk, with a PostgreSQL database on AWS RDS. I have a strange issue where data updates in the UI are inserted to the model locally, but not in the deployed version. Additionally, it's only for one specific model. The other models take UI inputs fine in the deployment. Again, this works perfectly locally, but not when deployed to Elastic Beanstalk. The weird part is that the other models in the application work fine in both local and deployed versions. Since it works locally, and only one model is impacted I don't necessarily know what code would be beneficial to post, and don't want to flood the post with unecessary code but I will be happy to provide relevant code. Any help would be greatly appreciated! I have reviewed the RDS logs, the Elastic Beanstalk logs, and access the EB instance using eb ssh to review additional logs there but find no indication of an error occurring. -
How to restart or reload Django when using it with gunicorn and nginx
I am new to Stackoverflow so i am sorry if i am a little bit of course I recently started to learn Django i am a noob at it still , i just installed django with gunicorn and nginx on a Ubuntu 20 server, and now i am configuring my server but i cant find how to reload or restart Django , any help? I added my domain to allowed_host and saved the file and its not reloading the config i needed to restart the server to reload and then i needed to go back into the venv stop nginx start gunicorn and start nginx again to work , i cant be doing this at evry change i make , and at this topic any ideea how can i make gunicorn start with nginx corectly? -
Django Simple History: Don't want to track User
I'm working on a Django project, and I'd like to use Django Simple History to track changes to records. However, I'm facing an issue: I don't want to track the user who made the change (I'm not using Django's auth app). When I try to perform the migrations, I receive this error message: SystemCheckError: System check identified some issues: ERRORS: my_app.HistoricalModel.history_user: (fields.E300) Field defines a relation with model 'auth.User', which is either not installed, or is abstract. data_lake.HistoricalInstance.history_user: (fields.E307) The field my_app.HistoricalInstance.history_user was declared with a lazy reference to 'auth.user', but app 'auth' isn't installed. Is there a way to use the HistoricalRecords model disabling references to user model? -
FactoryBoy factory that does NOT generate an 'id' for an unmanaged Django model?
I've got a factory that I need to just generate the data I want it to - without having it create an 'id' attribute. I have a couple factories that look like this: class RatedPersonalityFactory(PersonalityFactory): person__end_year = get_end_year() rating_information__create_rating = False rating_information__section = None class Params: pass @post_generation def person(obj, create, extracted, **kwargs): PersonFactory( personality=obj, personality_id=obj.id, state_id=1234, first_name=obj.identity.first_name, last_name=obj.identity.last_name, middle_name=obj.identity.middle_name, birth_date=obj.identity.birth_date, number=obj.student_number, end_year=kwargs["end_year"], ) class PersonFactory(DjangoModelFactory): class Meta: model = Person database = "alternatives" django_get_or_create = ("personality_id",) class Params: # This will create the Personality that we can then use attributes from personality = SubFactory(PersonalityFactory) current_end_year = get_end_year() personality_id = SelfAttribute("personality.id") state_id = 1234 first_name = Faker("first_name") last_name = Faker("last_name") middle_name = Faker("first_name") number = SelfAttribute("person.student_number") active_year = 1 birth_date = Faker( "date_between", start_date=(datetime.now() - relativedelta(years=14)).date(), end_date=datetime.now().date(), ) start_date = Faker( "date_time_between", start_date="-1y", end_date="now", tzinfo=py_timezone(settings.TIME_ZONE), ) end_date = None end_year = LazyFunction(get_end_year) gender = Iterator(["M", "F"]) native_lang = "EN" The model looks like this: class Person(models.Model): personality_id = models.IntegerField(db_column="personalityID") state_id = models.IntegerField(db_column="stateID") first_name = models.CharField(db_column="firstName", max_length=35) last_name = models.CharField(db_column="lastName", max_length=40) middle_name = models.CharField(db_column="middleName", max_length=30) number = models.IntegerField(db_column="studentNumber") active_year = models.IntegerField(db_column="activeYear") birth_date = models.DateField(db_column="BirthDate") start_date = models.DateField(db_column="startDate") end_date = models.DateField(db_column="endDate", null=True) end_year = models.IntegerField(db_column="endYear") gender = models.CharField(db_column="gender", max_length=1) native_lang = models.CharField(db_column="languageAlt", … -
How to get a queryset of foreign keys from a current queryset in django
I have two models, Employee and Manager. The Employee model has a foreign key to Manager. Given an arbitrary queryset qs of Employee objects, I would like to get a queryset of their managers. This seems very simple but I can't find a way to do it. In naive python, I could get a list of these managers by doing something like: qs = Employee.objects.filter(whatever) managerlist = [] for emp in qs: managerlist.append(emp.manager) and this would give me a list of managers corresponding to employees in my queryset. But instead of a list I would like a queryset. Is there a quick simple way to do this?