Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Name error context not defined in class based view
I'm very confused by this but it does appear to be my issue. I am getting a name error for context here: class ProjectView(ListView): template_name = 'project_portal/home.html' queryset = Project.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # <-- name error here context['update_category'] = UpdateCategory.objects.all() context['update'] = Update.objects.all() return context What am I doing wrong here? I thought that: context = super().get_context_data(**kwargs) was the definition? -
How to do unit testing properly in django?
Here i am trying to do a testing for the add_course function and i write the test code as below but it failed.This is the first unit testing i have done with django so any help would be great. I got this when i run python manage.py test AssertionError: 404 != 200 ---------------------------------------------------------------------- Ran 1 test in 0.077s FAILED (failures=1) Destroying test database for alias 'default'... Is there any problem with my view or test file. views.py def add_course(request): if request.method == 'POST': form = AddCourseForm(request.POST or None) if form.is_valid(): course = form.save() course.save() messages.success(request, 'course with title {} added.'.format(course.title)) return redirect('view_course') else: form = AddCourseForm() return render(request, 'add_course.html', {'form': form}) test.py import unittest from django.test import Client class AddCourseTest(unittest.TestCase): def setUp(self): self.client = Client() def test_details(self): response = self.client.post('/add-course/') self.assertEqual(response.status_code,200) -
Fullcalendar in Django: TemplateDoesNotExist
I have downloaded the FullCalendar library from FullCalendar and installed it. Views.py def event(request): all_events = Events.objects.all() get_event_types = Events.objects.only('event_type') # if filters applied then get parameter and filter based on condition else return object if request.GET: event_arr = [] if request.GET.get('event_type') == "all": all_events = Events.objects.all() else: all_events = Events.objects.filter(event_type__icontains=request.GET.get('event_type')) for i in all_events: event_sub_arr = {} event_sub_arr['title'] = i.event_name start_date = datetime.datetime.strptime(str(i.start_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d") end_date = datetime.datetime.strptime(str(i.end_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d") event_sub_arr['start'] = start_date event_sub_arr['end'] = end_date event_arr.append(event_sub_arr) return HttpResponse(json.dumps(event_arr)) context = { "events":all_events, "get_event_types":get_event_types, } return render(request,'classroom/teachers/event.html',context) Urls.py path('calendar', teachers.event, name='calendar'), event.html {% extends 'base.html' %} {% load fullcalendar_tags %} {% block content %} {% calendar %} {% endblock %} <script> $(document).ready(function() { $('#calendar').fullCalendar({ defaultDate: '2016-07-19', editable: true, eventLimit: true, // allow "more" link when too many events events: [ {% for i in events %} { title: "{{ i.event_name}}", start: '{{ i.start_date|date:"Y-m-d" }}', end: '{{ i.end_date|date:"Y-m-d" }}', }, {% endfor %} ] }); }); </script> </html> When I try to run it, I get the error: TemplateDoesNotExist at /shipper/calendar fullcalendar/calendar.html I am doing everything it says in the related question. But something is going wrong. Please Help -
How to fix "Django test setUp() function not creating the django users"?
I am doing the django test cases. Now I have a problem that, user created in django test is not shown in the database created for test. consider my database name as db. from django.contrib.auth.models import User,AnonymousUser from django.test import TestCase,LiveServerTestCase from django.db import connection class machinelist(TestCase): def setUp(self): self.user=User.objects.create_user(username="vishnu***",email="vishnu@clartrum.com",password="vishnu@12345") print self.user.username db_name = connection.settings_dict['NAME'] print db_name t=raw_input("PAUSE") def tearDown(self): print 'd' def test1(self):#view function print "2" The output will print the username vishnu*** and db_name as test_db. But when you observe the database, there is no data. In the code, when the raw_input is executed, I will sign into the mysql server and verified that test_db is created successfully and also the django's tables. But when i checked auth_user table there is no data in it. I am using django 1.11.20 and mysql 5.6.33. Why User is not updating on the database table? -
How can I refresh the queryset when using the browser's "back button?"
I'm using django to build a simple website and in part of it a message can be clicked on and marked as read which also pulls up a detail page with the message title and body. When I press the back button, however, it still leaves it as unread until I refresh the page. I've checked the sqlite file and it does show it as read already (I'm using a simple boolean field), but it doesn't on the page until it's refreshed. I have tried refreshing the page to make sure that the field has the correct value, but I'm not sure where to go from here. The section of my code that takes the user to the message detail page is as follows: def messages(request): user = request.user sent_messages = Message.objects.filter(sender=user.id) unread_messages = Message.objects.filter(recipient=user.id, read=0) read_messages = Message.objects.filter(recipient=user.id, read=1) context = { 'sent_messages': sent_messages, 'unread_messages': unread_messages, 'read_messages': read_messages, } return render(request, 'messenger/messages.html', context) It should automatically send the message to the unread section on the page, but it won't do that unless the page is explicitly reloaded. -
How to return List of QuerySets in graphql query as separate list elements?
The problem I am facing is that I have custom_filter of MyModel which return the list of <QuerySet> like [<QuerySet [<MyModel: xyz>]>, <QuerySet [<MyModel: xyz>, <MyModel: xyz>,<MyModel: xyz>]>] The object type class MyModelNode(DjangoObjectType): class Meta: model=MyModel filter_fields=['id] interfaces = (graphene.relay.Node,) Query class Query(graphene.ObjectType): my_model_items = graphene.List(MyModelNode) def resolve_my_model_items(self, info, **kwargs): my_model_filtered_items = MyModel.objects.custom_filter(kwargs) # my_model_filtered_items holds the list of querysets return my_model_filtered_items How to handle list of querysets. The graphql respone of the query should give a list which have the querysets as elements. [ { //These are from first <QuerySet> "myModelItems":[ { "fieldsIaskedFor":"response" } ] }, { //These are from second <QuerySet> "myModelItems":[ { "fieldsIaskedFor":"resp" }, { "fieldsIaskedFor":"resp" }, { "fieldsIaskedFor":"resp" }, ] }, ] How to get results of different querysets in separate list elements ? The number of <QuerySet> are not fixed. What I have to do to achieve that ?. -
How do I keep one portion of the query string in the URL when going to another page using Django?
I'm creating a web app that does web crawling using Django. After clicking a button the crawling would start. After the crawling process is done, I would get a query string like this ?conditions=cancer&geolocation=&startdate=2019-05-10&enddate=2019-05-11&max=100 I would like to know how can I get the button to auto redirect to the next page while keeping the query string in the URL intact? Preferably without any new packages or new coding language if possible. At the moment, i'm using two buttons one for crawling and one to bring the user to the next page but this method doesn't keep the query string in the URL intact. Thanks! I have tried adding action="/view" into form in crawl.html, however it would just immediately direct the user to the next page and stop the crawling process. Button onclick does the same thing as well. It brings the user to the next page and cuts short the crawling process. in views.py class testcrawl(TemplateView): template_name = 'crawl.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # crawl codes return tweets in crawl.html <form method="GET"> //multiple input fields (not using django forms) <button type="submit" class="btn btn-primary" id="searched">Search</button> -
How can we include datatable inside django admin with search box for retrieving and editing model data
I'm building a website using Django it is my first web site using Django, I want to how I can include datatable inside Django admin with a search box for searching the data from the model. -
Django:How do I put the initial data into the database before Migrate?
Added models from existing code. I'd like to put in the initial data when I migrate the models I've added. python3 -m pip install sqlparse python3 manage.py makeemigations sbimage //I have edited the generated 0002 file. python3 manage.py Migrate image 0002 //Normal operation confirmed. python3 manage.py sqlmigrate thimage 0002 //Normal operation confirmed. However, the data did not enter the table when the database was verified. from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sbimage', '0001_initial'), ] operations = [ migrations.CreateModel( name='AuthNumberR', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('auth_number_r', models.CharField(max_length=64)), ], ), migrations.RunSQL("INSERT INTO WarningStateList (id, warning) VALUES (1, 'aaaaaaaaaaaaaaa');"), ] -
Django: Adding databases to DATABASES after startup
So this is ultimately a multi tenancy question about adding new databases for new tenants after the server has started. If i have an array of nodes behind a load balancer, i don't want to have to restart each one after a new tenant is created. Is there a proper dynamic way to add databases that django can use without having to restart the server? Thanks -
No module named '_contextvars' in Python3.7 virtual environment
I'm working on a Django project which requires Python3.7 virtual environment. So I created a virtual env and installed all the requirements in it and verified it, activated it. But when I try to run the django server using runserver it is giving me below error. Traceback (most recent call last): File "/usr/lib/python3.7/decimal.py", line 3, in from _decimal import * ModuleNotFoundError: No module named '_decimal' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./interfaces/control/manage.py", line 8, in <module> execute_from_command_line(sys.argv) File "/home/ntamarada/Nagarjuna/dbssvenv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/ntamarada/Nagarjuna/dbssvenv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ntamarada/Nagarjuna/dbssvenv/lib/python3.7/site-packages/django/core/management/__init__.py", line 224, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/ntamarada/Nagarjuna/dbssvenv/lib/python3.7/site-packages/django/core/management/__init__.py", line 36, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/home/ntamarada/Nagarjuna/dbssvenv/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/ntamarada/Nagarjuna/dbssvenv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 10, in <module> from django.core.servers.basehttp import ( File "/home/ntamarada/Nagarjuna/dbssvenv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 17, in <module> from django.core.handlers.wsgi import LimitedStream File "/home/ntamarada/Nagarjuna/dbssvenv/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 8, in <module> … -
Django allauth custom registration view call from inside the application
I'm using Django 2.2 and django-allauth for handling login and registration along with django-rest-auth to enable authentication via API using django-allauth library. For handling the registration, I have written a custom view class CustomRegisterView(generics.CreateAPIView): serializer_class = RegisterSerializer permission_classes = register_permission_classes() @sensitive_post_parameters_m def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_response_data(self, user): if allauth_settings.EMAIL_VERIFICATION == allauth_settings.EmailVerificationMethod.MANDATORY: return {"detail": _("Verification e-mail sent.")} return {"detail": _("Registration successful")} def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(self.get_response_data(user), status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): user = serializer.save(request=self.request) complete_signup(self.request, user, allauth_settings.EMAIL_VERIFICATION, None) return user This handles all registration flow, verification, send signals, etc. Now I want to create a user account manually from some other parts (views) of the application. Is it possible to use **CustomRegisterView class to create an account?** I just pass the fields required and the user is registered. -
How to paginate multiple objects separately in one view?
i have 3 objects subs, post and mine. At any point in time one will be shown and the other 2 will be hidden. How can i paginate all 3 separately? i have seen similar problems where chain has solved the problem. However, in my case i do not want to merge these 3 together so that i can chose which one to show in my html based on a button. my class based view class SubListView(ListView): model = Post template_name = 'store/sub_home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 12 def get(self, request): if request.user.is_authenticated: paginate_by = 12 post = Post.objects.all().order_by('-date_posted') users = User.objects.exclude(id=request.user.id) sub = Subscriber.objects.get(current_user=request.user) subs = sub.users.all() my_content = Post.objects.filter(author=request.user.id) args={ 'posts':post, 'users':users, 'subs':subs, 'mine':my_content } return render(request, self.template_name, args) else: post = Post.objects.all().order_by('-date_posted') paginate_by = 12 args={ 'posts':post, } return render(request, self.template_name, args) This is my html: {% extends "store/base.html" %} {% block content %} <div class="panel"> <!-- <a href="{% url 'store-home'%}"> --> <button class="Active" id="random_link" onclick="show('random'); return true;"> <img src="/static/store/random.gif" alt=""> Random Finds </button> {% if user.is_authenticated %} <button id="subscription_link" onclick="show('subscription'); return true;"> {% else %} <a href="{% url 'login' %}"> {% endif %} <img src="/static/store/Subscription.gif" alt=""> My Subscription </button> {% … -
Django Error 'NoneType' object has no attribute '_meta'
I am trying to build a community page that has both a form for posting a new post and a list of all the previous posts, similar to facebook. But now I keep getting the error 'NoneType' object has no attribute '_meta' This is my view function: def community(request): if redirect_if_false_choice(request): return redirect_if_false_choice(request) posts = CommunityPost.objects.filter(public=True).order_by('date_posted') form = PostForm(request.POST or None) if str(request.method) == 'GET': return render(request, 'officer/community.html', {'posts': posts, 'form': form}) if form.is_valid(): form.save() return redirect('community') And this is the form: class PostForm(forms.ModelForm): class Meta: model = CommunityPost fields = ('content', ) widgets = { 'content': forms.Textarea(attrs={'rows': 4, 'placeholder': "What's going on?"}) } -
How can I deploy an Electron app served by a local Django server?
I'm creating an electron app, which upon start spawns a local Django server child process (to serve as backend processing). In my development environment, the electron app runs properly when I run npm start Although, when trying to deploy my application with electron-packager . The executable does not start the Django server. When I view the contents of the resources/app directory, created by the electron packager, I see the virtualenv and all the Django dependencies are present. Why doesn't my packaged application start the local server as my development environment does? My package.json: { "name": "AppName", "version": "1.0.0", "description": "", "main": "main.js", "scripts": { "start": "electron .", "dist": "build" }, "author": "AuthorName", "license": "CC0-1.0", "devDependencies": { "electron-packager": "^14.0.1" }, "dependencies": { "electron": "^5.0.6" } } My main.js: // Run local Django server var ChildProcess = require('child_process'); var DjangoServer = ChildProcess.spawn('python', ['run_server.py']); const {app, BrowserWindow} = require('electron') const path = require('path') let mainWindow function createWindow () { mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js') } }) // Load local host served by Django mainWindow.loadFile('https://localhost:8000') mainWindow.setMenuBarVisibility(false) mainWindow.on('closed', function () { mainWindow = null }) } app.on('ready', createWindow) app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() … -
Django Featching Data From DataBase Based on join Using ORM
I want to join two modes as shown in bellow and the join should be in Harsha to Bank only(not Bank to Harsha) model.py class Harsha(models.Model): name = models.CharField(max_length=255) email = models.CharField(max_length=255) class Bank(models.Model): user = models.ForeignKey(Harsha, on_delete=models.CASCADE) accountnumber = models.BigIntegerField() ifsc = models.CharField(max_length=255) branch = models.CharField(max_length=255) bank = models.CharField(max_length=255) views.py test = Harsha.objects.all() test1 = Bank.objects.all() # its working for me but i want join from Harsha table in templates # i want this {% for tes in test %} {{ tes.name }} {{ tes.email }} {{ tes.bank.accountnumber }} # how can i get this filelds {{ tes.bank.ifsc }} # how can i get this filelds {% endfor %} # its working {% for tes in test1 %} {{ tes.user.name }} {{ tes.user.email }} {{ tes.accountnumber }} {{ tes.ifsc }} {% endfor %} -
how to use trained model of machine learning in web application
Here what i get after my model is train how to integrate trained model to the production code. (I'm using django framework) -
Pass json String into a Model in Django
I am new to Django so please bear with me if my question sounds trivial. I have an item_json string which I am able to pass into a model in Django. However, what I would really want to do is parse the json string and pass the elements of the string into different fields in my model. Please let me know how to do this. My json string looks like this: { "pr5": [2,"<b>Product Item</b>",13,15] } where pr5 represents the product id, 2 represents the items purchased, Product Item represents the name of the product, 13 represents the stock remaining and 15 represents the price. My model looks like this: class Order(models.Model): order_id = models.AutoField(primary_key=True) items_json = models.CharField(max_length=5000) amount = models.DecimalField(max_digits = 10, decimal_places=2, default= 0) name = models.CharField(max_length = 90) mob = models.CharField(max_length = 30) apartment = models.CharField(max_length = 50) Please help me. Thanks in advance. -
Queryset taking too much time
I have too calculate some values for 3000 items from database. On selecting item from selectbox, fields should be filled by jquery. I am iterating each item, sending it into an dictionary (item name as key and tuple of variables as value) and passing this dictionary to django template. I am sending auto_dict dictionary in template. Every time user select value from select box, on change function, I iterate the dictionary and get the values. class Sales(models.Model): # sales detail of items item_id = models.ForeignKey('Item', models.DO_NOTHING) # some more fields class Item(models.Model): # detail of items, around 3000 items name = models.CharField(max_length=127) # some more fields class Order(models.Model): # order detail of each order order_number = models.CharField(max_length=63, unique=True) created_at = models.DateField(auto_now_add=True) status = models.CharField(max_length=2, choices=STATUS, blank=True, null=True, default='NP') final_approval = models.CharField(max_length=3,default='No') order_type = models.CharField(max_length=2, blank=True, null=True, choices=ORDER_TYPE) # some more fields class Orderitems(models.Model): # item detail for all order qty = models.IntegerField() item_id = models.ForeignKey(Item, models.DO_NOTHING, blank=True, null=True) order_id = models.ForeignKey(Order, models.DO_NOTHING, blank=True, null=True) sales_id = models.ForeignKey(Sales, models.DO_NOTHING, blank=True, null=True) # some more fields ----Calculations----- def get_detail(): item_table = OrderItemTable.objects.all() order_item_table = OrderOrderitemsTable.objects.filter(Q(order_id__order_type='NO') & Q( order_id__final_approval='Yes')).select_related('order_id', 'item_id') auto_dict = {} for item in item_table: # -------------------------------------------Previous Total Order------------------------------ previous_total_order_q = … -
How to generate a google-calendar-like schedule by using element-ui calendar
I am doing a page by using Django. One of the requirements is rendering a schedule page by using element-ui calender module. For example, the backand provide several date_plans data (Date type) as a list. I want to render these date datas in the designated cell in the calendar page by change the cell backgroud into different color. I come accross barries at this point The calendar page have already rendered <div id="app"> <el-calendar> <template slot="dateCell" slot-scope="{date, data}"> <p>hhhh</p> </template> </el-calendar> </div> <script> var calendar = new Vue({ el:'#app', data:{ value:new Date(), } }) </script> def calendar(request): _,c,_ = login_profile(request) plans_recent = c.interaction_summary().get('plans_recent','') return render(request, 'crm/calendar.html', { 'dates':[p.date_plan for p in plans_recent], }) the plans_recent returns a queryset inside which the object contains the date_plan and other field I expect: for example, the dates list is [2019-9-27, 2019-10-09,....]. the cell of the date in the list rendered by element-ui calendar have a different background color ''' -
Automatically restart django apps on system reboot
Is there a way to restart django apps automatically on system restart in pm2? Till now for django apps I found that I have to manually restart django apps. -
How to transfer data from one page to another?
There is a site, in a certain part of this site, the names of the downloaded Word files are displayed, and below it there is a button for moving to 2 pages. There is also a second page, there is a field in it. Question number 1: how to click to make the list of these documents displayed in the 2 page field? Question number 2: how to display the automatic numbering of documents? Tell me what to use? How to do it? In the second, I thought of using counters. -
Why do I get empty django querysets when using ThreadPoolExecutor with pytest-django?
I have been trying to track down some bugs in some concurrent code and wanted to write a test that ran a function in parallel. I am using Django with postgres as my database and testing using pytest and pytest-django. To run my function, I am using ThreadPoolExecutor and simply querying my database and returning a count of objects. Here is the test in the django shell working as expected: >>> from concurrent.futures import * >>> def count_accounts(): ... return Account.objects.all().count() ... >>> count_accounts() 2 >>> with ThreadPoolExecutor(max_workers=1) as e: ... future = e.submit(count_accounts) ... >>> for f in as_completed([future]): ... print(f.result()) ... 2 However, when I run this as a test under pytest, it appears like the function in the thread returns empty querysets: def test_count_accounts(): def count_accounts(): return Account.objects.all().count() initial_result = count_accounts() # 2 with ThreadPoolExecutor(max_workers=1) as e: future = e.submit(count_accounts) for f in as_completed([future]): assert f.result() == initial_result # 0 != 2 Is there anyway I can get the call inside the thread to return the correct value/access the db correctly? -
Can you use react to create dynamic email templates to be sent with django
If I want to use React to create email templates and manage my drip email campaign in Django. Is there a way to do this? Do I have to resort to using Django templating? -
Convert SQL Query to ORM Query
Here is SQL Query: select a.ur_id ur_id, c.ug_id ug_id, d.ui_mailid ui_mailid, d.ui_firstname ui_firstname, d.ui_lastname ui_lastname from user a LEFT OUTER JOIN user_groupmember b ON a.ur_id = b.ug_userid LEFT OUTER JOIN user_group c ON c.ug_id = b.ug_userid LEFT OUTER JOIN user_info d ON d.ui_id = a.ur_id where a.ur_mailid = 'test@test.com' I need to convert it in ORM Query. Is there any way to achieve it without using raw SQL? Any help is appreciated