Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why the update function return int where it must return string?
i have a django website where it include an update function where the user is allow to edit data. the update is done and the data in the database is changed but the problem is that the system crash. and when i tried to print the result of the query the system return int where it should return string and it display the error below : dbEntry.save() #to save into DB AttributeError: 'int' object has no attribute 'save' views.py def update(request,pk): #deny anonymouse user to enter the create page if not request.user.is_authenticated: return redirect("login") else: dbEntry = suspect.objects.get(pk =pk) print( "db entry : ",dbEntry) if request.method == 'POST': first_name = request.POST['fname'] print("first_name : ", first_name) dbEntry = suspect.objects.filter(pk = pk).update(suspect_name = first_name) print( "db entry after update: ",dbEntry) dbEntry.save() #to save into DB return render(request,'blog/update.html', {"dbEntry":dbEntry}) update.html {% extends "base.html" %} {% load static %} {% block body %} <head> <link rel="stylesheet" type="text/css" href="{% static '/css/linesAnimation.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/input-lineBorderBlue.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/dropDown.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/home.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/meta-Input.css' %}"> <meta name= "viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript" src="{% static '/js/jquery-3.1.1.min.js'%}"></script> <title>Welcome</title> </head> <body> <div class="lines"> … -
How to use parameters defined in a triple quoted string(using eval()) outside the string in the method?
I am using triple quoted string, have if-else conditions inside the string, and defining the value of variable as per the conditions, and I am not able to use the variable outside the the string. I tried writing whole class inside of triple quoted string, and it works, I am able to use the variable outside the triple quoted string. It Works when whole class is inside the triple quote, it prints the variable 'a': import pystache codeBlock = ''' class GetData(): def foo(): a = 0 if({{c}} == 5): a = {{d}} * 5; elif({{c}} >= 5 and {{c}} < 10): a = {{d}} * 4; elif({{c}}<5): a = {{d}} * 10; return a ''' codeBlock1 = pystache.render(codeBlock, {'c': 3,'d':10}) compiledCodeBlock = compile(codeBlock1, '<string>', 'exec') eval(compiledCodeBlock) print(GetData.foo()) output: >python a.py runserver >100 And what I want is, the variable 'a' to be printed when the code block does not contain the whole class itself in the following case: (I am not sure if that's possible or not) import pystache class GetData(): def foo(): a = 0 codeBlock = ''' if({{c}} == 5): print('one'); a = {{d}} * 5; elif({{c}} >= 5 and {{c}} < 10): print('two'); a = {{d}} … -
How to implement autocomplete in django 2.2? I have tried existing one's but no support for django 2.2
I want to use autocomplete feature instead of select for my foreign key table value I have tried everything but its got compatibility issues. I need to display data in autocomplete field, rather than select field. I'm using django 2.2. -
show/hide django admin form field based on selection in another field
I am trying to have a Django admin form field to be hidden until I select a specific value from a drop-down I have tried everything including Jquery, the Jquery files load properly so my static root is pointing to the right file but when the admin site load and I change the values on the drop-down nothing happens. I am using the latest Django and python 3.7 also I am using Django-jet as a customize admin template models.py class Incident(models.Model): Incident_Type =models.ForeignKey(IncidentType,on_delete=models.DO_NOTHING, null=True, blank=False) DEM_REASON_CHOICES = (("Payments", "Payments"), ("Policies", "Policies"), ("Legal Issues", "Legal Issues"), ("Deactivation", "Deactivation")) demonstration_reason = models.CharField(max_length=200, choices=DEM_REASON_CHOICES, null=True, blank=True) admin.py @admin.register(IncidentType) class IncidentTypeAdmin(admin.ModelAdmin): @admin.register(Incident) class IncidentAdmin(admin.ModelAdmin): form = IncidentAdminForm forms.py from django import forms from .models import Incident class IncidentAdminForm(forms.ModelForm): class Meta: model = Incident widgets = { 'demonstration_reason': forms.SelectMultiple, } fields = "__all__" class Media: js = ('jet/showhide.js',) My Jquery script (function($) { $(function() { var selectField = $('#id_Incident_Type'), verified = $('#id_demonstration_reason'); function toggleVerified(value) { if (value === 'Demonstration') { verified.show(); } else { verified.hide(); } } // show/hide on load based on pervious value of selectField toggleVerified(selectField.val()); // show/hide on change selectField.change(function() { toggleVerified($(this).val()); }); }); })(django.jQuery); I am loading the script in my … -
Managing migrations with two Django apps connected to same database?
I have two servers / Django apps connected to my one MySql database, 1.example.com and 2.example.com. I want to make all the migrations on 1.example.com, and not have to update the migrations folder / models.py file in 2.example.com every time I want to make a database change. What's proper protocol here? Can I just delete models.py and migrations/ from my 2.example.com? Or is there a Django setting to be aware of. -
Error when attempting to render data to the form via HTTP request (GET)
I'm new to Django and building forms. I have several examples on how to complete a simple operations and will share the code below models.py form Django.db import models class Query(models.Model): query_name = models.CharField(max_length=40, null=True, blank=True) forms.py from django import forms from testUI.models import Query class QueryForm(forms.ModelForm): class Meta: model = Query fields = ['query_name'] views.py from django.shortcuts import render from django.http import HttpResponse from django.template import loader from .models import Query def queries(request): if request.method == "GET": query = Query.objects.all() return render(request, 'testUI/queries.html', {"form": query}) else: query_form = QueryForm(request.POST) if query_form.is_valid(): query_form.save() return render(request, 'testUI/queries.html', {"form": query_form}) else: return HttpResponse("Form is not valid) queries.html {% extends "testUI/base.html" %} {% block content %} <div class="page-header" style="..."> <button type="button" data-toggle="modal" data-target="#newQueryModal" class="btn btn-success" sytle="..."><i class="fas fa-plus"></i>New Query</button> </div> <div> <div class="modal-dialog modal-xl" role="document"> <table class="table"> <thead> <th>Query Name</th> </thead> <tbody> {% for query in form } <tr> <td>{{query.query_name}}</td> </tr> </tbody> </table> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }}<br> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-success">Save Query</button> </form> </div> </div> {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path('queries/', views.queries, name='queries') ] There is one record created using the shell. What … -
Django check files and add to DB
I would like to ask, what could be the best approach to realize something like: I will insert a pdf file to static folder in Django. After That I want Django to check if there is a new file in static folder and if is add file name to Django's sqlite. Whole process I'm trying to do: I have a calendar app in my Django site. I want to check a new pdf file in static folder and save it to that calendar app DB, so it will be as a pdf link in certain day in calendar app -
How to protect my Django code at the time of delivery to Client? [duplicate]
This question already has an answer here: How would I package and sell a Django app? 7 answers How do I protect Python code? 27 answers I have created one web application using Django framework,at the time of delivery i have to give my whole source code to client. If client have done any changes in my settings.py file my application may not work. so is there any way to hide that files? I have tried .pyc conversion of .py files but may be only for simple python files. -
How can I locally create nodes for Cassandra using Django Framework on PyCharm?
I decided to change my database to Cassandra because the website I am creating has very large dataset and currently postgres has extensive query times. From my reading, Cassandra would greatly improve scalability. However, I am not sure how to create a multinode cluster to run locally on my machine for my databases info in settings.py. I was wondering if anyone can give me directions on how to create "multiple hosts" for my settings.py file using Pycharm? Thanks -
Django: Timeout when uploading videos to AWS S3
What is the proper way to upload files to S3 from a DjangoApp hosted on Heroku? Video upload takes about 10 seconds and then I get the error. Heroku is telling me this: 2019-07-23T02:53:52.878879+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=POST path="/predicas" host=el-comercio-editoriales.herokuapp.com request_id=22b60bf7-949b-4f47-bfad-dabc33df9192 fwd="47.156.66.69" dyno=web.1 connect=1ms service=30541ms status=503 bytes=0 protocol=https I suppose I need to make an upload by chunks or something. Any hint would be appreaciated. -
table row order are not updatin in the database after ajax call in django
I am using jquery UI .sortable to sort my table rows by drag and drop. I have declare a field map_order in the model as an order update. so the thing is when I am making ajax call to update the model order field. it didn't update it. but when I console log the sort variable it will show the assigning of index to the pk of model. I have tried to update the filed but it did,nt work HTML <tbody id="#layerTable"> {% for layer in layers %} <tr data-pk="{{ layer.id }}" class="ui-state-default"> <td><input type="checkbox" name="ids" value="{{ layer.id }}" /></td> <td> <a href="{% url 'mapport.maps.layers.one' map.id layer.id %}">{{ layer.name }}</a> </td> <td>{{ layer.heading }}</td> <td>{{ layer.class_group }}</td> <td> <span class="glyphicon glyphicon-resize-vertical"></span> {{ layer.map_order }}</td> <td>{{ layer.map_server }} </td> <td> {% if layer.sql_schema %}{{ layer.sql_schema }}.{{ layer.sql_table }}{% endif %} </td> </tr> JS <script type="text/javascript" charset="utf-8"> $(document).ready(function() { $("tbody").sortable({ update: function(event, ui) { sort = {}; window.CSRF_TOKEN = "{{ csrf_token }}"; $("tbody").children().each(function(){ sort[$(this).data('pk')] = $(this).index(); }); {#var csrftoken = $('input[name="csrfmiddlewaretoken"]').val();#} $.ajax({ url: "{% url "mapport.maps.layers.all" map.id %}sort/", type: "post", data:{sort, csrfmiddlewaretoken: window.CSRF_TOKEN, }, }); console.log(sort) }, }).disableSelection(); }); </script> views @csrf_exempt def sort(self): for index, … -
ModelChoiceField invalid literal for int() with base 10: ''
So I've spent the day trying to chase down a custom thing that I wanted to achieve using FormView. When I use FormView with HTML form method="POST", I am able to get the desired result, mostly. If a user clicks to submit a form and an empty field exists, they get an error message telling them the form is required. I'm aware that I can make the ModelChoiceField required on the form, but was trying to implement my own logic for this. I found through my searching that if I'm not updating anything via the form, form method="GET" may be more appropriate. So I switched to that, and basically got this method working, but my error logic still doesn't quite work the way I'd expect. Long story short, I can use the form method="GET", but when I try to do validation on the form, it doesn't work. Worse yet, if I try to include an empty label, that creates an invalid literal message, because based on this SO...In a Django template, how to specify a dictionary key which is itself an attribute? It doesn't seem possible to specify error logic/validation if the first field is essentially empty, which it is … -
How do I highlight a particular word from a column inside a text using django?
So let's say I have 3 columns. Text | Subject | connector Cancer is caused by windmills.| cancer, windmill| caused by These are all saved inside a postgreSQL database. How do I highlight the words, cancer and windmill (from subject) and caused by (from connector), inside the text and display it on the webpage? {% if db.cause and db.connector in db.text %} <td><mark>{{ db.text }}</mark></td> But this highlights the whole text instead of those 4 words cancer, windmill and caused by. -
How do I create a drop down menu in Django as shown below?
I'm following the instructions from the Django for Beginners book. I'm currently in chapter 13, trying to create my homepage to have a drop down nav bar in the top right and a loge with a create new article button in the top left. However, my code ends up putting the create new article button and the drop down bar both in the right. Moreover, the drop down bar does not show the expected options when I clicked on it. This is written using Django 2.x. Here's my code: <a class="navbar-brand" href="{% url 'home' %}">Newspaper</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> {% if user.is_authenticated %} <ul class="navbar-nav ml-auto"> <ul class="navbar-nav mr-auto"> <li class="nav-item"><a href="{% url 'article_new' %}">+ New</a></li> </ul> <li class="nav-item"> <a class="nav-link dropdown-toggle" href="#" id="userMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ user.username }} </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userMenu"> <a class="dropdown-item" href="{% url 'password_change' %}">Change password</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'logout' %}">Log out</a> </div> </li> </ul> {% else %} <form class="form-inline ml-auto"> <a href="{% url 'login' %}" class="btn btn-outline-secondary">Log in</a> <a href="{% url 'signup' %}" class="btn btn-primary ml-2 ">Sign up</a> </form> {% endif %} <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" … -
Django admin reuse header
I would like to reuse the header of the django admin page in my custom view so I can use the "view site, change password and logout" so I won't have to recode that part. Is it possible to extend only the header part? -
When using localhost in Django to open my project , it redirect to specific domain and says <specific domain> took too long to respond
I am new to django and using 1.10 version and also following this tutorial youtube. Here when i use localhost(http://127.0.0.1:8000/) to run my server it redirects to specific url and its mainly because DEFAULT_REDIRECT_URL ="http://www.tirr.com:8000" and due to this i am getting "ERR_CONNECTION_TIMED_OUT". ROOT_URLCONF = 'kirr.urls' ROOT_HOSTCONF = 'kirr.hosts' DEFAULT_HOST = 'www' DEFAULT_REDIRECT_URL ="http://www.tirr.com:8000" #kirr.co PARENT_HOST = "tirr.com:8000" " what i need is to display my files/application that is created using Django." -
ng-repeat returns blank rows into table
I am trying to populate a table with JSON data from my Django rest framework API utilizing http.get(). I cannot seem to get it to return anything besides the number of blank rows that I have data for. i.e. There are 9 reservations and I get nine blank rows. I do get the data back from the server on the console. I cannot figure out what I am doing wrong! <html ng-app="myReservation" ng-controller="myReservationController"> <head> <meta charset="utf-8"> <title>Waitlist</title> {% load staticfiles %} <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css"> <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-sm-12"> <table class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>id</th> <th>Name</th> <th>Party Size</th> <th>Date</th> <th>Time</th> <th>Location</th> <th>Status</th> </tr> </thead> <tbody> <tr ng-repeat="x in reservationsData"> <td>{{ x.id }}</td> <td>{{ x.name }}</td> <td>{{ x.psize }}</td> <td>{{ x.Date }}</td> <td>{{ x.Time }}</td> <td>{{ x.location }}</td> <td>{{ x.status }}</td> </tr> </tbody> </table> </div> </div> </div> <script src="//code.jquery.com/jquery-3.3.1.js"></script> <label class="col-md-4 control-label" for="makeReservation"></label> <div class="col-md-4"> <button name="singlebutton" class="btn btn-primary" type="submit" ng-click="getData()" id="makeReservation">getData!</button> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.min.js"></script> <script src="{% static 'app/scripts/reservations.js' %}"></script> </body> app.controller('myReservationController', function ($scope, $http) { $scope.saveData = function () { var dte = Date.parse($scope.dateInput); var newdte = new Date(dte).toISOString().slice(0, 10); var data = { name: $scope.nameInput, psize: $scope.psizeInput, Date: newdte, Time: $scope.timeInput, location: … -
Unable to use objects from a module in sys.modules
Because of circular dependencies a want to load a module this way: try: from ..foo import serializers as foo_serializers except ImportError: import sys foo_serializers = sys.modules['app.foo.serializers'] When I use the loaded module in a class definition like this, it says app.foo.serializers has no attribute OtherSerializer although it definitely has: class SomeSerializer(ModelSerializer): some_field = foo_serializers.OtherSerializer() But when I use foo_serializers.OtherSerializer in a class function it works. What does it mean? Are modules in sys.modules fully loaded in the time when the class definition is loaded? What could be a problem here? -
"connection reset by peer [errno 104]" occurs when closing a browser session?
As the title stated, whenever I open up a browser session in edge or safari, go to the stock website, then close the browser, I get the following trace-back: ---------------------------------------- Exception happened during processing of request from ('216.80.75.134', 50926) ---------------------------------------- Traceback (most recent call last): File "/usr/lib/python3.5/socketserver.py", line 625, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.5/socketserver.py", line 354, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.5/socketserver.py", line 681, in __init__ self.handle() File "/usr/local/lib/python3.5/dist-packages/django/core/servers/basehttp.py", line 169, in handle self.handle_one_request() File "/usr/local/lib/python3.5/dist-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/lib/python3.5/socket.py", line 576, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 104] Connection reset by peer ---------------------------------------- Exception happened during processing of request from ('216.80.75.134', 50925) Exception happened during processing of request from ('216.80.75.134', 50924) Traceback (most recent call last): File "/usr/lib/python3.5/socketserver.py", line 625, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.5/socketserver.py", line 354, in finish_request self.RequestHandlerClass(request, client_address, self) ---------------------------------------- File "/usr/lib/python3.5/socketserver.py", line 681, in __init__ self.handle() File "/usr/local/lib/python3.5/dist-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/usr/local/lib/python3.5/dist-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/lib/python3.5/socket.py", line 576, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 104] Connection reset by peer ---------------------------------------- Traceback (most recent call last): File "/usr/lib/python3.5/socketserver.py", line 625, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.5/socketserver.py", line 354, in finish_request … -
AttributeError at /stories/1/ 'int' object has no attribute 'replace'
context = super(PostMixinDetailView, self).get_context_data(**kwargs) … ▶ Local vars /home/hola/Desktop/several/hitcount/views.py in get_context_data hit_count_response = self.hit_count(self.request, hit_count) … ▶ Local vars /home/hola/Desktop/several/hitcount/views.py in hit_count if not qs.filter(user=user, hitcount=hitcount): … ▶ Local vars /home/hola/.local/lib/python3.6/site-packages/django/db/models/query.py in bool self._fetch_all() … ▶ Local vars /home/hola/.local/lib/python3.6/site-packages/django/db/models/query.py in _fetch_all self._result_cache = list(self._iterable_class(self)) … ▶ Local vars /home/hola/.local/lib/python3.6/site-packages/django/db/models/query.py in iter for row in compiler.results_iter(results): … ▶ Local vars /home/hola/.local/lib/python3.6/site-packages/django/db/models/sql/compiler.py in apply_converters value = converter(value, expression, connection) … ▶ Local vars /home/hola/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/operations.py in convert_uuidfield_value value = uuid.UUID(value) … ▶ Local vars /usr/lib/python3.6/uuid.py in init hex = hex.replace('urn:', '').replace('uuid:', '') … -
How can login in DRF?
I'm just starting to understand the DRF. Made authentication by jwt token. How now from this login page to access the site? How can I login to the site in this case? app/urls re_path(r'^users/login/?$', LoginAPIView.as_view()), models class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), db_index=True, max_length=255, unique=True) first_name = models.CharField(_('first_name'), db_index=True, max_length=255) last_name = models.CharField(_('last_name'), db_index=True, max_length=255) email = models.EmailField(db_index=True, unique=True) #... USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() serializer class LoginSerializer(serializers.Serializer): email = serializers.CharField(max_length=255) username = serializers.CharField(max_length=255, read_only=True) password = serializers.CharField(max_length=128, write_only=True) token = serializers.CharField(max_length=255, read_only=True) def validate(self, data): email = data.get('email', None) password = data.get('password', None) if email is None: raise serializers.ValidationError( 'An email address is required to log in.' ) if password is None: raise serializers.ValidationError( 'A password is required to log in.' ) user = authenticate(username=email, password=password) if user is None: raise serializers.ValidationError( 'A user with this email and password was not found.' ) if not user.is_active: raise serializers.ValidationError( 'This user has been deactivated.' ) return { 'email': user.email, 'username': user.username, 'token': user.token } view class LoginAPIView(APIView): permission_classes = (AllowAny,) serializer_class = LoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) If I write #... user = authenticate(request, username=username, password=password) print(user) if user is … -
Why do I need to use {% static to render js files on index build by webpack? (CloudFront, production) webpack django vue cloudFront beanstalk
Im currently trying to upload into production (beanstalk) my Django app, using webpack to wrap a vue app. The problem is that locally works perfect, I can render the text, style, js files, etc. but when I upload the code to production, the file "index.html" (the output from webpack) render, but the js and css files don't. When I add manually the tag for static ({% load static %}) and upload the code, the view render the "index.html" file and the js, css files also. Why do I need to add the static tag on production? what am I doing wrong? On production (beanstalk) I use CloudFront as CDN for static files, and when I debug beanstalk (eb logs) I see a 404 code trying to render the js, css files (with the other images that render with django template system, that render ok, i don't see any message, not even a 200 code (I suppose this is because the CDN deliver the files)) What code/debug logs/config should I upload here? Thanks! -
How to debug long wait times for Django Website
I have a Django website whose response time I would like to improve. When I click intra-site links on my site the result is either an immediate loading of the next page or a 20-30 second wait before the page loads. I find no reproducible patterns in this behavior to help me identify a fix. I realize that there are many, many reasons why this might be the case and much more information on my specific configuration would be required for specific help in this area. However, instead of dumping pages of config info and asking for specific suggestions, I hope others can provide suggestions as to general areas I should investigate that would be consistent with the following observation: Debug-Toolbar shows that total CPU time & SQL query times are in a reasonable range (< 1 sec), however the total browser request time is 22 seconds (see image). Why might these values be so different? What might account for several seconds of request time that wouldn't also fall under CPU-time? -
Matplotlib graph in Django (not a picture)
I have a quest about running a plot (matplotlib) in Django. I mean i don't wanna save a picture (png/jpeg) and show on website, but i want to run interactive plot on the website. I was trying to find similar problem on the stackOverflow but i didn't find. -
How to wildcard a URL package in a Django template?
I have this url: path('use_template/', views.use_template, name='use_template') Now I want to write an if statement in my template, so I define the URL as a variable. {% url 'use_template' as use_template %} {% if request.path == use_template %}### conditional stuff here ###{% endif %} However, I also want to pass a package to the view via the URL, e.g: path('use_template/<int:template_id>/', views.template_detail, name='template_detail') How can I write my if statement so all the possible <int> package values are captured?