Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remove Duplicates sqlite3
Table_one - userid(1,2,3,4,5), username(ram,raj,ravi,ram,arun) Table_two - userid(1,2,3,4,5),petname(tall,short,angry,foodie,childish) i want the output in new table as Table_three-username(ram,raj,ravi,arun),petname(tall,short,angry,foodie) I want to remove the duplicates by username in sqlite3 field please do help me from this problem -
Is it possible to use multiple aws ses account in django project?
I want use multiple aws ses account in one django project... for some customers, the email must sent from one account and the remaining users must get emails from another account.. -
could not execute "manage.py"command in Pycharm
I have a DJANGO project and I want to migrate changes in models.py with "manage.py makemigrations" but when use that in Pycharm's terminal , manage.py files open and show this: if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project2ofC4.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) how can I active virtual environment? -
How to return a value from the subprocess in python?
I am using django 1.11. In the view.py file i am calling a subprocess like this: def twitter_trend(request): output = call("python /home/imsaiful/PiroProject/pironews/feed/twitter/trends.py", shell=True) print(output) return HttpResponse(output, content_type='text/plain') My trends.py file is given below which is calling by this process import os def sum(): print("hello world") a = 5 b = 3 return a+b if __name__ == '__main__': sum() When I call this file it returns 0 by HTTP response. How to return addition of a+b in the HttpResponse? -
Can't install django_messages app
I tried to install django_messages I copied the folder in my directory and ran this command: python manage.py makemigrations The error is this: C:\Users\Admin\Desktop\sample\enginesearch1>python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000025D3C50A488> Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 410, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: django_messages.Message.sender: (fields.E320) Field specifies on_delete=SET_NULL, but cannot be null. HINT: Set null=True argument on the field, or change the on_delete rule. What's the problem here and where should i change? -
Django Rest Framework custom message for 404 errors
I have a generic class based view: class ProjectDetails(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, generics.GenericAPIView): queryset = Project.objects.all() # Rest of definition And in my urls.py, I have: urlpatterns = [ url(r'^(?P<pk>[0-9]+)/$', views.ProjectDetails.as_view()) ] When the API is called with a non-existent id, it returns HTTP 404 response with the content: { "detail": "Not found." } Is it possible to modify this response? I need this error message for this view only. -
Youtube button is a no-show in django-CKEditor
I've been following this Youtube tutorial: https://www.youtube.com/watch?v=L6y6cn1XUfw&t=942s Alas, no luck in terms of the youtube button showing up on the menu. I wanted to just make the YT plugin a part of toolbar_Custom rather than creating the extra toolbar_Special item, but apparently it's a no-fly-zone. Trying for the method recommended in the video doesn't work either; I get an error on the line that contains: 'config.extraPlugins': ','.join(['youtube', 'codesnippet']), What am I missing here? In main/settings.py: CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'height': 250, 'width': '100%', 'toolbar_Custom': [ ['Styles', 'Format'], ['Bold', 'Italic', 'Underline', 'Strike', 'Undo', 'Redo'], ['Link', 'Image', 'Table', 'Youtube'], ['TextColor', 'SpecialChar', 'CodeSnippet'], ['Source'] ], 'config.extraPlugins': ','.join(['youtube', 'codesnippet']), }, NOTE: the tutorial says to just go with "extraPlugins" in the 13th line of the settings file, but that results in the CKEditor not showing up at all, so I've added "config.", and it runs again... In blog/models.py: class Post(models.Model): name = models.CharField(max_length=120, null=False, blank=False) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) content = RichTextUploadingField( null=False, blank=False, # config_name='toolbar_Custom', external_plugin_resources=[( 'youtube', '/static/ckeditor/ckeditor/plugins/youtube/', 'plugin.js', )], ) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=70, blank=True, null=True, help_text='<small><font color="red">don\'t. touch. the. slug. field. unless. you. mean. it.</font> (it will auto-generate, don\'t … -
Migrate database from SQLite to other db with Django server on Beanstalk
I hav a Django Server on AWS Beanstalk with SQLite3 db. However I soon realize that by using SQLite3, every time I deploy an updated version of my app on Beanstalk my data is wipe clean as the sqlite3 file is uploaded as well. So far I'm not sure what is a good way to remedy this, but I guess that the best thing for me to do now is to migrate to another db. So what is the best way for me to migrate my db for my Django serer, and what db should I use to prevent my data from being wipe clean every time I update my app? -
Django ManyToMany table defining best way
I wonder that what is the best way defining many to many relationship in Django. Is this way correct ?; class Student(models.Model): name = models.CharField(max_length=100) class Teacher(models.Model): name = models.CharField(max_length=100) class StudentTeacher(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) extra_field = models.CharField(max_length=200) What are the advantages of using through ? class Student(models.Model): name = models.CharField(max_length=100) class Teacher(models.Model): name = models.CharField(max_length=100) students = models.ManyToManyField(Student, through='StudentTeacher') class StudentTeacher(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) extra_field = models.CharField(max_length=200) -
Python 3.7 django app failed to start with unhandled exception
I'm running windows 10 pro, just upgrade from python 3.6.2 64bits to python 3.7 64bits and my django app stopped working with an unhandled exception error. File "C:\Python\Python37\lib\site-packages\jinja2\loaders.py", line 224, in __init__ provider = get_provider(package_name) File "C:\Python\Python37\lib\site-packages\pkg_resources\__init__.py", line 351, in get_provider return _find_adapter(_provider_factories, loader)(module) File "C:\Python\Python37\lib\site-packages\pkg_resources\__init__.py", line 1384, in __init__ self.module_path = os.path.dirname(getattr(module, '__file__', '')) File "C:\Python\Python37\lib\ntpath.py", line 221, in dirname return split(p)[0] File "C:\Python\Python37\lib\ntpath.py", line 183, in split p = os.fspath(p) TypeError: expected str, bytes or os.PathLike object, not NoneType Anyone here seeing the same issue and got a solution to share? Many thanks! -
unable to update the fields in model Django
I am trying to edit user details of a specific user when admin logins its going to edit page but when I press the update button it's not updating not showing any error message. (correct me please if I am wrong). This is my edit.html {% extends 'base.html' %} {% block title %}edit details{% endblock %} {% block content %} {% if emp %} <form method="POST" class="form-inline my-2 my-lg-0" "> {% csrf_token %} <div class="container"> <br> <div class="form-group row"> <label class="col-sm-1 col-form-label"></label> <div class="col-sm-4"> <h3>Update Details</h3> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Employee User:</label> <div class="col-sm-4"> <input type="text" id="id_user" required maxlength="20" value="{{ emp.user }}"/> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Employee first_name:</label> <div class="col-sm-4"> <input type="search" id="id_first_name" required maxlength="100" value="{{ emp.first_name }}" /> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Employee last_name:</label> <div class="col-sm-4"> <input type="text" id="id_last_name" required maxlength="100" value="{{ emp.last_name }}" /> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Employee Email:</label> <div class="col-sm-4"> <input type="email" id="id_email" required maxlength="254" value="{{ emp.email }}" /> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Employee Gender:</label> <div class="col-sm-4"> <input type="text" id="id_gender" required maxlength="15" value="{{ emp.gender }}" /> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Employee Age:</label> <div class="col-sm-4"> <input type="text" id="id_age" required … -
django: how to send mail with TO, CC, subject and body?
to: A list or tuple of recipient addresses. cc: A list or tuple of recipient addresses used in the “Cc” header when sending the email. subject: The subject line of the email. body: The body text. This should be a plain text message. attachments: A list of attachments to put on the message. -
Django with Geoserver
I want to display a shapefile of my map using WMS with Geoserver, because transforming them to GeoJSON and displaying them into the map is taking time. I would like to be able to use the two ways. This is my code: I published my shapefile from postgis into geoserver and my workspace url is localhost:8080/geoserver/geodjango. views.py from django.shortcuts import render from django.views.generic import TemplateView from django.core.serializers import serialize from django.http import HttpResponse from layer.models import ww_manholes from django.http import JsonResponse from rest_framework.views import APIView from rest_framework.response import Response from . import forms class MapView(TemplateView): template_name = 'index.html' def layer_datasets(request): manholes = serialize('geojson', ww_manholes.objects.all()) return HttpResponse(ww_manholes, content_type='json') models.py from __future__ import unicode_literals from django.db import models from django.contrib.gis.db import models class ww_manholes(models.Model): id = models.BigIntegerField(primary_key=True) l_ass_obj = models.BigIntegerField() l_field_re = models.BigIntegerField() street = models.BigIntegerField() zip_code = models.BigIntegerField() regio_code = models.BigIntegerField() owner = models.BigIntegerField() ww_type = models.BigIntegerField() accuracy = models.BigIntegerField() x = models.FloatField() y = models.FloatField() x_ge = models.FloatField() y_ge = models.FloatField() z = models.FloatField() invert_el = models.FloatField() inv_start = models.FloatField() inv_end = models.FloatField() depth = models.FloatField() depth_star = models.FloatField() depth_end = models.FloatField() material = models.BigIntegerField() lining = models.BigIntegerField() coating = models.BigIntegerField() contractor = models.BigIntegerField() const_year = models.BigIntegerField() diam_nom = models.BigIntegerField() … -
Django Postman implementation for sending messages
I am trying to use Django-Postman framework to send messages between users in Django 2.0 . I have installed the app and made the necessary changes as mentioned in this website. However when i try to go the the message urls I get blank page Here is what I have done so far. Installed django-postman In settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'postman', 'account', 'cart', 'shop', 'landingpage', ] POSTMAN_I18N_URLS = True # default is False POSTMAN_DISALLOW_ANONYMOUS = True # default is False POSTMAN_DISALLOW_MULTIRECIPIENTS = True # default is False POSTMAN_DISALLOW_COPIES_ON_REPLY = True # default is False POSTMAN_DISABLE_USER_EMAILING = True # default is False POSTMAN_FROM_EMAIL = 'from@host.tld' # default is DEFAULT_FROM_EMAIL POSTMAN_AUTO_MODERATE_AS = True # default is None POSTMAN_SHOW_USER_AS = 'get_full_name' # default is None POSTMAN_NAME_USER_AS = 'last_name' # default is None POSTMAN_QUICKREPLY_QUOTE_BODY = True # default is False POSTMAN_NOTIFIER_APP = None # default is 'notification' POSTMAN_MAILER_APP = None # default is 'mailer' And I have linked urls this way in urls.py url(r'^messages/', include('postman.urls', namespace='postman')), How can I solve this problem. can help me ? Thanks. -
Django-Facebook Login Error
When I try to login with facebook I'm getting following error URL blocked: This redirect failed because the redirect URI is not white-listed in the app's client OAuth settings. Make sure that the client and web OAuth logins are on and add all your app domains as valid OAuth redirect URIs. Please help me to solve this error. -
How to POST a data value using @api_view in django rest api?
I have two APIs. From one API, I am sending string data to the second API. In the second API doing some calculation, I save a JSON format data in the API and send back the data to the first API. It is working. But in the second API, if I try to POST string data from the content box it shows error. Here the media type is "application/json". So how do I POST data from the API view? I have added the screenshot of the second API: input data Error Massage Some portion of my views.py of the second API: @api_view(['GET', 'POST']) def sentenceList(request): if request.method == 'GET': queryset = Bucketlist.objects.all() serializer = BucketlistSerializer(queryset, many=True) return Response(serializer.data) elif request.method == 'POST': triples = getTriples(request.data) keys = ['sub','predi','obj'] demo_data = dict(zip(keys,triples[0])) serializer = BucketlistSerializer(data=demo_data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django zip multiple PDF files generated with xhtml2pdf
I am successfully using xhtml2pdf to generate a PDF file for download. What I would now like to achieve is the ability to generate multiple (separate) PDF files for download. I'm guessing that the best way to achieve this is to zip the PDF's but I'm at a loss at how to go about achieving this. Is anyone able to point me in the right direction? My function for rendering to PDF is: def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")),result, link_callback=link_callback) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None My view for generating the single PDF file is: class GeneratePDF(View): def get(self, request, *args, **kwargs): date = datetime.datetime.now() context = { 'date':date } pdf = render_to_pdf('pdf/my_first_file.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "First_File.pdf" content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") The other files I would like to render as PDF as part of the zip download are all in the 'pdf' folder. There will be a maximum of 12 of these. The context differs for each: pdf/my_second_file.html pdf/my_third_file.html ... Any guidance that can be provided will be much appreciated! -
Django; query objects through jquery ajax
I'm not familiar with jquery and I'm creating a project using Django. Now I am trying to create a search function. What I want to do is showing up entries that have a specific word the user input without loading the page. I'm not sure what this page is using but what I want to create is basically like this page. https://simpleisbetterthancomplex.com/search/ But I don't understand how I can adapt ajax into Django yet, anyone who can give me an example and tips? -
Django freezes object insertion into sqllite to 750 KB
I am running the latest versions of Django and Python. The problem that I experience is that the bulk insertion into a Sqlite3 database is frozen at 750 KB. In short, I added an import_data method to the respective model in models.py. In the import_data model, I load a csv file, create a csv.DictReader, and iterate through the csv to import each line. Via the save() method in multiple model classes (each line has related data and is inserted into multiple tables), the data is processed. Each time I run the program, the program freezes once the Sqlite database is 750 KB in size. The actual csv file is something like 2 GB in size... Does Django have some restrictions regarding imports? Is there a time-out? Some cache? I feel pretty confident that the problem does not relate to my code, but rather to Django limiting these imports. Does anyone have experience with this issue? -
How to override global parameter of javascript?
Background: I have web project written in django(python), record some global settings in settings.py settings.py EXTERNAL_SERVICE_IP = 10.192.225.30 When I deliver this project to users, they may need to change this EXTERNAL_SERVICE_IP, as they deploy the service on different IP. Normally, they can modify this settings.py, but when I deliver this project using docker, it is not so convenient. So changed the settings.py. EXTERNAL_SERVICE_IP = os.environ.get('EXTERNAL_SREVICE_IP') Then, when start the container, user can use -e to pass their external service ip to python. Question: Now, same scenario happened in javascript part. I have a settings.js settings.js const SERVICE_API = "http://10.192.225.18:8090/xxx/" The web's ui part will let browser to use this to launch a ajax call in javascript, of course, we use jsonp, so no cross-origin issue. So, if the project also in docker container, what's the best way for user to override this SERVICE_API in javascript? I don't want user to docker exec to change this file, not out-of-box for user. -
pymongo.errors.ServerSelectionTimeoutError
What could possibly be the reason of this error? I am using a ubuntu guest server in a windows 10 host system The entire error is as follows: ` File "train_data.py", line 36, in <module> update_database.insert_features(features) File "/pupyl/preprocessing_data/update_database_with_features.py", line 59, in insert_features self.db_operation.insert_record(records, "train") File "/pupyl/database_client/database_operations.py", line 33, in insert_record self.db.train.insert(record) File "/usr/local/lib/python3.6/site-packages/pymongo/collection.py", line 3161, in insert check_keys, manipulate, write_concern) File "/usr/local/lib/python3.6/site-packages/pymongo/collection.py", line 607, in _insert bypass_doc_val, session) File "/usr/local/lib/python3.6/site-packages/pymongo/collection.py", line 595, in _insert_one acknowledged, _insert_command, session) File "/usr/local/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1242, in _retryable_write with self._tmp_session(session) as s: File "/usr/local/lib/python3.6/contextlib.py", line 81, in __enter__ return next(self.gen) File "/usr/local/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1571, in _tmp_session s = self._ensure_session(session) File "/usr/local/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1558, in _ensure_session return self.__start_session(True, causal_consistency=False) File "/usr/local/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1511, in __start_session server_session = self._get_server_session() File "/usr/local/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1544, in _get_server_session return self._topology.get_server_session() File "/usr/local/lib/python3.6/site-packages/pymongo/topology.py", line 427, in get_server_session None) File "/usr/local/lib/python3.6/site-packages/pymongo/topology.py", line 199, in _select_servers_loop self._error_message(selector)) pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused ` -
How can I render 3 elements per loop in django template?
I don't know how to express my need.I just show the code. data_lis = [1,2,3,4,5,6,7,8,9] How can I separate this list into N parts with 3 element each part? I do this is in order to render <div class="card-group d-block d-md-flex u-card--gutters-2-md"> <div class="card border-0 rounded shadow-sm mb-3 transition-3d-hover">element</div> <div class="card border-0 rounded shadow-sm mb-3 transition-3d-hover">element</div> <div class="card border-0 rounded shadow-sm mb-3 transition-3d-hover">element</div> </div> I need to render the data just like the above style,but how can I dynamically change the render way? My solutions a = [[3,2,3],[3,4,2],[3,2]] I just handly separate it into N parts with 3 elements each part! -
How to join two table columns and store in a separate new table in sqlite3
I Have two tables Name-fields(user_Id,name) Type-fields(user_Id,meaning) These are my two tables and i want to copy these data and merge them into a new separate table like this using sqlite3 output table-fields(name,meaning) make me out of this question What I have tried: i have tried update method but did not got an clear output -
'Q' object has no attribute 'order_by'-Django
I am trying to include a search field inside my profile page. It works for some of the module fields. My problem is when I use order by Attribute (correct me please if I am wrong). I have a model class employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=50) gender = models.CharField(max_length=1,choices=(('M','Male'), ('F','Female')),blank=True) age = models.PositiveIntegerField(blank=True, null=True) salary = models.CharField(blank = True,max_length=50) def __str__(self): return self.user.username and query def view_profile(request): employees = employee.objects.all() query = request.GET.get("q") if query: employees = employee.objects.filter( Q(last_name__icontains=query)| Q(first_name__icontains=query)| Q(gender__icontains=query)| Q(email__icontains=query)| Q(age__icontains=query).order_by('-id') ).distinct() args= {'user':request.user,'employees':employees} return render(request,'profile.html',args) I am getting the error: 'Q' object has no attribute 'order_by' there is another small error i would like to know when i search the field on username i am getting this type of error: Q(user__icontains=query) Related Field got invalid lookup: icontains -
Django partially restricting contents according to different user group
Just started Django last week and I am facing this problem regarding two types of users (normal and VIP) and how to restrict normal users from viewing VIP contents. I am using Django with MySQL. My site does not requires user to signup but instead, I will be giving them username/password. I manually creates user via Django admin and group them according to VIP or normal. I will be uploading contents (again via admin) and I have a Boolean check-box that determine whether it is a VIP content or not. What I done so far: User must login to view the contents Upon logging in, VIPs can see VIP contents and normal users will not be able to see VIP contents. FAQ.html {% extends 'base.html' %} ...skipping... {% for faqs in fq reversed %} {{ faqs.name }} {{ faqs.description }} {{ endfor }} views.py def is_user(user): return user.groups.filter(name='User').exists() def is_vip(user): return user.groups.filter(name='VIP').exists() @login_required @user_passes_test(is_user) def faq(request): fq = FAQ.objects.filter(vip_only=False) return render(request, 'faq.html', {'fq':fq}) models.py class FAQ(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=300) vip_only = models.BooleanField(default=False) Error Case 3 FAQ entries are made, the first one is classified as VIP only. When a normal user log in into FAQ section, …