Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at /student/test/ Reverse for 'single_quiz' with arguments '('',)' not found. 1 pattern(s) tried: ['quiz/(?P<quiz_id>[0-9]+)/$']
revere match error occurred when passing id. but works fine when added manually.it shows NoReverseMatch error. I am unable to figure out where this is coming from. Should I add the traceback too ? template <div style="padding: 100px 270px;"> {% for a in applied%} {{a.job.quiz.id}} <a href="{% url 'single_quiz' a.job.quiz.id %}">{{a.job.quiz}}</a> {%endfor%} </div> views.py def single_quiz(request, quiz_id): print(quiz_id) quiz = get_object_or_404(Quiz, pk=quiz_id) print(quiz) num_questions = len(quiz.question_set.all()) try: unique = Result.objects.get(user=request.user,quiz=quiz) except Result.DoesNotExist: unique = False # deletes quiz and returns to home if no questions created if num_questions == 0: quiz.delete() all_quiz_list = Quiz.objects.all() context = { 'all_quiz_list': all_quiz_list, } return render(request, 'quiz/index.html', context) quiz.num_questions = num_questions quiz.save() # resets accuracy info to 0 request.session["num_correct"] = 0 request.session["num_wrong"] = 0 context = { 'quiz': quiz, 'num_questions': num_questions, 'unique': unique, } return render(request, 'quiz/single_quiz.html', context) urls.py path('<int:quiz_id>/', views.single_quiz, name='single_quiz'), -
How to fetch Form data in django using cloud firestore?
[] ID is been selected but I'm not getting the values in the form, please check my code files. See in the picture in URL of the browser, update/id is selected, the problem is values are not fetched in the form. HTML: <form id="task-form" name="myForm"> {% csrf_token %} <div class="form-group"> <div class="row"> <div class="col"> <input type="text" class="form-control" id="task-building" placeholder="Building name" name="building" value="{{buildings.building}}"> </div> <div class="col"> <input type="text" class="form-control" id="task-postal" placeholder="Postal Code" name="postalCode" value="{{buildings.postalCode}}"> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col"> <input type="text" class="form-control" id="task-town" placeholder="town" name="town" value="{{buildings.town}}"> </div> <div class="col"> <input type="text" class="form-control" id="task-street" placeholder="Street" name="street" value="{{buildings.street}}"> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col"> <input type="text" class="form-control" id="task-house" placeholder="House No." name="houseNo" value="{{buildings.houseNo}}"> </div> <div class="col"> <input type="text" class="form-control" id="task-info" placeholder="Additional Information" name="additionalInfo" value="{{buildings.additionalInfo}}"> </div> </div> </div> <div class="text-center mt-3"> <button type="submit" id="btn-task-form" class="btn btn-primary ">UPDATE</button> </div> </form> views.py def update_Building(request, id): docId = id; context = { 'buildings': db.collection('Buildings').document(docId).get() } return render(request,"EmployeeAdmin/updateBuilding.html", context) urls.py path('update/<str:id>/',views.update_Building,name='update_Building'), -
What is acceptable speed of Django JSON search on Postgres DB [closed]
Using a JSON field that I need to search through every field I use this: queries = [Q(**{'field_data__' + f['name'] + '__icontains': search}) for f in model.fields] qs = None for query in queries: qs = query if qs is None else qs | query for 1 million items with 4 fields a search on a random string takes about 1-2 seconds. Insert of 0.5 million items takes about 10-20 seconds using bulk insert. Is that acceptable or is this way to slow. The Postgres database and Django run on the same machine i5 7500T which I think is an avarage modern CPU... I am just wondering if the order of magnitude is about right, I am not looking for the absolute highest speeds... -
Using the URLconf defined in Webwork.urls, Django tried these URL patterns, in this order: The empty path didn’t match any of these
I am getting this error can anyone help me Request Method: GET Using the URLconf defined in Webwork.urls, Django tried these URL patterns, in this order: admin/ ^ ^department/$ ^ ^department/([0-9]+)$ ^ ^employee/$ ^ ^employee/([0-9]+)$ The empty path didn’t match any of these. here is my code: from django.contrib import admin from django.urls import path from django.conf.urls import url,include urlpatterns = [ path('admin/', admin.site.urls), url(r'^',include('EmpApp.urls')) ] and from django.conf.urls import url from EmpApp import views urlpatterns=[ url(r'^department/$',views.departmentApi), url(r'^department/([0-9]+)$',views.departmentApi), url(r'^employee/$',views.employeeApi), url(r'^employee/([0-9]+)$',views.employeeApi), ] -
Django-Using distinct on a specific field with annotate
I have following models: class Post(models.Model): title = models.CharField(max_length=30) class PostView(models.Model): post = models.ForeignKey(Post, related_name='views', on_delete=models.CASCADE) user = models.ForeignKey(get_user_model(), related_name='my_views') created = models.DateTimeField(auto_now_add=True) I want to get posts ordered by number of unique views. I get the posts ordered by views by following code: filters = { 'created__date__gte': datetime.datetime(year=2020, month=1, day=1), 'created__date__lte': datetime.datetime(year=2021, month=1, day=1), } qs = Post.objects.all().annotate( total_views=Count('views', filter=Q(**filters)) ).order_by('-total_views') above code will calculate all views as total_views. I want to get unique views by user. Is it possible to do that with ORM? -
Django getting percentage filtering the object
So I have this two models: class Freguesia(models.Model): nome = models.CharField("Freguesia",max_length=255) class Intervencao(models.Model): freguesia = models.ForeignKey(Freguesia, on_delete=models.CASCADE, verbose_name="Freguesia") ......... And I want to display in html the top 6 freguesias with more intervecao and the percentage they have in total I already can display the freguesias and the number of intervencoes they have , but I don't know how to display the percentage. My View: def DashboardView(request): freguesias = Freguesia.objects.annotate(num_intervencao=Count('intervencao')).order_by('-num_intervencao')[:6] context = { 'freguesias':freguesias } -
Using crispy forms in HTML's select form field
I am Building a BlogApp and I am trying to style HTML select field in django. edit.html class Edit(forms.ModelForm): class Meta: model = Models fields = ('field1','field2','field3') edit.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> <div class="card-body text-center"> <select name="field1" class="div1" id="field1Id"> <option value="">Select 1</option> </select> <select name="field2" class="div2" id="field2Id"> <option value="">Select 2</option> </select> <select name="field3" class="div3" id="field3Id"> <option value="">Select 3</option> </select> </div> </table> <button type="submit">Save Changes</button> </form> What have i tried :- I know that i can do it with {{ form.field1|as_crispy_field }} BUT i am using some externel library in all of these three fields, AND i cannot access there ids with {{ form.field1 }}, So i will use <select name="field3" class="div3" id="field3Id">. I have no idea , how can i style them. Any help would be Appreciated. Thank You in Advance. -
Django session | Light & Dark Theme
I have a question about the Django sessions, I've been looking at it for a few days and I want to make a light and dark theme on my website, but I do not want to create users, so I use the Django sessions, then I want to have a button on the main page that by default is and if you press it is I have tried several ways, I had thought to create a variable (true or false) in a HTML button that passes it to the view, and from there to know the user session to save if it is true or false. So that it does not have to be changing between dark and light theme. Thanks. -
Django Testing sycopg2.errors.DependentObjectsStillExist: cannot drop
I am working on Django project with Django 3.2 and I am using PostgreSQL as my database backend. When I am trying to run tests in the python side I am getting an error regarding foreign key constraints. psycopg2.errors.DependentObjectsStillExist: cannot drop constraint activities_activitytype_pkey on table activities_activitytype because other objects depend on it DETAIL: constraint activities_activity_activityType_id_9dd5265d_fk_activitie on table activities_activity depends on index activities_activitytype_pkey HINT: Use DROP ... CASCADE to drop the dependent objects too. That would have made sense to me but the thing is that I even made sure to drop the complete test database through pg_admin before proceeding to run the tests. What do I miss ? Thanks -
"'Connection aborted.', RemoteDisconnected" or not getting any info with urllib3 and Django
I am developing a web scraping application with BeautifulSoup and Django and I am experiencing some 'conexion issues' (I think). The app has to check if any website is satisfying all the SEO requirements, and for that I have to make different 'requests'... first to get the "soup" and then to check if the robots.txt and sitemap.xml, for example, exists... so I guess some sites are blocking my app because of that, and I am keep getting the "'Connection aborted.', RemoteDisconnected" error or in another cases, I don't get the error but the "soup" is empty... is there a way to fix this? I have tried with time.sleep() but doesn't seem to work... This is part of my code: http = PoolManager() r = http.request('GET', "https://" + url, headers={'User-Agent': "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36", 'Accept-Encoding': 'br'}) soup = BeautifulSoup(r.data, 'lxml') And where I check if robots and sitemap exists: robots_url = url + "/robots.txt" robot = requests.get(robots_url, headers) if robot.ok: robot = True else: robot = False sleep(5) sitemap_url = url + '/sitemap.xml' sitemap = requests.get(sitemap_url, headers=headers) if sitemap.ok: sitemap = True else: sitemap = False In most of websites the code is working fine … -
HttpResponseRedirect doesn't change url [closed]
HttpResponseRedirect doesn't change the url for me. I can see from the logs that it calls the view which I want to redirect the user to but it never changes the url & sends the user to the other page In my javascript code inside video.html, I send the user to exit view to do some computation video.html navigator.sendBeacon("{% url 'exit' %}", data); def exitView(request): if request.method == 'POST': print("post request inside exit") return HttpResponseRedirect('/') def mainView(request): if request.method == 'GET': print("get request inside mainView") return render(request, 'index.html') My logs look like this post request inside exit get request inside mainView So HttpResponseRedirect does redirect the view from exitView to mainView. However, in the frontend, the user continues to be on main-site/video What I want to do is send the user from main-site/video to main-site/exit & then redirect to main-site/ However, the user continues to stay on the urlpatterns = [ path('admin/', admin.site.urls), path('video/', videoView), path("", mainView, name='index'), path("exit/", exitView, name='exit'), path("accounts/", include('allauth.urls')), ] -
Django Updating Tables
Basically I have an Account table that keeps track of a users balance and then I have a Transaction table that keeps track of all transactions (for all users). When I save data to my Account table 'user: 12' 'type: deposit' 'description: Venmo inc' 'amount: 200.00' I want to update the users current account balance from 'user: 12' balance: 200 to 'user: 12' 'balance: 400.00' The code below works fine: @receiver(post_save, sender=Transaction) def update_account(sender, instance, created, **kwargs): if created: user = instance.user amount = instance.amount a = Account.objects.get(user=user) new_balance = amount + a.balance a.balance = new_balance a.save() But could I also do this? Is this good practice? @receiver(post_save, sender=Transaction) def update_account(sender, instance, created, **kwargs): if created: a = Account.objects.get(user=instance.user) a.balance = instance.amount + a.balance a.save() -
How to redirect a form to a tab (panel)?
I created several tabs with bootstrap in my Django project. I have a form in my second tab (pills-approval-tab). What I want is when a user fills the form, it should redirect the page to the same second tab (pills-approval-tab). I have just 2 tabs. How can I do that? views.py if request.method == 'POST' and request.POST.get('form') == 'risk': form = PdfRiskForm(request.POST, request.FILES, instance=pdf) if form.is_valid(): this_pdf = form.save() ... redirect('????') else: form = PdfRiskForm() ocr.html ... <div class="card-body"> <ul class="nav nav-pills nav-primary" id="pills-tab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="pills-ftables-tab" data-toggle="pill" href="#pills-ftables" role="tab" aria-controls="pills-ftables" aria-selected="true">Financial Tables</a> </li> <li class="nav-item"> <a class="nav-link" id="pills-approval-tab" data-toggle="pill" href="#pills-approval" role="tab" aria-controls="pills-approval" aria-selected="false">Approval</a> </li> </ul> <div class="tab-content mt-2 mb-3" id="pills-tabContent"> {% include './financial_tables_tab.html' %} {% include './approval_tab.html' %} </div> approval_tab.html <div class="tab-pane fade" id="pills-approval" role="tabpanel" aria-labelledby="pills-approval-tab"> ... </div> -
DataTables in Django modify columns ordering
I write Django app, where I have a base.html template and I defined var table where I declared order by column 0 with 'desc' (look below) So I currently use it some templates, where I extend base.html. But now I need to sort in new template firstly by the second column, and after that by the first column (like this: "order": [1, 0, 'desc'] ). I don't know how I modify this variable without a duplicate code. Could somebody help me? var table = $('#example').dataTable( { "columnDefs": [ { "targets": 0, "searchable": false, "order": [0, 'desc'], "ordering": true, } ] } ); -
How to configure apache-airflow with Django project for use of ORM's
I want to configure apache-airflow with the Django project. But I didn't find any resources that help me to set up this. Basically, I want to use Django Orm for scheduling tasks. -
Auto refresh cache DRF
I cache my rest-api with the rest_framework_extensions like: class UpdatedAtKeyBit(KeyBitBase): def get_data(self, **kwargs): basename = kwargs['view_instance'].basename.lower() key = f'api_updated_at_timestamp_{basename}' value = cache.get(key, None) if not value: value = datetime.datetime.utcnow() cache.set(key, value=value) return force_text(value) class CustomListKeyConstructor(DefaultKeyConstructor): list_sql = ListSqlQueryKeyBit() pagination = PaginationKeyBit() updated_at = UpdatedAtKeyBit() def change_api_updated_at(sender=None, instance=None, *args, **kwargs): cache.set(f'api_updated_at_timestamp_{sender.__name__.lower()}', datetime.datetime.utcnow()) for model in [Address, Order, Permission, User]: post_save.connect(receiver=change_api_updated_at, sender=model) post_delete.connect(receiver=change_api_updated_at, sender=model) this works perfect! I cache the GET-list responses from the Models. Now I would like to automatically refresh those views after a update or a save. So that the following requests are already in the cache. How can i solve this? -
Static files on Django 404 with static_root and static_url both set
I know this question has been answered a lot but I can't seem to work this out. My static files are there, at the location I've told django they are. Debug is set to True, and static_url is set to '/static/' but the static files are 404ing. development(settings).py DEBUG = True logger.info(f"Debug is {DEBUG}") STATIC_URL = "/static/" STATIC_ROOT = "/home/phillyharper/dask/static" logger.info(STATIC_ROOT) Running python manage.py runserver using these settings produces this result: 2021-05-09 07:17:03.197 | INFO | dask.settings.development:<module>:4 - Debug is True 2021-05-09 07:17:03.197 | INFO | dask.settings.development:<module>:47 - Debug is True 2021-05-09 07:17:03.197 | INFO | dask.settings.development:<module>:50 - /home/phillyharper/dask/static 2021-05-09 07:17:03.198 | INFO | dask.settings:<module>:7 - DEV SETTINGS SETTINGS 2021-05-09 01:47:03.417 | INFO | dask.settings.development:<module>:4 - Debug is True 2021-05-09 01:47:03.417 | INFO | dask.settings.development:<module>:47 - Debug is True 2021-05-09 01:47:03.417 | INFO | dask.settings.development:<module>:50 - /home/phillyharper/dask/static 2021-05-09 01:47:03.417 | INFO | dask.settings:<module>:7 - DEV SETTINGS SETTINGS However, when I click onto the page - none of the static files load. They all 404, giving this:~ [09/May/2021 01:47:51] "GET / HTTP/1.1" 200 22203 [09/May/2021 01:47:51] "GET /static/src/assets/lib/perfect-scrollbar/css/perfect-scrollbar.css HTTP/1.1" 404 1800 [09/May/2021 01:47:51] "GET /static/src/assets/lib/material-design-icons/css/material-design-iconic-font.min.css HTTP/1.1" 404 1854 [09/May/2021 01:47:51] "GET /static/src/assets/css/app.css HTTP/1.1" 404 1692 [09/May/2021 01:47:51] "GET /static/src/assets/lib/jquery/jquery.min.js HTTP/1.1" 404 … -
NoReverseMatch Error in Django project: Bootstrap link causing problem? Can't see how or why though
I'm really stumped on how to fix this. I've dealt with NoReverseMatch errors before and I'm aware that it's usually an issue with the URL path or the function related to it in views.py, but this particular page I'm trying to render keeps returning NoReverseMatch saying that there's a line in my layout.html template that contains my link to Bootstrap that's the problem. I've tried editing this line out but no good. I've checked the URL path and the relevant function in views.py but I can't see anything that suggests an error. Here's what I mean... Error message Reverse for 'register' not found. 'register' is not a valid view function or pattern name. Error during template rendering In template C:\Users\Leigh\Desktop\Coursework\CS50Web\project4\network\templates\network\layout.html, error at line 7 Reverse for 'register' not found. 'register' is not a valid view function or pattern name. Here's an image of line 7 being referred to. As I've mentioned, I've checked out line 160 in views.py which calls on the URL in urls.py. Here is the URL path for "register.html" in urls.py path("register", views.register, name="register") I'm at a loss really. I can't see anything that would be causing the NoReverseMatch. "register.html" definitely exists despite Django saying that there … -
loading two html pages linked to different urls in same page(iframe)
I have a page 1.html linked to /registration in urls.py, now I have a another page 2.html linked to /verify. Now I want to display /verify as a pop in /registration page it self. So far I have used iframe to do this but it says 127.0.0.1 refused to connect. <iframe id="theFrame" src="/verify" style="width:100%;" frameborder="0"> </iframe> Iam using djnago btw. Basically I want to display one html page as a pop in another. Thank you! -
Django-q: WARNING reincarnated worker Process-1:1 after timeout
I've installed and configured Django-Q 1.3.5 (on Django 3.2 with Redis 3.5.3 and Python 3.8.5). This is my Cluster configuration: # redis defaults Q_CLUSTER = { 'name': 'my_broker', 'workers': 4, 'recycle': 500, 'timeout': 60, 'retry': 65, 'compress': True, 'save_limit': 250, 'queue_limit': 500, 'cpu_affinity': 1, 'redis': { 'host': 'localhost', 'port': 6379, 'db': 0, 'password': None, 'socket_timeout': None, 'charset': 'utf-8', 'errors': 'strict', 'unix_socket_path': None } } where I have appropriately chosen timeout:60 and retry:65 to explain my problem. I created this simple function to call via Admin Scheduled Task: def test_timeout_task(): time.sleep(61) return "Result of task" And this is my "Scheduled Task page" (localhost:8000/admin/django_q/schedule/) ID Name Func Success 1 test timeout mymodel.tasks.test_timeout_task ? When I run this task, I get the following warning: 10:18:21 [Q] INFO Process-1 created a task from schedule [test timeout] 10:19:22 [Q] WARNING reincarnated worker Process-1:1 after timeout 10:19:22 [Q] INFO Process-1:7 ready for work at 68301 and the task is no longer executed. So, my question is: is there a way to correctly handle an unpredicted task? -
Is there a convention for tightness of database relations vs ease of testing in Django?
Say I have a model with a foreign key: class Thing(models.Model): related_stuff = models.ForeignKey('app.stuff', blank=True, null=True, related_name='things', on_delete=models.PROTECT) def method_of_thing(self): pass This is pretty easy and fast to test, I just create a Thing and away I go testing method_of_thing. However, strictly speaking a Thing should always have related_stuff so in terms of correct constraints this is the relation I should have: class Thing(models.Model): related_stuff = models.ForeignKey('app.stuff', related_name='things', on_delete=models.PROTECT) BUT, when it comes to testing, this means I have to do a hell of a lot of setup in tests, creating the related_stuff. Even using model_bakery or factory_boy this leads to a lot of extra lines and time in my tests. What are the key things to think about when deciding if I should make this tradeoff of data integrity for speed of development and test? Is there a convention / emerged dominant opinion on this within the django community? -
How do I call Datatables draw() method in Ajax?
I am trying to implement datatables draw() method in my Django application using AJAX. I have implemented both datatables and AJAX, which are working fine. However, I am facing a lot of challenges anytime I create a new object and call the draw() method so that datatables can refresh the table and show the newly created data the proper way. If I add the draw() method, the table does not get populated at all except I refresh the page. main.js //datatables $(document).ready(function() { $('table').on('click', ".dropdownDatatableButton" ,function() { $( this ).toggleClass( "active"); }); function csrfSafeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); }; $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); var table = $('#boardsTable').DataTable({ "autoWidth": false, "info": false, "lengthChange": false, "processing": true, "hover": true, "serverMethod": 'post', "searching": true, "ajax": "/boards/api/data/?format=datatables", "pagingType": "full_numbers", "order": [[ 0, "asc" ]], language: { search: "", "zeroRecords": '<img class=' + '"dataTables-error-image"' + 'src=' + "'/static/media/images/empty-search.jpg'" + '/>' + '<p class=' + '"dataTables-error-text"' + '>' + 'No boards were found that match your search' + '<p/>', "loadingRecords": '<div class="spinner-border m-5" role="status">' + '<span class="sr-only d-block">Loading...</span> </div>' + '<p class="d-block text-center mt-3">Pulling board information...' + '</p>', "processing": '<p class="d-block text-center … -
Run Django in DEBUG mode with Daphne
Need help to run django app with daphne in DEBUG mode with pycharm. Is there any way? -
How can i get this value? DJANGO
I would like to collect this value and pass it by post to the database I want to pass {{qs.nombre}} and {{ user.user }} but i try this and not run.. When i try request.POST['maquina']: img My code here: .html <form action="" method="POST"> {% csrf_token %} <div class="container"> <div class="row"> {% for qs in queryset %} <div class="col-xl-12 col-lg-12"> <fieldset class="scheduler-border"> <legend class="scheduler-border">EMPLEADO</legend> <b><p class="black">Identificado: </b>{{ user.username }}</p> <b><p class="black">Empleado: </b>{{ user.first_name }} {{ user.last_name }} </p> <b><p class="black">IP: </b>{{ qs.ip }}</p> <b><p class="black">Maquina: </b><input type="text" name="maquina" value="{{ qs.nombre }}" disabled /></p> <b><p class="black">Nº Maq: </b><input type="text" name="rec_" value="{{ qs.rec }}" disabled/></p> <b><p class="black">Usuario: </b><input type="text" name="user" value="{{ user.user}}" disabled/></p> </fieldset> </div> {% endfor %} -
How to measure usage in a video chat app?
I have a group video chat application where users can randomly pop into rooms to have a conversation. Imagine something like a video reddit This is more of an architecture question than a code question. How do I measure usage? I want to track how long users spend in each room, which rooms are popular, get a history of every room that a user has visited to understand their user profile The most naive thing that I can think of is to create a new table in the database called usage where I log every event such as user entering a room with timestamp, user leaving a room with timestamp that would look something like this for eg - | user | room | event | timestamp |------|----------|---------------|------------ | 1 | bitcoin | join_room | 1620632092 | 2 | comedy | join_room | 1620632094 | 1 | bitcoin | leave_room | 1620632292 | 3 | politics | join_room | 1620632295 | 3 | politics | leave_room | 1620632296 | 4 | dogs | join_room | 1620632296 | 5 | python | join_room | 1620632296 | 4 | dogs | leave_room | 1620632296 | 5 | python | leave_room | 1620632296 …