Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django error to final deployment not finding url
any idea why this could not be working?? when in urls.py does not give any error except when in production. this is the error when deploying. ModuleNotFoundError at /admin No module named 'djangopdf.project' Request Method: GET Request URL: https://pdfshellapp.herokuapp.com/admin Django Version: 2.2.7 Exception Type: ModuleNotFoundError Exception Value: No module named 'djangopdf.project' Exception Location: /app/djangopdf/urls.py in <module>, line 18 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.9 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Mon, 25 Nov 2019 04:34:24 +0000 this is my urls.py: from django.contrib import admin from django.urls import path from djangopdf.project import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.HOME.as_view(), name='home'), path('signup/', views.signup_views, name='signup'), path('contact/', views.contact, name='contact'), path('main/', views.upload, name='main'), path('logout/', views.logout_views, name='logout'), path('login/', views.login_views, name='login'), ] -
Django group by max in a migration
How do you write a group-by aggregate that works in a Django migration? I have two models, Parent and Child. One parent can have hundreds of child records linked through a parent ForeignKey column in the child. I've added a new column called max_timestamp to Parent which I want to use to cache the largest Child.timestamp value. To efficiently update this retroactively, I need to run the equivalent of: SELECT parent_id, MAX(timestamp) AS max_timestamp FROM myapp_child GROUP BY parent_id; in Django's ORM, and the use that query to update the Parent records. Seems pretty simple, right? The ORM usage should be similar to the answer presented here. However, it's not working. My migration looks like: from django.db import migrations from django.db.models import Max def update(apps, schema_editor): Child = apps.get_model("myapp", "Child") Parent = apps.get_model("myapp", "Parent") qs = Child.objects.all().values('parent_id').annotate(max_timestamp=Max('timestamp')).distinct() total = qs.count() print('count:', total) i = 0 for data in qs.iterator(): print(data) parent = Parent.objects.get(id=data['parent_id']) parent.max_timestamp = data['max_timestamp'] parent.save() class Migration(migrations.Migration): dependencies = [ ('myapp', '0001_add_timestamp'), ] operations = [ migrations.RunPython(update), ] Yet when I run the migration, it doesn't seem to actually aggregate, and I see output with duplicate parent_ids like: {'parent_id': 94, 'max_created': datetime.datetime(2019, 9, 8, 20, 1, 52, 700533, … -
Azures' windows VM is getiing restarted 1-3 times daily running simple Django server
I'm running a Django server in a Windows VM in the Azure portal. I'm running Windows server 2019 8 GB ram and 4 virtual processors. The Server has a 10-30 request per minute, and the main function is to parse a file in an external software using pyautogui to interact with the buttons of the external software. Since I'm using that library I have to have the connection always open in another VM. but this last never get restarted running the same Django server (with the difference that this not receive requests) the Event Viewer of windows never has any insight about the issue... so I would like to know if any of you have faced something similar? It would be very helpful any help. I have had this issue a long long time ago and right now the only solution is having a status bot to check the server availability and knowing when i have to restart it. -
How to upload files to media folder on django using angular?
I'm trying to upload a file using angular on django but its not saving it on the media folder. It just saves it on the database. I have tested the api on postman and it saves the file on the database and on the media folder. But when i used angular, it just saves it on the database. Below is my angular code: file.component.ts saveFileForm() { let file = this.fileForm.get('contentFile').value; let final_file = file.replace("C:\\fakepath\\", ""); console.log('file', final_file); this.coursemoduleService.uploadFile( this.contentDetails.content.id, final_file ).subscribe( result => console.log(result), error => console.log(error) ); } file.component.html <div class="modal fade" id="newFileForm" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Upload File</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form [formGroup]="fileForm" (ngSubmit)="saveFileForm()" enctype="multipart/form-data"> <div class="modal-body m-3"> <div class="form-group"> <label class="form-label w-100">File input</label> <input type="file" formControlName="contentFile"> <small class="form-text text-muted">Example block-level help text here.</small> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-success">Save changes</button> </div> </form> </div> </div> </div> Below is my django code. @action(detail=True, methods=['POST']) def file(self, request, pk=None): contentfile = request.data['contentfile'] content = Content.objects.get(id=pk) contentItemCount = ContentItem.objects.filter(contentitem_content_id=pk).count() contentItemCount += 1 contentitem = ContentItem.objects.create( contentitem_type = 1, contentitem_order = contentItemCount, contentitem_content_id = content ) print(contentitem) contentFile = ContentFile.objects.create( contentfile = … -
Django NoReverseMatch at /provider/ 'providers' is not a registered namespace
i'm learning django . having the above error when rendering the provider page , if i removed the the html code the page will load without error but with the below code it give the above error thank in advance the html: ''' <ul class="all-cat-list"> {% for category in category_list %} <li><a href="{% url 'providers: provider_list_category' category.slug %}">{{category}} <span class="num-of-ads">({{category.total_providers}})</span></a></li> {% endfor%} </ul> </div> <ol class="breadcrumb" style="margin-bottom: 5px;"> <li><a href="/">Home</a></li> <li class="active"><a active href="{% url 'providers :provider_list' %}> All Categories </a> </li> {% if category %} <li class="active">{{category}} </li> {% endif%} </ol> <div class="ads-grid"> <div class="side-bar col-md-3"> <div class="search-hotel"> <h3 class="sear-head">Search</h3> <form method="GET" action="{url 'providers : provider_list' %}"> <input type="text" value="Product name..." name ="q" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Product name...';}" required=""> <input type="submit" value=" "> </form> </div> ''' the Views: '''' def providerlist(request,category_slug = None): category = None providerlist = Provider.objects.all() categorylist = Category.objects.annotate(total_providers=Count('provider')) if category_slug: category= get_object_or_404(Category, slug = category_slug) providerlist = Category.filter(category=category) search_query = request.GET.get('q') if search_query : providerlist = providerlist.filter( Q(name__icontains=search_query) | Q(description__icontains=search_query)| Q(category__category__name__icontains = search_query) ) template = 'provider/provider_list.html' context = {'provider_list': providerlist ,'category_list' : categorylist} return render(request,template,context) def providerdetail(request,provider_slug): #print(provider_slug) providerdetail=get_object_or_404(Provider,slug=provider_slug) providerimage = ProviderImages.objects.filter(provider = providerdetail) template ='provider/provider_detail.html' context = … -
Passing variable between view and JS; Django
I am first passing a JS variable 'confirmed' to my Django view via POST request. I then run a python script which takes this variable and does some processing. Finally I want to pass it back to my html/JS so I can display the processed data. I am currently trying to use Django sessions to achieve my goal but there is a '1 session delay', so the session variable which I update is returning as the value from the previous session. Is there a better way I can pass the variable from my view to JS/a fix for my current solution? VIEW: def crossword(request): if request.method == 'POST': Session.objects.all().delete() str_squares = (request.body).decode('utf-8') squares = [int(i) for i in str_squares.split(',')] letters = puzzle_solver.solve_puzzle(3, squares) # print(letters) for each_square in letters.keys(): request.session[each_square] = letters[each_square] request.session.modified = True return render(request, 'crossword.html') JS: // Output a list of active squares var xhr = new XMLHttpRequest(); var generate = { Generate:function(){ var confirmed = []; for (i=0; i<active_boxes.length; i++){ confirmed.push(active_boxes[ i ].id_num); } console.log(confirmed); xhr.open("POST", "http://localhost:8000/", true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(c=confirmed); console.log("{{ request.session.keys }}") console.log("{{ request.session.values }}") var tester = parse_session_keys("{{ request.session.keys }}"); console.log(tester); solve_crossword(tester); }}; -
Django Wizard Form, Lost Values in preview steps
I am using a django formtools. I have two forms, first form called PersonalData and second form called Reference. When I fill the first form(PersonalData), I press button submit and go to the second forms. I fill the second form(Reference), but I press the button prev step, and return the first form, but the textbox and another ui is empty. How to re fill the first step? -
MySQL procedure execution results
Convert text to json using procedure When executing a procedure in the workbench, the following is entered : {"data1" : "8192","data2" : "30"} When running a procedure in django, the following is entered : {"data1" : "8192 ","data2" : "30} django(pymysql) code: try: cursor.callproc("convertData", [chk_id, var_data, sta_data]) cursor.fetchall() finally: cursor.close() return HttpResponseRedirect(success_url) Is there an input method without line breaks? -
Django Creating A Dynamic XML Sitemap That Updates Every Day
How do I implement a dynamic sitemap in Django that updates itself based on newly added courses and lessons as well as all other static links? The dynamic links that constantly get added or edited from admin are courses and lessons slugs are using this format: domain.com/courses/courses/course_slug/lesson_slug Directory Structure: https://imgur.com/a/eG3JlXE https://imgur.com/a/mZDeIf6 https://imgur.com/a/mm9W1G3 Updated Memberships urls.py: https://dpaste.de/mT0d Updated Courses urls.py code: https://dpaste.de/6d54 Updated Project settings.py and urls.py: https://dpaste.de/KpCc All other code: https://github.com/danialbagheri/video-membership Here are all of the static links: / /courses/ /about/ /contact/ /memberships/ /memberships/profile/ /termsofservice/ /privacypolicy/ /memberships/payment/ And all of the allauth ones. I tried following some youtube videos here but I am still completely lost. I would appreciate any help with this. -
Httpresponse redirect exception not catching error
I have a phone verification system I coded today but the last step in the process is not working. When the wrong passcode is entered by the user it should throw a ValueError but the except statement I have is not catching the error. class PhoneVerifyView(LoginRequiredMixin, SuccessMessageMixin, FormView): form_class = PhoneVerifyForm template_name = 'phone_verify/phoneverification.html' success_url = reverse_lazy('overview') success_message = 'You have successfully verified your phone number!' def form_valid(self, form): employee = self.request.user user_input = form.cleaned_data['passcode'] phone_verify = get_object_or_404(PhoneVerify, employee=employee) try: if user_input == phone_verify.passcode: phone_verify.verified = True phone_verify.save() return super(PhoneVerifyView, self).form_valid(form) except ValueError: return HttpResponseRedirect(reverse_lazy('overview')) ValueError at /phone_verify/ The view phone_verify.views.PhoneVerifyView didn't return an HttpResponse object. It returned None instead. Thoughts on why this except statement is not working? -
How to limit text inside a div
I currently have a todo website, and on the home screen I display events in a div. However, when there is a really long title it overflows. Currently I have the x overflow hidden. How would I make it so it would add a ... at the end? I tried text-overflow: ellipsis, but that doesn't seem to help. Code that displays events: <div class="col-md-6 inline mb-4"> <h3 class="ml-1">Events:</h3> <div class="events-content-section ml-2"> {% for event in events %} <div class="mb-2" style="display: flex; align-items: center;"> <button type="button" class="view-event btn btn-light" style="width: 100%;" data-id="{% url 'view-event' event.pk %}"> <span> <h4 style="float: left;">{{ event.title }}</h4> <button type="button" class="update-event btn btn-sm btn-info ml-1" data-id="{% url 'update-event' event.pk %}" style="float: right;"> <span class="fas fa-edit"></span> </button> <button type="button" class="delete-event btn btn-sm btn-danger mr-2 ml-2" data-id="{% url 'delete-event' event.pk %}" style="float: right;"> <span class="fa fa-trash"></span> </button> </span> </button> </div> {% endfor %} </div> </div> css for div .events-content-section { background: #f5f5f5; padding: 10px 20px; border: 3px solid #dddddd; border-radius: 3px; overflow-y: auto; overflow-x: hidden; text-overflow: ellipsis; height: 400px; } -
Bootstrap datepicker + Django + Docker not working
I am running into a strange problem that I have tried debugging without success. I am using the django-bootstrap-datepicker-plus library to render datepickers on certain fields on my Django forms, and they appear correctly in dev (locally) however, they do not appear when I run them in a docker setup. I have include_jquery set to True in settings, and I am not loading any other jquery files. Any suggestions? local: docker: -
Failed to query Elasticsearch using : TransportErrorr(400, 'parsing_exception')
I have been trying to get the Elasticsearch to work in a Django application. It has been a problem because of the mess of compatibility considerations this apparently involves. I follow the recommendations, but still get an error when I actually perform a search. Here is what I have Django==2.1.7 Django-Haystack==2.5.1 Elasticsearch(django)==1.7.0 Elasticsearch(Linux app)==5.0.1 There is also DjangoCMS==3.7 and aldryn-search=1.0.1, but I am not sure how relevant those are. Here is the error I get when I submit a search query via the basic text form. GET /videos/modelresult/_search?_source=true [status:400 request:0.001s] Failed to query Elasticsearch using '(video)': TransportError(400, 'parsing_exception') Traceback (most recent call last): File "/home/user-name/miniconda3/envs/project-web/lib/python3.7/site-packages/haystack/backends/elasticsearch_backend.py", line 524, in search _source=True) File "/home/user-name/miniconda3/envs/project-web/lib/python3.7/site-packages/elasticsearch/client/utils.py", line 69, in _wrapped return func(*args, params=params, **kwargs) File "/home/user-name/miniconda3/envs/project-web/lib/python3.7/site-packages/elasticsearch/client/__init__.py", line 527, in search doc_type, '_search'), params=params, body=body) File "/home/user-name/miniconda3/envs/project-web/lib/python3.7/site-packages/elasticsearch/transport.py", line 307, in perform_request status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout) File "/home/user-name/miniconda3/envs/project-web/lib/python3.7/site-packages/elasticsearch/connection/http_urllib3.py", line 93, in perform_request self._raise_error(response.status, raw_data) File "/home/user-name/miniconda3/envs/project-web/lib/python3.7/site-packages/elasticsearch/connection/base.py", line 105, in _raise_error raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info) elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception') Could someone tell me if this is an issue with compatibility or is there something else going on? How can I fix it? -
Why Django base.css dont save my changes?
I did change header color background of Django admin, but this dont work, I clear cookies of Chrome, I close all and run again... i dont know. Django /static/admin/css/base.css -
Django Navbar Categories Link Issues
When I click the categories link in the menu, I get the following error. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/post/categorylist/ Raised by: post.views.post_detail No Post matches the given query. models.py def get_categorylist_url(self): return reverse('post:categorylist', kwargs={'slug': self.slug}) views.py def post_categorylist(request, slug): if not request.user.is_superuser: raise Http404() post = get_object_or_404(Post, slug=slug) post.categorylist() return redirect('post:categorylist') urls.py path('categorylist/',views.post_categorylist, name='categorylist'), categorylist.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Test</title> </head> <body> Test message. </body> </html> -
Get pass or fail output from Django unit tests
For my Django project I am trying to get 0 or 1 output from python manage.py test for whether or not all the tests have passed. I'm wanting to run the tests in a bash script and then have the script know whether or not all the tests have passed, and if so continue to do some other actions. From what I can tell this doesn't seem possible -
Connecting Raspberry Pi to Django Web App
I currently have a django web app which is deployed at: http://ltdiadams.pythonanywhere.com/, the home view consists of a bunch of graphs which are made from a csv (stored.csv) included in the project folder. Here is a link to the github for the files: https://github.com/ltdiadams/Garden-Bot-3000. The csv file 'stored.csv' is created using another python script on my Raspberry Pi which reads in values for moisture, light, temperature, etc. from sensors and outputs them into columns of a csv. Now that I have the functioning web app which reads in from a csv I gave it, I'm having trouble getting it to connect to the Pi. That is, how can I make it so that I can go to this website on my Pi, have the Pi output the csv file and have this website read and make the graphs from that csv rather than the one that's included in the django folder? The two csv files are exactly the same, just one has set values I used to get it up and running, and the other which is outputted on the Pi updates constantly as the sensors read in data, I would like for the web app to read in this … -
How to do django-reversion with ManyToMany fields?
I am using django-reversion, it works well on an entity and simples relationships but when the model class have ManyToManyField, o reversion not work. I saw about use `reversion.register(CodeList, follow=["fieldManyToMany"])` but I am using the declarative form `@reversion.register() class MyModel(models.Model):` And don't know how and where to use reversion.register(CodeList, follow=["fieldManyToMany"]) -
Change text or image of an html page from Django admin page?
Is it possible in Django to change a paragraph of index page or to change an image of the index page as an admin from admin page? -
Dynamic Django dynamic initial input with phone number
Looking for some assistance in adding a form field where the phone formatting is done actually in the input itself. Where the ( ) and - automatically fit around the numbers as are they're typed. Any suggestions? -
Django ManyToMany field filter
So I have this system where my Post object has a ManyToMany field and it's called Saves. So like for example on Reddit you can save a post. So I got it working and users can save posts, and it adds them to the ManyToMany field. However, I want to filter out these posts and only show the posts where said user is in the ManyToMany field. Here is my models.py class Post(models.Model): author = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) saves = models.ManyToManyField(User,blank=True,related_name='post_saves') I have the saves field connected to the User model Django provides. And here is my views.py class PostSaveRedirect(RedirectView): def get_redirect_url(self,*args,**kwargs): pk = self.kwargs.get("pk") slug = self.kwargs.get("slug") obj = get_object_or_404(Post,pk=pk,slug=slug) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated: if user in obj.saves.all(): obj.saves.remove(user) else: obj.saves.add(user) return url_ So this is all working fine, it adds the user to the ManyToMany field, but now I want to know how I can filter out posts and only display ones where the user is in the ManyToMany field. Here is my saved posts view. class PostSaveListView(ListView): model = Post template_name = 'mainapp/post_saved.html' paginate_by = 10 queryset = models.Post.objects.all() def get(self,request): posts = Post.objects.all() return render(request, self.template_name) def get_queryset(self): return Post.objects.filter().order_by('-published_date') So with Post.objects.all(), how … -
Cannot submit a form in django template from javascript
I have the following django template. I am submitting the form through javascript, because ultimately I want that the submit button will be hidden, and the form will autosubmit when the input text changes (i want it to autosubmit when a "." is the last character in the text): <form action="/rewrite/" method="post" id="sentence"> {% csrf_token %} <textarea name="inp" id="ans">abc</textarea> <input type="button" value="Submit" name="new_stop" onclick="submitForm()" id="but"> </form> <script> function submitForm() { form.submit(); } </script> Upon clicking the button I get a Forbidden (403) CSRF verification failed. Request aborted. error -
Elasticsearch 5.x Fails to Start
I have been trying to install Elasticsearch, which, for version 7.x seemed easy, whereas for version 5.x is a pain in the neck. The whole ordeal exists because there is a slew of compatibility requirements between the Elasticseach, Django Haystack, Django CMS and other things. If someone has a nice table or a way to wrap their head around that, I'd be happy to hear it. As to the actual question, after installing ES 5.x, I cannot seem to get it working. user@user-desktop:~/sites/project-web/project$ sudo systemctl restart elasticsearch user@user-desktop:~/sites/project-web/project$ curl -X GET localhost:9200 curl: (7) Failed to connect to localhost port 9200: Connection refused user@user-desktop:~/sites/project-web/project$ Entities that are uncommented in /etc/elasticsearch/elasticsearch.yml # ======================== Elasticsearch Configuration ========================= # # NOTE: Elasticsearch comes with reasonable defaults for most settings. # Before you set out to tweak and tune the configuration, make sure you # understand what are you trying to accomplish and the consequences. # # The primary way of configuring a node is via this file. This template lists # the most important settings you may want to configure for a production cluster. # # Please consult the documentation for further information on configuration options: # https://www.elastic.co/guide/en/elasticsearch/reference/index.html # # ---------------------------------- Cluster ----------------------------------- … -
Only displaying red errors in pylint-django VS Code
In Visual Studio Code, when working on a Django project, I made the decision to use the pylint-django package for linting. Currently, In my python files, Numerous "warnings" occur in the colour blue. This is not what I want. In my python files, I don't want any blue or yellow warnings, I only want any red or "major" errors to display within my files. Does anybody know how to accomplish this within Visual Studio Code? Also here is my current settings.json for VS code: { "window.zoomLevel": 2, "python.linting.pylintArgs": [ "--load-plugins=pylint_django" ] } -
Django many to one relationship, foreign key as text input
I have 2 databases, Book and Comment (one book could have many comments, but each comment only refers to one book). Each database has an HTML form for the user to input book data or comment. ISBN is the primary key for the Book database and foreign key for the Comment database. In both html form, user will use text input to input ISBN. How can I revise my html form and code below so that such many to one relationship will be created? models.py class Book(models.Model): ISBN = models.BigIntegerField(primary_key=True) Chinese_Book_Name = models.CharField(max_length=200) English_Book_Name = models.CharField(max_length=200, blank = True) Author_Name = models.CharField(max_length=100) class Comment(models.Model): ISBN = models.ForeignKey(Book, on_delete = models.CASCADE) age = models.CharField(max_length=10) score = models.IntegerField() comment = models.TextField() topic = models.CharField(max_length=100, blank = True) name = models.CharField(max_length=50) contact = models.CharField(max_length=200, blank = True) Views.py def saveBook(request): ISBN = request.POST['ISBN'] Chinese_Book_Name = request.POST['chinese name'] English_Book_Name = request.POST['english name'] Author_Name = request.POST['author name'] book = Book(ISBN = ISBN, Chinese_Book_Name = Chinese_Book_Name, English_Book_Name = English_Book_Name, Author_Name = Author_Name) book.save() return redirect('/input/addComment') def saveComment(request): ISBN = request.POST['ISBN'] age = request.POST['age'] score = request.POST['score'] topic = request.POST['topic'] name = request.POST['name'] contact = request.POST['contact'] comment = Comment(ISBN=ISBN, age = age, score = score, topic = …