Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Using javascript or python regular expressions I want to determine if the number is 1-99 how to make it?
var category = prompt("where do you go? (1~99)", ""); hello Using regular expressions I want to determine if the category is 1-99. How can I solve it? Thank you if you let me know. -
How to populate the form with value from current page?
I am learning to build a Post-comment app on Django. I understand how and why the current user can be assigned as author in the Comment form. But I do not understand how the post_id can be assigned to connect the comment with a particular post. Tried using various methods obtained from searching the web. I keep getting various errors- TypeError, KeyError, ValueError etc. My models.py is set up like this: class Post(models.Model): pid = models.AutoField(primary_key=True) title = models.CharField(max_length=1000) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog-home')#, kwargs={'pk':self.pk}) class Comment(models.Model): cid = models.AutoField(primary_key=True) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) comment = models.TextField() comment_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.comment def get_absolute_url(self): return reverse('blog-home') def save(self, *args, **kwargs): super(Comment, self).save(*args, **kwargs) The views.py with the comment create view is as follows: class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['comment'] def form_valid(self, form,**kwargs): form.instance.author = self.request.user form.instance.post_id = self.kwargs['post_id'] # IS THE ABOVE LINE CORRECT? return super().form_valid(form) The Answer button is on the home page included in every post block. The html for the same with the url for it is as below: {% extends "blog/base.html" %} {% block … -
how to implement form based cart/basket in django where you select the items from form based ui without any image?
Once you select the items from form and click on add to cart it should take you to checkout the cart, do payment and close the transaction. -
How to create the list of users who enter the page?
I'm new into Django and as the training I decided to create a blog application. But I have a one problem. I don't know how to create a view where I will can see which users saw this post. It can be simple, only user nick and date. -
I get a MissingSchema error within my python file that is trying to read a local JSON file
This is the error I get when I try to load my indexes.html page: MissingSchema at /indexes/ Invalid URL "<_io.TextIOWrapper name='tableInfo.json' mode='r' encoding='cp1252'>": No schema supplied. Perhaps you meant http://<_io.TextIOWrapper name='tableInfo.json' mode='r' encoding='cp1252'>? I am not sure why this is happening, I am trying to read from a local JSON file and display it in a table This is my views.py code: def indexes(request): with open('tableInfo.json') as json_file: if request.POST: form = Sea(request.POST) po = request.POST.get('poNo') dc = request.POST.get('dcNo') vendor = request.POST.get('vendor') order_date = request.POST.get('order_date') delivery_date = request.POST.get('delivery_date') payload = {} if len(po) > 8: payload['poNo'] = po if "DC" in dc: payload['dcNo'] = dc if len(vendor) > 8: payload['vendorNo'] = vendor if len(order_date) > 6: payload['orderDate'] = order_date if len(delivery_date) > 6: payload['deliveryDate'] = delivery_date data = json.loads((requests.get(json_file, payload)).content) if data['returnCode'] == 0: resultList = data['resultList'] else: resultList = [] else: form = Sea() resultList = [] context = { 'data': resultList, 'form': form } return render(request, 'users/indexes.html', context) -
How to get urls and views correct with this code
Hey guys I'm trying to set up my chatterbot to work with Django but for some reason I can't seem to get the urls and views correct for Django to show the chatbot on my server. Django 2.1.1 is the version I'm running on with Python 3.7 as my interpreter. My chatbot is in the same project in a folder called Sili with it's own views.py and urls.py in that folder. I have tried this but no luck from django.contrib import admin from sili import views urlpatterns = [ path('admin/', admin.site.urls), path('', home.views), ] this is what is in my views.py from django.shortcuts import render,render_to_response from django.http import HttpResponse import json from django.views.decorators.csrf import csrf_exempt from chatterbot import ChatBot # from chatterbot.trainers import ChatterBotCorpusTrainer chatbot=ChatBot('Sili',trainer='chatterbot.trainers.ChatterBotCorpusTrainer') # Train based on the english corpus chatbot.train("chatterbot.corpus.english") @csrf_exempt def get_response(request): response = {'status': None} if request.method == 'POST': data = json.loads(request.body) message = data['message'] chat_response = chatbot.get_response(message).text response['message'] = {'text': chat_response, 'user': False, 'chat_bot': True} response['status'] = 'ok' else: response['error'] = 'no post data found' return HttpResponse( json.dumps(response), content_type="application/json" ) def home(request, template_name="home.html"): context = {'title': 'Sili Chatbot Version 1.0'} return render_to_response(template_name, context) what do I add to the urls.py so that it shows … -
Override default templates in Django admin site
I'd like to override some of the django admin templates found in django/contrib/admin/templates/admin. I would just like to get rid of some unnecessary parts in some templates. I'd like to do so without copying and pasting the templates, minus the parts I don't want, into the templates/admin/my_app/ directory like they mention here https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#overriding-admin-templates. Is there any way other approach to this? -
Keep getting "IntegrityError FOREIGN KEY constraint failed" when i am trying to delete a post
Every time i try to delete a post i keeping getting this error, but my delete button use to work before. I think it has something to do with the on_delete attribute but i changed its value a few times and it still did not work. //models.py from django.db import models from django.conf import settings from django.urls import reverse User = settings.AUTH_USER_MODEL class PostManager(models.Manager): def search(self, query): qs = self.get_queryset().filter(title__icontains=query) if qs: return qs return None def get_by_id(self, id): qs = self.get_queryset().filter(id=id) if qs.count() == 1: return qs.first() else: return None # Create your models here. class PostModel(models.Model): user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) title = models.CharField(max_length=50) message = models.TextField() date = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, blank=True, related_name='post_likes') def __str__(self): return self.title objects = PostManager() def get_total_likes(self): return self.likes.count() def get_absolute_url(self): return reverse("birdpost:detail", kwargs={"id": self.id}) def get_like_url(self): return reverse("birdpost:like-toggle", kwargs={"id": self.id}) def get_delete_url(self): return reverse("birdpost:delete_post", kwargs={"id": self.id}) //views.py def del_post(request, id): obj = get_object_or_404(PostModel, id=id) if request.user != obj.user: print("Ooh no looks like this post is not yours... ") else: obj.delete() return redirect("home") -
How can i combine two ModelForms in a single django views
Goodday everyone, so i have two models, one of which has a foreignkey field pointing to the other and i have model forms for each model class and in my views.py, i would like to make the model with the foreignkey point at the other model i made a modelforms (CharacterForm and RoleForm) in my forms.py which would show all fields but in my html, i would hide the player field (a foreignkey which points to the other model) so in my views.py i would automatically make the newly created character the player. models.py class Character(models.Model): #some fields class Role(models.Model): player = models.ForeignKey(Character, on_delete=models.PROTECT, related_name='the_player') views.py def NewRole(request): if request.method == 'POST' form = CharacterForm() formset = RoleForm() if all([form.is_valid, formset.is_valid]): role_player = form.save() formset.player = role_player formset.save() return redirect('index') else: form = CharacterForm() formset = RoleForm() return render(request, 'new_role.html', {'form':form, 'formset':formset}) i just wanted the player field under the role model to point at the Character model the user just created and i dont know the best way to do it. i thought this would work but i keep getting ForeignKey Constraint error. -
How to populate my django database with json that I scraped from a website
I have scraped data from a website using their API on a Django application. The data is JSON (a Python dictionary when I retrieve it on my end). The data has many, many fields. I want to store them in a database. I need to use their fields to create the structure of my database. Any help on this issue or on how to tackle it would be greatly appreciated. I apologize if my question is not concise enough, please let me know if there is anything I need to specify. I have seen many, many people saying to just populate it, such as this example How to populate a Django sqlite3 database. The issue is, there are so many fields that I cannot go and actually create the django model fields myself. From what I have read, it seems like I may be able to use serializers.ModelSerializer, although that seems to just populate a pre-existing db with already defined model.