Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add specific permission view to certain users based on their field in Django?
So basically i have to make sure Users that are from the same department field to view and create any datas in the database. Not sure how to apply it using field-based user permissions? class Profile(AbstractUser): class Meta: verbose_name_plural = 'Profiles' company = models.CharField(max_length=30, null=True) contact = models.CharField(max_length=20, null=True) branch = models.ForeignKey('generals.Branch', on_delete=models.CASCADE) department = models.ForeignKey('generals.Department', on_delete=models.CASCADE) created_by = models.CharField(max_length=20) modify_by = models.CharField(max_length=20) modify_date = models.DateTimeField(default=datetime.now, blank=True) is_active = models.BooleanField(default=False, null=True, blank=True) is_superuser = models.BooleanField(default=False, null=True, blank=True) is_staff = models.BooleanField(default=False, null=True, blank=True) def __str__(self): return self.username -
bootstrap datepicker not working in django
i am trying to integrate bootstrap datepicker but its not working setting.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main_site', 'crispy_forms', 'bootstrap_datepicker_plus', 'bootstrap4' ] forms.py: from django import forms import datetime from bootstrap_datepicker_plus import DatePickerInput class BookartistForm(forms.Form): name = forms.CharField() email = forms.EmailField(label = 'email', required=False) number = forms.CharField(required=False) artist_name = forms.CharField(required=False) artist_category = forms.ChoiceField(choices = [('singer','Singer'),('dancer','Dancer'),('comedian','Comedian'),('model','Model'),('celebrities','Celebrities'),('photographer','Photographer')]) #Event_Type = forms.ChoiceField( choices = [('question','Question'),('other','Other')]) budget = forms.CharField(required=False) date = forms.DateField(widget=DatePickerInput(format='%m/%d/%Y')) location = forms.CharField(required=False) description = forms.CharField(widget = forms.Textarea, required=False) html template: {% extends 'main_site/base.html' %} {% load static %} {% block content %} {% load crispy_forms_tags %} {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} <div class="container"> <section> <form method = 'post'> {% csrf_token %} {{ form|crispy }} <button type="submit" class="bg bg-primary">Submit</button> </form> </section> {% endblock content%} also its unable to import on forms.py as i get error showing this: unable to import bootstrap datepicker_plus this is the output i'm getting -
Database multiple data not show in html file - django 2.1
i making a web page to get data from database and show in web page.i used .get() and it only get one data from database. and a tried .all() with many times. but can't show any data in html file. i need to get multiple data from database and show in web page here my code views.py from django.shortcuts import render from django.http import HttpResponse from .models import data # Create your views here. def index(request): return render(request, 'index.html') def about(request): return render(request, 'about.html') def postjob(request): data.objects.all() context = { "title": data.title, "jobType": data.jobType, "des": data.description, "jImg": data.jImg } return render(request, 'jobpost.html', context) models.py from django.db import models # Create your models here. class data(models.Model): title = models.TextField() jobType = models.TextField() description = models.TextField() jImg = models.ImageField(upload_to="media") urls.py from django.contrib import admin from django.urls import path from diligent.views import index, about, postjob from webDiligent import settings from django.contrib.staticfiles.urls import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', index, name='index'), path('about/', about, name='about'), path('jobpost/', postjob, name='postjob'), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) jobpost.html <div class="row"> {% for con in context %} <!-- single product --> <div class="col-lg-4 col-md-6"> <div class="single-product"> <img class="img-fluid" src="{{con.jImg.url}}" alt=""> <div class="product-details"> … -
DRF request.data has no attribute _mutable
I'm using Django 2.x and Django REST framework. I'm using django-oauth-toolkit to enable OAuth2 authentication and django-rest-auth for login and django-allauth for user registration. I want to generate access token in the response when a user is successfully registered. For that, I'm using a custom registration view. For that, I have created a function utils like def generate_token(request, user): # Get OAuth application to use application_: Application = Application.objects.filter( client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_PASSWORD ).first() if not application_: raise Exception('No OAuth2 Application is setup') auth_data = { 'username': user.username, 'password': password, 'grant_type': 'password', 'client_id': application_.client_id, 'client_secret': application_.client_secret } if request.data: mutable = request.data._mutable request.data._mutable = True request.data.update(auth_data) request.data._mutable = mutable if request.POST: mutable = request.POST._mutable request.POST._mutable = True request.POST.update(auth_data) request.POST._mutable = mutable return TokenView().create_token_response(request=request) When the endpoint is hit by Postman it works fine and request.data has _mutable attribute. But when it is hit by Angular application, it gives error 'dict' object has no attribute '_mutable' and the error points to mutable = request.data._mutable Why _mutable is missing for some requests? -
How to fix Expecting value: line 1 column 1 (char 0) error
After changing the url of my website from example1.com to example2.com I got the error of JSONDecodeError Expecting value: line 1 column 1 (char 0) Moreover, thinking that may the woocommerce key and secret caused the problem I changed them also, but the problem remains. Here is my code: def create_woocommerce_products_individually(wcapi,name,code,regular_price): data = { "name": name, "sku": code, "regular_price": str(regular_price), } wcapi.post("products", data).json() class ProductCreateView(LoginRequiredMixin, CreateView): model = Product form_class = ProductForm template_name='products/product_create_form.html' def form_valid(self, form): if self.request.method == 'POST': form = ProductForm(self.request.POST) if form.is_valid(): self.object = form.save(commit=False) name=self.object.description code=self.object.code wholesale_status=self.object.wholesale_status regular_price=self.object.retail_price wcapi=get_wcapi_b2b() create_woocommerce_products_individually(wcapi,name,code,regular_price) r=wcapi.get("products?filter[sku]='"+code+"'").json() post_id=r[0]['id'] self.object.pid=post_id self.object.save() else: form = ProductForm() return super(ProductCreateView, self).form_valid(form) My aim is to create a Product both in my db and woocommerce api, that's why I call the create_woocommerce_products_individually function. How can I fix this error and save properly? Here is the Traceback: Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/mixins.py" in dispatch 56. return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/edit.py" in post 217. … -
10 Applications streaming live locations
I am building a mobile application for forest touring users who need to stream their live locations to a real time web system so that they can be tracked for the entire time they are in the forest. Of course consent is to be granted and this has been taken care of. My problem is the design and how to put the pieces together. Below are some things I have figured out. I will use services library to get live location of the use user with the app installed and logged in. Lets say after every one minute. My backed server is based on Django. I am using REST APIs. I will use google maps to show the locations in the live web page. Questions: Should I keep the changing coordinates in the database? How do i live stream the changes in coordinate in the web page? -
Django celery unregistered task | relative imports
I'm trying implement periodic tasks in django app by using celery (v 4.3.0). My tasks.py looks like below: # forepy is the simple package created by me from forepy import Instrument from forepy import oanda_api from celery import shared_task @shared_task def sum_numbers(a, b): return a + b Problem is that celery worker returns error Received unregistered task of type 'fxsignal.tasks.sum_number'. I think that cause of problem is two import statements at the top of tasks.py (forepy imports). When I comment out those two lines my periodic task sum_numbers works correctly. For your reference, structure of forepy package is as below: forepy\ downloaders\ __init.py__ oanda_api.py __init__.py instruments.py utils.py And forepy's init.py: # -*- coding: utf-8 -*- """Top-level package for forepy.""" __author__ = """Elgin Jahangirov""" __email__ = 'cahangirove@gmail.com' __version__ = '0.2.0' from forepy.instrument import Instrument from forepy.downloaders import oanda_api __all__ = ['Instrument', 'oanda_api'] I've read this part of celery documentation and get rid of all . imports in my forepy package, but still problem exists. What can I do further to solve this problem? -
django.db.utils.OperationalError: (1698, "Access denied for user 'root'@'localhost'")
I m new to django I m learning how to connect django to mysql but I m getting error django.db.utils.OperationalError: (1698, "Access denied for user 'root'@'localhost'") my database is mysql user root database PyDjangoSQL2019 password nothing port 3306 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'PyDjangoSQL2019', 'USER': 'root', `enter code here` 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '3306' } } please help me what is problem and what I do? thanks -
How to add columns to some row of a table with reportlab?
I've been looking for an alternative for a few days but I can't find it. I paste a fragment of my code in which I generate a table with the questions and answers, most rows will have a single column, but in particular cases I need to show information in more than one column in the same row (it can be in 2, 3, 4, columns etc.) Is there any way to add columns to certain rows? o Specify the number of columns per row? Or another alternative. Of course, thanks for your help def answer_data(self, style): answers = [] style_bodytext = style['BodyText'] for a in self._answers: question = Paragraph(a['question_code'] + " - " + a['question'], style_bodytext) answer_paragraph = Paragraph(self.serializer_answer(a['answers']), style_bodytext) answers.append([ question ]) answers.append([ answer_paragraph ]) try: table_dependent = [] qs = [] aws = [] for d in a['dependent']: q = Paragraph(d['question_code'] + " - " + d['question'], style_bodytext) ans = Paragraph(self.serializer_answer(d['answers']), style_bodytext) qs.append(q) aws.append(ans) table_dependent.append(qs) table_dependent.append(aws) answers = answers + table_dependent except KeyError: pass table = Table(answers, colWidths=18 * cm) table.setStyle([ ("BOX", (0, 0), (-1, -1), 0.25, colors.black), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ]) for each in range(len(answers)): bg_color … -
Quickst Gmail api setup with djanogo
I try to send an email with my Django project and I like to use quickstart Gmail API instead of SMTP How can edit my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') -
How to prevent toast message on button click if form having a validation on some text field?
I used something similar to toast message in my html page, when i click on submit. It shows the message. But the problem is i have given some validation to some text field, if validation error occurs still it shows that toast message. How to prevent that? I tried to check the fields whether its null or not if its null, shows a message if not, shows successful and submit the form. <a class="white-button submit" id='test'>SUBMIT</a> $('#test').click(function () { var name=$('#con-name').val(); var email=$('#con-email').val(); var phone=$('#con-phone').val(); var address=$('#con-address').val(); var nation=$('#con-nation').val(); if(name!=""&&email!=""&&phone!=""&&address!=""&&nation!=""){ $(".success").click(function(){ toastr.success('Form submitted.', 'Success Alert', {timeOut: 5000}) }); $('form#feedback').submit(); } else{ $(".warning").click(function(){ toastr.warning('Fill the fields', 'Warning', {timeOut: 5000}) }); } }) What i want is toast message should be displayed only when form is submitted without any validation error. -
Does anyone have used BENEFIT Payment Gateway process
Have anyone used BENEFIT Payment gateway? How we can integrate it and use it in our script, I have searched it but didn't get the actual flow. -
how to pass parameters from views to the template in django?
i have a function that create object and i need to display the value on the template i know that i can pass the parameter in dictionary but it did not work and the template is empty. but if i print the value in the views it display the correct result. views.py def createFolder(request): if request.method == 'POST': FolderNum = request.POST['FolderNum'] print("folder number :",FolderNum ) dbFolder = testFolder.objects.create(folder_num = FolderNum) print("dbfolder = ", dbFolder.id) print("folder number after save====", dbFolder.folder_num) return render(request,'dropDown.html',{"dbFolder":dbFolder}) dropDown.html <h1> folder number is {{dbFolder.folder_num}}</h1> <h1> folder id is {{dbFolder.id}}</h1> -
Is it possible to connect a model object to a celery task?
I need to connect a celery task to a model objects. For example, I need to create an object of a model class AuthorPrice(models.Model): author = models.Charfield(default=0) price = models.FloatField(default=0) I have a task.py app = Celery() @app.task def create(): new = AuthorPrice.object.create() new.author = John new.price = 30 new.save() I call a task in view create.apply_async(eta.datetime(2019, 07, 31, 15, 56)) so far, everything is ok but, if i need to revoke or edit this task is possible to connect it at my model like a ForeignKey? ty -
Displayed haystack search result in template using result.field_name shows within square brackets issue
I'm able to display the search result using django haystack with solr as back end. But the issue is that the displayed values that has been indexed by search engine is been got displayed within the square brackets as in json eg : ['User name']. How to display this properly? search_indexes.py class ShowcaseSearch(indexes.SearchIndex,indexes.Indexable): text = indexes.EdgeNgramField(document=True,use_template=True) showcase_name = indexes.CharField(model_attr='showcase_name') created_date= indexes.CharField(model_attr='created_date') status = indexes.CharField(model_attr='status') created_by = indexes.CharField(model_attr='created_by') def get_model(self): return Showcase def index_queryset(self, using=None): qs=self.get_model().objects.exclude(status='P')\ .filter(is_active='Y') return qs showcase_text.txt {{object.showcase_name|safe}} {{object.created_date|safe}} {{object.reg_id.reg_name|safe}} search.html {% for result in object_list %} <tr> <td><a href="{% url 'showcase:showcase_applicant_view' pk=result.object.id %}">{{result.showcase_name}}</a></td> <td>{{result.created_date}}</td> <td>{{result.created_by}}</td> </tr> {% empty %} <p>No results found.</p> {% endfor %} Resulting slor index file { "id":"showcase.showcase.31", "django_ct":["showcase.showcase"], "django_id":[31], "text":["Test 52\nJuly 19, 2019, 6:58 p.m.\nInvestor"], "showcase_name":["Test 52"], "created_date":["2019-07-19T13:28:36.710Z"], "status":["N"], "created_by":["test_tt@abc.in"], "_version_":1640491605421981702}, I expect the result.showcase_name should display corresponding name Test 52, but instead it is displayed with in square brackets like ['Test 52']. Also please let me know how to get showcase id from text field of solr file, instead of retrieving from model instance using result.object.id. -
How to put an item in a context list that comes from related class?
In a View context field I want to show a new entry from related class. Context list uses some type of format that I can't comprehend, so I need some help. I have tried showing related information directly on the list, but I am missing attribute that should be provided to the template (I am talking about 'verbose_name') views.py: class UpdateSimple(UserPassesTestRaiseException, UpdateView): model = Subjects def get_context_data(self, **kwargs): context = super(UpdateSimple, self).get_context_data(**kwargs) context['readonly_fields'] = ['program', 'title', self.object.program.type] print(context['readonly_fields']) # For this I get: ['program', 'title', Fulltime] models.py: class Subjects(models.Model): title = models.CharField(max_length=160, verbose_name="Title") program = models.ForeignKey(Program, verbose_name="Program") def __str__(self): return self.title class Program(models.Model): title = models.CharField(max_length=160, verbose_name="Program") type = models.CharField(max_length=64, verbose_name='Type') def __str__(self): return self.title I want to get something similar in this part: context['readonly_fields'] = ['program', 'title', 'type'] print(context['readonly_fields']) # For this I want to get: ['program', 'title', 'type'] On the page it should show result: form.instance - verbose_name form.instance - value Program: program1 Title: subjectTitle1 Type: Fulltime -
'mkvirtualenv' is not recognized as an internal or external command, operable program or batch file
When I gave the following commands error occured. pip install virtualenv (WORKED) pip install virtualenvwrapper-win (WORKED) mkvirtualenv env2 (ERROR as follows) 'mkvirtualenv' is not recognized as an internal or external command, operable program or batch file. Can anyone provide me solution? -
DRF: What validation takes place when calling <model_instance>.save()?
I've read a lot of posts here in SO, and the more I read, the more confused I get. This came about from creating unitttests, where I often need to create an instance of a model, then change fields, and call instance.save(). But it's not just for unittests. For my multi-tenant site, there's a create_tenant() method (for example), which eventually calls create(). And when updating a tenant, some "save()" method is called, though it's not clear in my mind yet how, when, or which one is called. The first time I tried saving an instance in my unittests, the validations didn't run - my test was checking for raising a ValidationError, and I didn't get that assertion error. I then created a save() method in my model class and called self.full_clean(). That caused the validations to run, but I got this error: Traceback (most recent call last): File "/code/src/virticl_api/tenants/tests/test_models.py", line 110, in test_invalid_schema_names self.test_tenant.save() File "/code/src/virticl_api/tenants/models.py", line 230, in save self.full_clean() # Run validations File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 1152, in full_clean raise ValidationError(errors) django.core.exceptions.ValidationError: {'schema_name': ['This field cannot be blank.']} However, this didn't trigger the unittest assertion either because that is the wrong ValidationError. Note that it is: django.core.exceptions.ValidationError My test … -
How to fix broken link from Django MEDIA_ROOT?
I am attempting to show my image on website which is part of a postgresql DB which is connected to Django. I upload the file to the Django admin upload screen and have my model set up. However, I keep on getting a broken link for the picture. My images folder is also in the base directory of my project. I have tried to manipulate the root many times. I have also tried to use different images and types of images. settings.py MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url('', jobs.views.home, name='home'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) home.html <img src = "{{ job.image.url }}" class="card-img-top" > Am getting this get request "GET /media/images/22195497_10214668197162885_8935384055220872583_n.jpg HTTP/1.1" 200" Which is the correct image I want to show. -
Django 'pip install django-heroku'(psycopg2) error is blocking deployment to Heroku
I am setting up a new Django project to deploy on Heroku, however when I am following the Django Heroku deployment guide I come across an error during 'pip install django-heroku'. I am running on: OS: MacOS Mojave 10.14.6 virtualenv: python3 pip freeze output: (env) MacBook-Pro:testing_django sudoxx2$ pip freeze dj-database-url==0.5.0 Django==2.2.3 gunicorn==19.9.0 psycopg2-binary==2.8.3 pytz==2019.1 sqlparse==0.3.0 whitenoise==4.1.3 Here is the error output after executing the pip install django-heroku command: (env) MacBook-Pro:testing_django sudoxx2$ pip install psycopg2-binary Collecting psycopg2-binary Using cached https://files.pythonhosted.org/packages/ee/ed/2772267467ba5c21a73d37149da0b49a4343c6646d501dbb1450b492d40a/psycopg2_binary-2.8.3-cp37-cp37m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl Installing collected packages: psycopg2-binary Successfully installed psycopg2-binary-2.8.3 (env) MacBook-Pro:testing_django sudoxx2$ pip install django-heroku Collecting django-heroku Using cached https://files.pythonhosted.org/packages/59/af/5475a876c5addd5a3494db47d9f7be93cc14d3a7603542b194572791b6c6/django_heroku-0.3.1-py2.py3-none-any.whl Collecting psycopg2 (from django-heroku) Using cached https://files.pythonhosted.org/packages/5c/1c/6997288da181277a0c29bc39a5f9143ff20b8c99f2a7d059cfb55163e165/psycopg2-2.8.3.tar.gz Requirement already satisfied: whitenoise in /Users/sudoxx2/Documents/github/delete_copy/env/lib/python3.7/site-packages (from django-heroku) (4.1.3) Requirement already satisfied: django in /Users/sudoxx2/Documents/github/delete_copy/env/lib/python3.7/site-packages (from django-heroku) (2.2.3) Requirement already satisfied: dj-database-url>=0.5.0 in /Users/sudoxx2/Documents/github/delete_copy/env/lib/python3.7/site-packages (from django-heroku) (0.5.0) Requirement already satisfied: sqlparse in /Users/sudoxx2/Documents/github/delete_copy/env/lib/python3.7/site-packages (from django->django-heroku) (0.3.0) Requirement already satisfied: pytz in /Users/sudoxx2/Documents/github/delete_copy/env/lib/python3.7/site-packages (from django->django-heroku) (2019.1) Installing collected packages: psycopg2, django-heroku Running setup.py install for psycopg2 ... error ERROR: Command errored out with exit status 1: command: /Users/sudoxx2/Documents/github/delete_copy/env/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/4d/s84v7k6d1dx_m_6qbd1wfbz80000gp/T/pip-install-cq6yuehb/psycopg2/setup.py'"'"'; __file__='"'"'/private/var/folders/4d/s84v7k6d1dx_m_6qbd1wfbz80000gp/T/pip-install-cq6yuehb/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/4d/s84v7k6d1dx_m_6qbd1wfbz80000gp/T/pip-record-tyidyv7j/install-record.txt --single-version-externally-managed --compile --install-headers /Users/sudoxx2/Documents/github/delete_copy/env/include/site/python3.7/psycopg2 cwd: /private/var/folders/4d/s84v7k6d1dx_m_6qbd1wfbz80000gp/T/pip-install-cq6yuehb/psycopg2/ Complete output (48 lines): running … -
Use Django ORM for Complex Queries
I'm querying a legacy Postgres database based on user input and outputting it via my django views.py file. I'd like to generate and execute the query via the Django ORM functions. The database is setup so each record utilizes a unique foreign key field nct_id that is referenced across all tables. Using the nct_id I'd like to pull desirable information from various tables of my choosing. Currently I can generate and execute the query using raw SQL. The Raw SQL I'm trying to execute via Django ORM is below: Master_Query = Studies.objects.raw(''' SELECT DISTINCT ON (Studies.nct_id) Studies.nct_id, Studies.overall_status, Eligibilities.gender, Eligibilities.criteria, Conditions.conditions_name, Facilities.city, Facilities.country, Facility_Contacts.fc_name, Facility_Contacts.email FROM Studies INNER JOIN Eligibilities on Eligibilities.nct_id = Studies.nct_id INNER JOIN Conditions on Conditions.nct_id = Studies.nct_id INNER JOIN Facilities on Facilities.nct_id = Studies.nct_id INNER JOIN Facility_Contacts on Facility_Contacts.nct_id = Studies.nct_id WHERE ((Studies.overall_status LIKE 'Recruiting' OR Studies.overall_status LIKE 'Unknown status')) AND ((Conditions.conditions_name LIKE %s OR Conditions.conditions_name LIKE %s)) AND (gender LIKE %s OR gender LIKE %s) ORDER BY nct_id LIMIT %s''', [CondTypeU, CondTypeL, GenderQuery, GenderAll, LimitQuery]) I expect to see the same output as that of my raw sql query. From the above code I should see records from all the selected columns from all the … -
Django startserver not recognizing built in python libraries?
I am running Python 3.7 and Django 2.1 I am using Django for the first time. I have set up a virtual environment to run my project. I have imported django into the virtual environment using pip, but when I try to issue the command python manage.py runserver I have spent many hours searching for the problem online already but can't find a solution to my problem. I have opened python to check if sqlite3 is installed and it is. I have tried to use pip install sqlite3 in the virtual environment but that doesn't work. I get the following error code Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x00000203257A1B70> Traceback (most recent call last): File "C:\Environments\django_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Environments\django_env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Environments\django_env\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Environments\django_env\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Environments\django_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Environments\django_env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Environments\django_env\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Environments\django_env\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Environments\django_env\lib\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, … -
How can i reset/remove Nginx and Gunicorn i made on AWS server ? is deleting nginx directory would reset the server?
I have an AWS server when I tried deploying a Django app on it at first I messed up and made many typos so I followed The digital ocean tutorial which is so close to what I wanted to do and it worked fine. but I discovered that I needed to delete the Github repo and make a new one and I needed to use the new repo on the server so I removed the old project and cloned the new one and made a new virtual environment and referred to it in both the Gunicorn.service file and the Nginx but the app now is a total mess and returns a lot of errors and when I typed sudo journalctl -u gunicorn i found that gunicorn still refers to the old virtual environment so now I want to start from the beginning and reset everything to square 1 so how can I do that ? I don't want to wipe the machine storage as it contains other apps I want them maintained. deleting etc///gunicorn.config and etc/nginx would solve it and make me start again? btw during the whole process, I restarted both nginx and gunicorn many times but it's still … -
ModuleNotFoundError: No module named 'django_heroku' , although i have correctly installed all things for it vut could not get it?
I am making a django project and using css files but while deploying to heroku i got ModuleNotFoundError: No module named 'django_heroku' and i have installed all things for django-heroku...and at end it says Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 but im using css files and by disabling this applicaton error occure plz help ,,,i almost gave up im trying for 2 days HERE is the program when i do git push heroku master where error occurs remote: import django_heroku remote: ModuleNotFoundError: No module named 'django_heroku' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 remote: remote: https://devcenter.heroku.com/articles/django-assets remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to fjblogs. remote: To https://git.heroku.com/fjblogs.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/fjblogs.git' -
Printing well formatted sql queries in jupyter notebook with django-extensions plugin
In Django i want to see the sql in jupyter notebook in the way same way shown using ipython Eg: python manage.py shell_plus --ipython --print-sql In[1]: User.objects.all() Out[1]: SELECT "user"."id", "user"."password", "user"."last_login", "user"."is_superuser", "user"."is_staff", "user"."date_joined", "user"."first_name", "user"."last_name", "user"."email", "user"."is_active", "user"."modified_date" FROM "user" LIMIT 21 Execution time: 0.001471s [Database: default] <QuerySet [<User: yss@tst.com>]> The sql is show in a very well formated way which is very easy to understand. Now i want to try that in jupyter notebook python manage.py shell_plus --notebook --print-sql From here i followed the answer: https://stackoverflow.com/a/54632855 It says to install django_print_sql which i did then try to run from django_print_sql import print_sql with print_sql(count_only=False): q = User.objects.all() [0 queries executed, total time elapsed 0.00ms] django_print_sql: it says 0 queries and shows no sql output Also i installed sqlparser and tried the solution mentioned User.objects.all() import sqlparse from django import db sqlparse.format( db.connection.queries[-1]['sql'], reindent=True, keyword_case='upper' ) Out[1]: SELECT "user"."id",\n "user"."password",\n "user"."last_login",\n "user"."is_superuser",\n "user"."is_staff",\n "user"."date_joined",\n "user"."first_name",\n "user"."last_name",\n "user"."email",\n "user"."is_active",\n "user"."modified_date" FROM "user" LIMIT 21 The above sql does not look well formated at all. So django_print_sql and sqlparser are not giving a colorful formatted sql which is given by the python manage.py shell_plus --ipython --print-sql So how to get …