Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to call django view from template
Below is my urls.py code snippet for the main app urlpatterns = [ path('admin/', admin.site.urls), path('',views.home,name='home'), path('save_query',views.SaveQuery,name='SaveQuery'), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) Below is my html template snippet <form method="post" action="{% url 'save_query' %}"> {% csrf_token %} <p id="error-msg"></p> <div class="row"> <div class="col-lg-6"> <div class="mb-3"> <label class="form-label" for="name">Name</label> <input name="name" id="name" type="text" class="form-control" placeholder="Enter your name..." /> </div> </div> <div class="col-lg-6"> <div class="mb-3"> <label class="form-label" for="email">Email address</label> <input name="email" id="email" type="email" class="form-control" placeholder="Enter your email..." /> </div> </div> </div> <!-- end row --> <div class="mb-3"> <label class="form-label" for="subject">Subject</label> <input name="subject" id="subject" type="text" class="form-control" placeholder="Enter Subject..." /> </div> <div class="mb-3"> <label class="form-label" for="comments">Message</label> <textarea name="comments" id="comments" rows="3" class="form-control" placeholder="Enter your message..."></textarea> </div> <div class="text-right"> <!-- <input type="submit" id="submit" name="send" class="submitBnt btn btn-primary" value="Send message" /> --> <button type="submit" id="submit" name="send" class="submitBnt btn btn-primary" value="Send message"></button> </div> </form> Below is my view function (in the views.py file of the main app folder) def SaveQuery(request): if request.method == "POST": name = request.POST["name"] email = request.POST["email"] subject = request.POST["subject"] message = request.POST["comments"] query = Query(name=name,email=email,subject=subject,message=message) query.save() print(f"[DEBUG] New query has been saved @ {debug()}") return redirect('home') return render(request,"main.html") On running the application I get the following error Reverse for 'save_query' not found. 'save_query' is not a valid view … -
Registration during performance testing
I have an app on django, that I am writing performance tests for it using locust. I have a custom registration process (not the built-in one from django, session-based), that require you to verify your email by sending a link with token to your email. What is the best way to register and authenticate a user in locust? Generate a verification token in locust bu providing it the same secret key Make the request to some email api to get the token from there Skip the registration process and use pre-configured users Something else? -
Permission in pytest
I would like to test views with PermissionRequiredMixin where permission_required = 'can_manage_employees' Fixture below. I got error assert 403 == 302. It look like I did not grant correctly permission to user. Where is mistake? I tried give permission in different way but i did not give result `@pytest.fixture def my_permission(): permission, _ = Permission.objects.get_or_create( codename='can_manage_employees', name='can manage employees', content_type=ContentType.objects.get_for_model(User) ) return permission @pytest.fixture def user_with_permission(my_permission): u = User.objects.create_user( username='Dariusz', email='testuser@example.com', password='password' ) u.user_permissions.add(my_permission) return u ` Another ways of add permission -
Override the template of a widget and pass values to it with Django 4.0
I am creating a simple app to do product reviews. I have a Product, Manufacturer and Review models which I will now summarize (this is not my actual code, if you see some small errors it is because I am rewriting everything now to make it easier to understand) class Manufacturer(models.Model): name = models.CharField() class Product(models.Model): name = models.CharField() manufacturere = models.ForeignKey(Manufacturer) class Review(models.Model): title = CharField() product = models.ForeignKey(Product) I created a ModelForm to create the review. So far I was only able to create a custom widget with an overridden template. class CustomSelectWidget(forms.widgets.Select): option_template_name = 'widgets/select_option.html' class NewReviewForm(forms.ModelForm): review = forms.ModelMultipleChoiceField( queryset = Review.objects.none(), widget = CustomSelectWidget(), ) class Meta: model = Review fields = '__all__' The form view is a normal function based view. The review field is rendered with a list of products in a <select>.What I want to do is change the text inside <option> to make it so that the manufacturer's name is also there. IMPORTANT: I have to take the manufacturer's name from the respective Object, I can't just insert it into the Product name field. ES: what I have now Geforce RTX2080 MAXSUN AMD Radeon RX 550 Arca770 the goal NVIDIA - … -
Download files when popup is open in Django project
Hello there I need to download the file buy the in put post by the popup window in my Django project I am sharing the, the html code of popup window and function in views.py. if I don't use popup window it is working file and able to download file. HTML of Popup window <div class="modal-content"> <div class="modal-header"> {% for fil in instance %} <h5 class="modal-title">Download files for {{ fil.recorule_name|title }}</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <table class="table table-hover tablebdr"> <thead> <tr> <th>Account</th> <th>Rule name</th> <th>Date</th> </tr> </thead> <form action="{% url 'downloadlog'%}" method="POST" enctype="multipart/form-data" id="downloadlog-form"> {% csrf_token %} <tbody> <h6 id="modal_body"></h6> {% if fil.in_file1 %} <tr scope="row"> <td> <input type="text" class="form-control m-0" name="account_name" id = "account_name" value="{{ fil.account_name|title }}" readonly style="background-color: #f2f2f2; border: none;"> </td> <td> <input type="text" class="form-control m-0" name="recorule_name" id = "recorule_name" value="{{ fil.recorule_name|title }}" readonly style="background-color: #f2f2f2; border: none;"> </td> <td> <input type="date" class="form-control" name="recon_date" id= "recon_date"> </td> </tr> {% endif %} {% endfor %} </tbody> </table> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary btn-rounded btnwidth" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary btn-rounded btnwidth" id="downloadlog-submit">OK</button> </div> </div> <div class="modal-body"> <div class="alert alert-danger" style="display:none;" id="error-message"> Error message goes here. </div> <div class="alert alert-warning" … -
Django Modelformset
I have followed this link https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/ to help me in creating a modelformset. However, each time I press "submit", it creates new forms and it shows the previously submitted forms. That's not what I want, I want to specify in my view how many forms I want and it should stay that way after submitting. How can I cause no extra forms to be made after submitting? views.py: def test(request): AuthorFormSet = modelformset_factory(Author, fields=('name', 'title', 'birth_date'), extra=3) if request.method == 'POST': formset = AuthorFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() return render(request, 'voting/test.html', {'formset': formset}) # do something. else: formset = AuthorFormSet() return render(request, 'voting/test.html', {'formset': formset}) models.py: TITLE_CHOICES = [ ('MR', 'Mr.'), ('MRS', 'Mrs.'), ('MS', 'Ms.'), ] class Author(models.Model): name = models.CharField(max_length=100) title = models.CharField(max_length=3, choices=TITLE_CHOICES) birth_date = models.DateField(blank=True, null=True) def __str__(self): return self.name forms.py: class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ('name', 'title', 'birth_date') test.html: <form method="post"> {{ formset.management_data }} {% csrf_token %} {{ formset }} <button type="submit" name = "voting" class="btn btn-primary save">Submit</button> </form> -
How to test @login_required view in django
I've a django view which has @login_required decorator then it renders html file with context and I'm trying test it's function whether the context is in response @login_required def my_view(request): #code goes here context={'name':name} return render(request, home.html, context) class TestEmployer(TestCase): def setUp(self): self.client = Client() self.client.login(username='1', password='Pass@123') def test_list_employer(self): url = reverse(my_view) response = self.client.post(url, follow=True) self.assertEqual(response.status_code, 200) self.assertIn('name', response.context) So @login_required decorator blocking me to test the function and asserts an error with 'name' not in signin html page -
Django Query two Models and Display Records in One HTML Table
I am working on a Django Daily Saving Project where I have Statement view and I want to display a Customer's Deposits and Withdrawals (all his deposits and withdrawals) in one HTML Table. I am looking at the Best Performance (Constant Complexity for Big O Notation if possible in this case). I don't know whether there is another way of displaying records in a table from a Model other than using a For Loop. If there is, then your kind answer is also welcome. Here are my Models: class Deposit(models.Model): customer = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) transID = models.CharField(max_length=12, null=True) acct = models.CharField(max_length=6, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) deposit_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('create_account', args=[self.id]) def __str__(self): return f'{self.customer} Deposited {self.deposit_amount} by {self.staff.username}' class Witdrawal(models.Model): account = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) transID = models.CharField(max_length=12, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) withdrawal_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.account}- Withdrawn - {self.withdrawal_amount}' Here is my view: def account_statement(request, id): try: customer = Account.objects.get(id=id) #Get Customer ID customerID = customer.customer.id except Account.DoesNotExist: messages.error(request, 'Something Went Wrong') return redirect('create-customer') else: deposits = Deposit.objects.filter(customer__id=customerID).order_by('-date')[:5] #Get Customer Withdrawal by ID and order by Date minimum 5 records displayed withdrawals = … -
Celery: Would increasing the number of queues speed things up?
I'm running my site on a VPS with 4 vCPUs, so by default each queue has 4 worker processes. I'm running 6 queues simultaneously now for my Celery process. The first queue, let's call it queue1, it's a very busy queue with multiple tasks/processes running all the time (mostly I/O tasks). Should I split queue1's tasks into smaller queues, e.g. queue1a, queue1b, queue1c, etc.? Will there be a performance benefit? My CPU utilization is quite high, I was just wondering if doing this will ease things up a little. -
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.