Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to change admin filed name in django, python
I added one model Author in models.py file in my app and created model names for the author while I opened in admin panel it's showing as Author object(12) how can I change that? i tried to add Unicode class Author(models.Model): author_name=models.CharField(max_length=300) i need want field name instead of Author object in the admin panel -
how does django ORM handle thousands of concurrent requests as it is synchronous?
As Django ORM is a synchronous piece of code and django is WSGI based, then how it serve thousands of concurrent request at a time. -
Django sitemaps: XML declaration allowed only at the start of the document
I have been working on the implementation of the sitemaps on Django-2.2 for the Blog website. The code structure I followed was- Sitemaps.py from django.contrib.sitemaps import Sitemap from .models import Post class PostSitemap(Sitemap): changefreq = "never" priority = 0.9 def items(self): return Post.objects.all() urls.py from django.contrib.sitemaps.views import sitemap from .sitemaps import PostSitemap sitemaps = { 'posts': PostSitemap } urlpatterns = [ url(r'^sitemap\.xml/$', sitemap, {'sitemaps' : sitemaps } , name='sitemap'), ] settings.py INSTALLED_APPS = [ ... 'django.contrib.sites', 'django.contrib.sitemaps', ] SITE_ID = 1 I guess that was pretty much it as I referenced so many links. but when I open 127.0.0.1:8000/sitemap.xml It gives me th following error- This page contains the following errors: error on line 2 at column 6: XML declaration allowed only at the start of the document Below is a rendering of the page up to the first error. That's it, nothing on the server log. Please, If anyone can please help me out. Thanks in advance -
Passing parameters from a view function to another through HTML rendered by view1 without URL changing?
I have 2 views functions in django: > def view1(request): > dict_ex = Mod.objects.all() > ............... (modifying and processing the dict_ex variable) > return render(request, 'view1.html', {"dd": dict_ex}) Then I have these lines in view1.html: {% for k, v in dd.items %} Name: {{ v }} <a class="btn btn-primary" href="{% url 'view2' k.id %}">Choose this </a> {% endfor %} Then I have my view2 that needs the modified dict_ex to get other values needed: > def view2(request): > dict_ex = Mod.objects.all() > ............... (modifying and processing the dict_ex variable) > ....... (obtaining var1 from different operations on dict_ex) > return render(request, 'view2.html', {"v": var1}) Is there any method to pass the modified dict_ex from view1 to view2 functions through view1.html? I don't want to repeat these lines of code in view2 too > dict_ex = Mod.objects.all() > ............... (modifying and processing the dict_ex variable) Is there a way to acces the view2 function like this: view2(request, dict_ex) without changing the URL ? I have these in my URL_PATTERNS: path('view_one/', view1, name='view1'), path('view_two/<int:id>', view2, name='view2'), -
Could not parse the remainder: '['prod_title']' from 'd['prod_title']'
From the yesterday, I am trying to get data from the existing database of mongodb atlas. But I am stuck at a point.Whenever I tried to get data from the database using for loop within the html, it throws an error saying that Could not parse the remainder: '['prod_title']' from 'd['prod_title']' I tried a lot of answers posted on the similar questions but after getting frustrated, I choose to post the problem here. Here is the views.py file from django.shortcuts import render import pymongo client = pymongo.MongoClient('mongodb+srv://danial:1234@wearit-qyueb.mongodb.net/test?retryWrites=true&w=majority') db=client.scraped_data.all_brands rand_doc = db.aggregate([{ '$sample': { 'size': db.count() } }]) # Create your views here. def index(request): template='products/products.html' contaxt=locals() return render(request,template,contaxt) def home(req): return render(req, 'products/home.html',{'data':rand_doc}) And this is the the html file. <div class="row"> <div class="col-xs-18 "> <div class="products wrapper grid products-grid"> <ol class="products list items product-items"> {% for d in data %} <li class="item product product-item"> <div class="product-item-info" data-container="product-grid"> <a class="product photo product-item-photo" href="https://www.khaadi.com/pk/lkb19505-pink-3pc.html" tabindex="-1"> <span class="product-image-container"> <span class="product-image-wrapper"> <span> <span class="product-image-container"> <span class="product-image-wrapper"> <img class="product-image-photo"src="https://d224nth7ac0evy.cloudfront.net/catalog/product/cache/1e8ef93b9b4867ab9f3538dde2cb3b8a/g/l/glm-18-10_eid_1_.jpg } " alt="Shirt Shalwar Dupatta"> </span> </span> </span> </span> </span> </a> <div class="product details product-item-details"> <div class="info-holder"> <strong class="product name product-item-name"> <a class="product-item-link" href="https://www.khaadi.com/pk/lkb19505-pink-3pc.html"> {{ d['prod_title'] }} </a> </strong> </div> <div class="info-holder"> <div class="price-box price-final_price" … -
pass data from one view to another django
I have two views in my app Views.py def selectwarehouse(request): z = Warehouse.objects.all() return render(request, 'packsapp/employee/selectwarehouse.html', {'z': z}) def warehouse_details(request): queryset = AllotmentDocket.objects.filter(send_from_warehouse = 1) return render(request, 'packsapp/employee/allotwarehousedetails.html', {'query': queryset}) selectwarehouse.html {% block content %} <label>Select Warehouse<label> <select id="the-id"> {% for i in z %} <option value="{{ i }}">{{ i }}</option> {% endfor %} <form method="post" novalidate> {% csrf_token %} <a href="{% url 'employee:warehouse_details' %}" class="btn btn-outline-secondary" role="button">Proceed</a> <a href="{% url 'employee:products_table' %}" class="btn btn-outline-secondary" role="button">Nevermind</a> </form> </select> {% endblock %} I want that when a person selects the "Warehouse" from the dropdown and clicks on Proceed, it should pass that value to def warehouse_details and pass the value to Allotment queryset. How Can I do that ? -
How fetch a list of dates where cluster = C18 and Mean is the model name using queryset in django?
y_axis = Mean.objects.filter(Cluster_ID = 'C18').values_list("Date_id").distinct() -
I can't open my local server. I made todo list
Present states I made easy "to do list". I copied and pasted from Japanese website. These procedures was going well on the way, however when I set up local server, this error occurred python manage.py runserver 8080 Performing system checks... System check identified no issues (0 silenced). You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. October 14, 2019 - 18:23:49 Django version 2.2.5, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8080/ Quit the server with CTRL-BREAK. C:\Users\kazu\Anaconda3\lib\site-packages\django\views\generic\list.py:88: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'todo.models.Todo'> QuerySet. allow_empty_first_page=allow_empty_first_page, **kwargs) Internal Server Error: /todo/list/ Traceback (most recent call last): File "C:\Users\kazu\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\kazu\Anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: todo_todo The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\kazu\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\kazu\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\kazu\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\kazu\Anaconda3\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, … -
WSGI error using Django 2.2 on Elastic Beanstalk
Trying to access a Django 2.2 web app deployed to AWS Elastic Beanstalk gives a 500 error. When checking the elastic beanstalk logs the below errors are shown. mod_wsgi (pid=3388): Target WSGI script '/opt/python/current/app/app_name/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=3388): Exception occurred processing WSGI script '/opt/python/current/app/app_name/wsgi.py'. Traceback (most recent call last): File "/opt/python/current/app/app_name/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/registry.py", line 83, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant -
Pylint with Django
I have the following directory structure in a Django project: . ├── config ├── element ├── home ├── static ├── templates ├── tree └── user I'm searching for the easiest command to run pylint on all directories that are python modules. This would be all except 'static' and 'templates'. I tested for example: pylint --load-plugins=pylint_django --ignore=static/,templates/ */ But the ignore switch isn't working. The following would work of course: pylint --load-plugins=pylint_django config element home tree user But I want it as dynamic as possible. When i add a new django app i could forget to update the pylint statement. -
Unable to import 'import_export'
I am developing an app in Django. I have a model named glossary_entry and I want to be able to use the import_export widget for it. So I have already run pip install django-import-export added to settings.py INSTALLED_APPS = [ 'import_export', run: pip freeze>requirements.txt And in my admin.py I have: from django.contrib import admin from .models import glossary_entry from import_export import resources from import_export.admin import ImportExportModelAdmin class glossary_entry_resource(resources.ModelResource): class Meta: model=glossary_entry # Register your models here. admin.site.register(glossary_entry) The problem is that when I run the server, I get Connection negated by 127.0.0.1 But even before that, in my VS code editor, i get an error underlined at lines from import_export import resources from import_export.admin import ImportExportModelAdmin which tells: Unable to import 'import_export'pylint(import-error) What am I missing? -
how to fix - invalid token in plural form: EXPRESSION?
I created a localization file through the: python manage.py makemessages -l en and then django-admin.py compilemessages But I get an error when changing the language invalid token in plural form: EXPRESSION How can i fix this? Django Version: 1.11.25 Exception Type: ValueError Exception Value: invalid token in plural form: EXPRESSION Exception Location: /usr/lib/python3.5/gettext.py in _tokenize, line 91 -
Add two numbers in django and output will print same on same page
I'm new to django and i need to add two numbers x and y . The x and y are inputs from user. Here is my views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'home.html', {'name':'keyur'}) def add(request): val1 = int(request.POST['num1']) val2 = int(request.POST['num2']) # red = add('val1','val2') res = val1 + val2 return render(request,'home.html',{'result': res}) Here is my url.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('add', views.add, name='add') ] Here is my home.html {% extends 'base.html' %} {% block content %} <h1>hello {{name}} !!!!</h1> <form action="add" method="post"> {% csrf_token %} Enter a 1st number: <input type="text" name="num1" placeholder="enter the number"> Enter a 2st number: <input type="text" name="num2" placeholder="enter the number"> <input type="submit"> </form> {% endblock %} Here is my result.html {% extends 'base.html' %} {% block content %} Result is... {{result}} {% endblock %} i want to print the output in same page.. can uh please help me.. -
Connecting Django App to RDS database using AWS ElasticBeanStalk
I am using eb deploy to try and load a Django application and connect it to an RDS database. Within settings I have the following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } And I have all these set within the Environment's Configuration > Software > Environment Properties. The RDS database exists and is available. I have added the Enviornments Instances Security Groups to the RDS database. I am getting the following error when I try to deploy. Traceback (most recent call last): File "./src/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/base.py", line 350, in execute self.check() File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/commands/migrate.py", line 59, in _run_checks issues = run_checks(tags=[Tags.database]) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/checks/database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/db/backends/mysql/validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/db/backends/mysql/validation.py", line 13, in _check_sql_mode with self.connection.cursor() as cursor: File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/db/backends/base/base.py", line 255, in cursor return self._cursor() File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/db/backends/base/base.py", line 232, in _cursor self.ensure_connection() File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection … -
how to run a function from a link withing popup modal bootstrap
I have a django project that includes a popup modal where the modal has tabs as links one of these tabs once the user clicked it must perform a function and retrieve data from the database. The problem is that once the user clicked the tab nothing happen as is the function isn't initialize. urls.py path("events/<int:id>/", getEvents, name = "getEvents"), views.py def getEvents(request,id): q1 = cursor.execute('SELECT Person_.ID FROM Person_ WHERE Person_.ID = {0}'.format(id)) print('q1==>',q1) qresult = q1.fetchone() print("qresult==>",qresult) print("query is not empty!") eventQ = cursor.execute('SELECT Person_.ID, Person_.Full_Name, Events.ID, Events.Event_Title, Events.Event_Details, Links.document_id from Person_, Events, Links where ( Person_.ID = {0}) and (Person_.ID = Links.A_Person or Person_.ID = Links.B_Person) and (Events.ID = Links.A_Event or Events.ID = Links.B_Event) ORDER BY Events.ID DESC '.format(id)) resultEvents = eventQ.fetchall() return render(request,'pictureCard.html',{ "resultEvents":resultEvents, "qresult":qresult, }) pictureCrads.html <!-- Popup Modal --> {% for obj in object_list %} <div id="popModel{{obj.0}}" class="modal fade modal-rtl" role="dialog"> <div class="modal-dialog modal-lg"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header Modal-Pic"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">{{ obj.1 }}</h4> <a href="{% static 'img/logo_title/icon-AddressBar.png' %}" data-toggle="modal" data-target="#test2"><img src="{% static '/img/card/1.png'%}"/></a> </div> <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link" id="contact-tab" data-toggle="tab" href="#contact{{ obj.0 }}" role="tab" aria-controls="contact" aria-selected="false">contact us</a> </li> <li class="nav-item"> <a class="nav-link" id="event-tab" … -
What does <int:question_id> do?
I am learning Django and there's an expression in code "int:question_id" which I'm not getting. from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] -
Name 'x' is not defined
Im having a problem when I try to migrate this shows up. mysite\profesores\admin.py", line 18, in admin.site.register(Profesor, ProfesorAdmin) NameError: name 'ProfesorAdmin' is not defined admin.py # -*- coding: utf-8 -*- from django.contrib import admin from profesores.models import Profesor # Register your models here. class Profesor(admin.ModelAdmin): list_display = ('nombre', 'apellido', 'nacionalidad', 'especialidad') list_filter = ('fecha_publicacion',) date_hierarchy = 'fecha_publicacion' ordering = ('-fecha_publicacion',) class Trainer(admin.ModelAdmin): list_display = ('nombre', 'apellido', 'nacionalidad') list_filter = ('nombre',) date_hierarchy = 'nombre' ordering = ('nombre',) admin.site.register(Profesor, ProfesorAdmin) admin.site.register(Trainer, TrainerAdmin) models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class Profesor(models.Model): nombre = models.CharField(max_length=30) apellido = models.CharField(max_length=40) nacionalidad = models.CharField(max_length=25) especialidad = models.CharField(max_length=60) class Meta: ordering = ["nombre"] verbose_name_plural = "Profesores" def __unicode__(self): return '%s %s' % (self.nombre, self.apellidos) class Trainer(models.Model): nombre = models.CharField(max_length=40) apellidos = models.CharField(max_length=40) nacionalidad = models.CharField(max_length=40) class Meta: verbose_name_plural = "Trainers" def __unicode__(self): return '%s %s' % (self.nombre, self.apellidos) -
Django Rest Framework - Automatically create new model B instance each and every time new model A instance is created
As said in the title. I want my django rest framework to create new model B object instance - with foreign key to model A , each and every time new model A object instance is created, so that they have foreign key relation. Currently i use ViewSets. Thanks for help in advance. -
Save two model instances in one updateview
Am trying to update the User model and UserProfile model in one view but it's not working. No error is shown and no changes are made to the objects. What am I not doing right. Here is my models.py: class UserProfile(models.Model): """User information not related to authentication""" user = models.OneToOneField(User, related_name='user_profile', on_delete=models.CASCADE) age = models.IntegerField() # other fields ignored Here is my serializer.py: class UserSerializer(ModelSerializer): first_name = CharField(max_length=20) last_name = CharField(max_length=20) email = EmailField(required=True, validators=[UniqueValidator(queryset=User.objects.all())]) username = CharField(max_length=32,validators=[UniqueValidator(queryset=User.objects.all())]) password = CharField(min_length=8, write_only=True) confirm_password = CharField(write_only=True) def create(self, validated_data): user = User.objects.create_user( validated_data['username'], email = validated_data['email'], first_name = validated_data['first_name'], last_name = validated_data['last_name'] ) password = validated_data['password'] confirm_password = validated_data['confirm_password'] if password != confirm_password: raise ValidationError({'password': 'Passwords must match'}) else: user.set_password(password) user.save() return user class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password', 'confirm_password') class UserProfileSerializer(ModelSerializer): username = CharField(source='user.username') first_name = CharField(source='user.first_name') last_name = CharField(source='user.last_name') email = CharField(source='user.email') class Meta: model = UserProfile exclude = ('user',) # fields = '__all__' # depth = 1 def update(self, instance, validated_data): user = instance.user instance.user.username = validated_data.get('username', instance.user.username) instance.user.email = validated_data.get('email', instance.user.email) instance.user.first_name = validated_data.get('first_name', instance.user.first_name) instance.user.last_name = validated_data.get('last_name', instance.user.last_name) instance.save() # user.save() return instance Here is view.py: class UserProfileUpdate(UpdateAPIView): queryset = … -
Render ajax post to HTML in Django
I am writing an page that with a form of several inputs wrapped in selectize.js on the top. By clicking a button, I wish to return some queries info based on inputs. I am using ajax to post inputs to avoid page reloading. I am following DJANGO render new result values from AJAX request to HTML page to render the queried result cat_result based on ajax post data in HTML. def cat_select(request): cat_result=[] cat_selected=[] cat_name=['l2','l3'] cat_selected=list(map(lambda x:request.POST.get(x, '').split(','), cat_name)) cat_result=c_result(["US"],cat_selected) #list of tuples I want to get print(cat_selected) print(cat_result) html=render_to_string('esearch/result.html', {'cat_result': cat_result},request) return JsonResponse({'cat':cat_result,'html':html},safe=False) This is the function that works with the main base.html that works for data input, which result.html extend from. def search_index(request): ##something to populate input options for l2 and l3 print(results) context = {'l2':l2, 'l3':l3} return render(request, 'esearch/base.html', context) base.html <form id="cat_select">{% csrf_token %} <input class="site" name="site" type="text"> <input class="l2" name="l2" id="l2" type="text" style="width:30%"> <input class="l3" name="l3" id="l3" type="text" style="width:50%"> <br> <button class="btn btn-outline-success my-2 my-sm-0" type="submit" id="cat_submit">Submit</button> </form> <script type="text/javascript"> $(document).on('submit','#cat_select',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/cat_select', data:{ l2:$('#l2').val(), l3:$('#l3').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function(){ alert ("selected!") } }); }); </script> result.html {% extends "esearch/base.html" %} {% block title %} Result {% endblock %} {% block content … -
i want to insert data in a new model after calling is through a post method , how do in do that when a i call it through the template?
models.py from django.db import models class booking(models.Model): fname=models.CharField( max_length=50) lname=models.CharField( max_length=50) email=models.EmailField(max_length=254) city=models.CharField(max_length=50) state=models.CharField(max_length=50) pin=models.IntegerField() def __str__(self): return self.fname class approved(models.Model): fname=models.CharField( max_length=50) lname=models.CharField( max_length=50) email=models.EmailField(max_length=254) city=models.CharField(max_length=50) state=models.CharField(max_length=50) pin=models.IntegerField() def __str__(self): return self.fname views.py def adminp(request): if 'form_rejected' in request.POST and request.method=="POST": print("Went into reject") p=booking.objects.filter(id=request.POST.get('object_id','')).delete() print(p) elif 'form_approved' in request.POST and request.method=="POST": print("went in approve") fname= booking.objects.filter(fname=request.POST.get('object_fname','')).values_list('fname') lname= booking.objects.filter(lname=request.POST.get('object_lname','')).values_list('lname') email= booking.objects.filter(email=request.POST.get('object_email','')).values_list('email') city= booking.objects.filter(city=request.POST.get('object_city','')).values_list('city') state= booking.objects.filter(state=request.POST.get('object_state','')).values_list('state') pin= booking.objects.filter(pin=request.POST.get('object_pin','')).values_list('pin') app= approved(fname=fname,lname=lname,email=email,city=city,state=state,pin=pin) app.save() print(fname,pin) x=booking.objects.all() params={'pro': x} return render(request,'dbms/adminpanel.html',params) template <form action="" method="POST"> {% csrf_token %} <div class="col"><p>Firstname: {{i.fname}}</p></div> <div class="col"><p>Lastname: {{i.lname}}</p></div> <div class="col"><p>Email: {{i.email}}</p></div> <div class="col"><p>City: {{i.city}}</p></div> <div class="col"><p>Pin: {{i.pin}}</p></div> <input type="hidden" name="object_fname" value="{{ i.fname }}"> <input type="hidden" name="object_lname" value="{{ i.lname }}"> <input type="hidden" name="object_email" value="{{ i.email }}"> <input type="hidden" name="object_city" value="{{ i.city }}"> <input type="hidden" name="object_state" value="{{ i.state }}"> <input type="hidden" name="object_pin" value="{{ i.pin }}"> <input class="btn btn-success mx-2" name="form_approved" type="submit" value="Approve"> <input type="hidden" name="object_id" value="{{ i.id }}"> <input class="btn btn-danger mx-2" name="form_rejected" type="submit" value="Reject"> <!--Added attribute name="form_rejected"--> OUTPUT after printing output of fname and pin: went in approve <QuerySet [('snaTYE',)]> <QuerySet [(939393,)]> when I print fname just to check it gives me a queryset which can't be inserted, so how do either insert the following in approved database or … -
NoReverseMatch in url pattern-data is in tuple form
django url pattern not recognized due to tuple entry i want to put a hyperlink in html code to redirect to a page with sending a data with it. hyperlink path is dynamic so i used {% url "check" book.id %} in html code. book.id gives correct data but it appers in tuple format ('12',) when i call perticular page by writing static url like http://127.0.0.1:8000/check/12/ it works fine "check" as view area and 12 as argument passed how to use a dynamic path views.py def add(request): book = Readdata.objects.all() return render(request, 'result.html', {'books': book}) def check(request,id): return render(request,'result.html',{'result': id}) urls.py urlpatterns = [ url('add', views.add, name='add'), url(r'^check/(\d+)/$', views.check, name="delete_book"), url(r'^check', views.check, name="check"), url('', views.index, name="index") ] html <a href="{% url 'check' book.age %}">click </a> not working <a href="http://127.0.0.1:8000/check/21/">click </a> working error- Reverse for 'check' with arguments '(21,)' not found. 1 pattern(s) tried: ['check'] -
Logging cron jobs in Django
I would like to log all cron job errors into a database table. Is it a good idea to log errors into a db table and what would you suggest me to do? Is it possible to do it with built-in logging module? P.s. I am using python 2.7 and django 1.11 (Yea, I know I should migrate to Py3 and Django 2 :D) -
How to build full url of object in django template using `obj.get_absolute_url'?
I am trying to feed "sharethis" data-url with the full url (domain + absolute_url) of the object. Currently, I am doing this in django template: <div class="sharethis-inline-share-buttons" data-url="http://www.my-domain.com{{program.get_absolute_url}}"></div> However, I want a better method to get this part: http://www.my-domain.com The reason I am looking for this is that the first method does not return a relevant url in development using localhost. it would return, as an example, this (fictional) url: http://www.my-domain.com/objects/object_slug-object_pk/ while I expect this: 127.0.0.1.com:8000/objects/object_slug-object_pk/ -
Как реализовать посекундное обновление страницы в django
Мне нужно реализовать посекундное обновление страницы, для обновления графика, без подтверждения пользователем. Есть идеи? Что я имею: все встало на моменте рекурсии, решил реализовать пока что проверку посекундного обновления. Ранее сталкивался с проблемой рекурсии тэмплейтов, но успешно нашел обходной путь, но сейчас, к сожалению не вижу его. Изначально пытался реализовать на js, но там спрашивают подтверждение обновления страницы, что при отрисовке графика каждую секунду меня не устраивает. Да можно было воспользоваться более сложными графиками, а не google charts, но это тоже меня не устраивает, так как мой уровень знания js не очень то хорош. PYTHON from django.shortcuts import render from django.views.generic.edit import FormView from django.contrib.auth.forms import UserCreationForm from django.shortcuts import redirect from django.http import HttpResponseRedirect from django.urls import reverse from .models import Profile from .models import Profile2 from .forms import forma from .forms import forma0 from math import sqrt import time ... def ac1 (request,category): # материнская функция к timerecus понадобиться дальше idc=decode(category) pf= Profile2.objects.get(id=idc) time=0 timerecus(request,time) ... def timerecus(request,timer): time.sleep(1) if(timer<=60): timer=timer+1 return HttpResponseRedirect(reverse('timerecus',args=(request,timer))) return render(request,'ac1.html',context={'num':timer}) HTML <meta charset="utf-8" /> <title>lichkab</title> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {packages: ['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['time', 'action'], ['1', 378.280], ['2', 378.260], ['3', 378.320], ['4', 378.320] ]); var …