Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django crash: exceptions must be old-style classes or derived from BaseException, not str
I have an app that uses 1.9. It will work fine for weeks and weeks, and then out of the blue a page that has just worked will crash with this: Traceback: File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 174. response = self.process_exception_by_middleware(e, request) File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 172. response = response.render() File "/usr/lib/python2.7/site-packages/django/template/response.py" in render 160. self.content = self.rendered_content File "/usr/lib/python2.7/site-packages/django/template/response.py" in rendered_content 137. content = template.render(context, self._request) File "/usr/lib/python2.7/site-packages/django/template/backends/django.py" in render 95. return self.template.render(context) File "/usr/lib/python2.7/site-packages/django/template/base.py" in render 204. with context.bind_template(self): File "/usr/lib64/python2.7/contextlib.py" in __enter__ 17. return self.gen.next() exceptions must be old-style classes or derived from BaseException, not str Exception Location: /usr/lib/python2.7/site-packages/django/utils/module_loading.py in import_string, line 23 If I go the exact same URL again it will work. Anyone have any idea what could be causing this or how I can debug it further? -
Adding array field OperationalError
I am very new to django(version 1.11).I am trying to make a shoppingwebsite and i am confused in creating Order model. In here you can see my first (version 1) models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.contrib.postgres.fields import ArrayField class Products(models.Model): name = models.CharField(max_length = 20 , default='') description = models.CharField(max_length = 100 , default='') price = models.IntegerField(default=0) image = models.ImageField(upload_to='product_image',blank=True) vojood = models.BooleanField(default=False) unique = models.CharField(max_length = 100 ,default='') typ = models.CharField(max_length = 100 ,default='') def __str__ (self): return self.name @classmethod def turn_on(prds,pk): prds[pk].vojood=true @classmethod def turn_off(prds,pk): prds[pk].vojood=false class Order(models.Model): username = models.CharField(max_length = 300 , default='') address = models.CharField(max_length = 300 , default='') time = models.IntegerField(default=0) price = models.IntegerField(default=0) arrived = models.BooleanField(default=False) basket = ArrayField(models.CharField(max_length=300,default=''),default=list) def __str__ (self): return self.username After python manage.py makemigrations when i tried to migrate the new field (arrayfield) with python manage.py migrate i got a very long error . So the last line was django.db.utils.OperationalError: near "[]": syntax errorSo i deleted the new field(arrayfield) and again i used makemigrations but the error during migrate did not change.And now i cant migrate any field with any type! And here is my Fucking Error : E:\django projects\4\third>python … -
React post with axios using Django serializers
//localhost:3000/[object%20Object] Currently trying to submit form data from react front end using axios with django rest api. First time implementing it; can't figure out why I continue to get this error. For my backend, I've set django serializers. I'm trying to submit my react form to allow my django backend to retrieve/send out an email with the data that was submitted. React Form Django Mail View Django API endpoint Web Error -
Django connection cursor not showing any tables?
I'm trying to debug an issue in a separate question, Django "MigrationSchemaMissing: Unable to create the django_migrations table (no schema has been selected to create in)": when I try to python manage.py migrate, I get an error no schema has been selected to create in. In my version of Django (1.11.9), the ensure_schema method of the MigrationRecorder is def ensure_schema(self): """ Ensures the table exists and has the correct schema. """ # If the table's there, that's fine - we've never changed its schema # in the codebase. import ipdb; ipdb.set_trace() if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): return # Make the table try: with self.connection.schema_editor() as editor: editor.create_model(self.Migration) except DatabaseError as exc: raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) (It would appear that in https://github.com/django/django/blob/master/django/db/migrations/recorder.py this is slightly refactored, but essentially the same). Note that I've set a trace at the beginning of the method using import ipdb; ipdb.set_trace(). Now, when I drop into the debugger, I see that introspection.table_names() on the self.connection.cursor() returns an empty list: (venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py migrate > /Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/migrations/recorder.py(53)ensure_schema() 52 import ipdb; ipdb.set_trace() ---> 53 if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): 54 return ipdb> self.Migration._meta.db_table 'django_migrations' ipdb> self.connection.introspection.table_names(self.connection.cursor()) [] So it seems like the database … -
Django - Calling one class method from another in Class Based View
I have a method inside a django class based view like called get_player_stats. From this method I want to call another method in the same class but I am unable to. Code is like below: class ScoreView(TemplateView): def get_player_stats(request): player_id = request.GET.get(player_id, None) # compute player stats #here I want to call like below: self.get_team_stats(player_id) def get_team_stats(self, player_id): #compute team stats When I run this it says name 'self' is not defined If I try def get_player_stats(self, request): it says missing 1 required positional argument: 'request' If I try def get_player_stats(request, request): it says missing 1 required positional argument: 'self' How can I call get_team_stats from get_player_stats? This is very frustrating, any help is greatly appreciated -
dropdown menu does not work as expected
in index.html I want to display dropdown menu to select percent of project, and then update selected value to Project table in database. It typically works, except when I hit submit button the index page is not automatically refreshed, I have to manually refresh the page to get updated value to be displayed on the page. Please excuse me, Im new to Django. I appreciate all these helps!! forms.py class HomeForm(forms.Form): FILTER_CHOICES = ( (0, 0.02), (1, 0.03), (2, 0.04), ) Update_Project_No = forms.CharField(widget = forms.TextInput( attrs = { 'size': '30', 'class': 'form-control', 'placeholder': 'New project no...', } )) Percent_of_Project = forms.CharField(widget = forms.TextInput( attrs = { 'size': '30', 'class': 'form-control', 'placeholder': 'Percent of Project', } )) filter_by = forms.ChoiceField(choices = FILTER_CHOICES) views.py def emp_detail(request, project_id): employee = Project.objects.get(pk = project_id).employee.all() project = Project.objects.get(pk = project_id) project_inst = get_object_or_404(Project, pk = project_id) paginator = Paginator(employee, 20) page = request.GET.get('page') try: employee = paginator.page(page) except PageNotAnInteger: employee = paginator.page(1) except EmptyPage: employee = paginator.page(paginator.num_pages) if request.method == 'POST': form = HomeForm(request.POST) if form.is_valid(): project_inst.pro_no = form.cleaned_data['Update_Project_No'] project_inst.percent = form.cleaned_data.get('filter_by') project_inst.save() form = HomeForm() else: form = HomeForm() return render(request, 'polls/emp_detail.html', {'employee': employee, 'project': project, 'form': form}) -
Django Built-in Login System - accounts/profile/ not found
I am using django built-in login system for my website. Whenever I create an account and try to login, it redirects to the page http://127.0.0.1:8000/accounts/profile/ and gives error page not found. But when I manually remove the accounts/profile/ part from url, it logins into the website. How can I make my django system to directly redirect to http://127.0.0.1:8000 rather than the above mentioned URL. Here is my urls.py file code: urlpatterns = [ path('',include('feedback.urls')), path('accounts/', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), path('login/', auth_views.login, {'template_name': 'login.html'}, name='login'), path('logout/', auth_views.logout, {'next_page': 'login'}, name='logout'), path('signup/', core_views.signup, name='signup'), ] feedback/urls.py: urlpatterns = [ path('create_url/',views.create_url,name='create_url'), path('submit_affective/',views.submit_affective,name='submit_affective'), path('submit_cognitive/',views.submit_cognitive,name='submit_cognitive'), path('thanks/',views.thanks,name='thanks'), path('detail_affective/<int:id>',views.detail_affective,name='detail_affective'), path('detail_cognitive/<int:id>',views.detail_cognitive,name='detail_cognitive'), path('',views.index,name='index'), ] -
Create OpenAPI specification with Django Rest Framework and Swagger
I'm trying to figure out how do I create rich API specification with Swagger, specifically where and how to declare descriptions for parameters, response codes and sample bodies of POST and GET responses. The documentation provided with Swagger for DRF seems to answer none of this questions. Here's my sample model for object of type "Card": class Card(models.Model): archiveStatus = models.BooleanField(default=False, help_text='Status of card') title = models.TextField(max_length=200, blank=False, help_text='Title of card') description = models.TextField(max_length=1000, blank=True, help_text='Description') color = models.CharField(max_length=10, default='#fff9ac', help_text='Color') uniqueNumber = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False, help_text='UUID') owner = models.ForeignKey('auth.User', related_name='cards', on_delete=models.CASCADE, help_text='owner') tableID = models.ForeignKey(Table, on_delete=models.CASCADE, help_text='ID of containing table') URL pattern for this endpoint: url(r'^card/(?P<cardid>[0-9a-f-]+)$', views.CardDetails.as_view()), The serialiser I'm using to zip/unzip it from/to JSON object: class CardSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Card fields = ('uniqueNumber', 'archiveStatus', 'title', 'description', 'color', 'owner', 'tableID') And finally the APIView: class CardDetails(APIView): permission_classes = (permissions.AllowAny,) parser_classes = (JSONParser,) def get_record(self, cardid): try: return Card.objects.get(uniqueNumber=cardid) except Card.DoesNotExist: raise Http404 def get(self, request, cardid, format=None): record = self.get_record(cardid) serializer = CardSerializer(record) return Response(serializer.data) With all this set up I'm getting this description from Swagger: I want to add description for parameter, description for endpoint, sample response and couple descriptions for different … -
Django "MigrationSchemaMissing: Unable to create the django_migrations table (no schema has been selected to create in)"
I'm trying to restore a production database to my local machine, similar to the workflow described for Heroku (https://devcenter.heroku.com/articles/heroku-postgres-import-export). However, I'm using Aptible, which provides a DB tunnel for this purpose. Using pgAdmin4, I've created a 'Custom' backup. Then, slightly modifying a pgAdmin command, I've restored it using "/Applications/pgAdmin 4.app/Contents/SharedSupport/pg_restore" --host "localhost" --port "5432" --username "postgres" --no-password --dbname "lucy_prod" --verbose "/Users/kurtpeek/lucy-prod-backup-11-june-2018" --clean where I've added the --clean option to drop database objects before recreating them (cf. https://www.postgresql.org/docs/9.2/static/app-pgrestore.html). The problem is that when I now try to python manage.py migrate, I get the following error: (venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py migrate Traceback (most recent call last): File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) psycopg2.ProgrammingError: no schema has been selected to create in LINE 1: CREATE TABLE "django_migrations" ("id" serial NOT NULL PRIMA... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 57, in ensure_schema editor.create_model(self.Migration) File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 303, in create_model self.execute(sql, params or None) File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, … -
Django Unit Tests Failing on Travis CI Builds
I have a very basic Django app (Python 3.6.4) and I've written a unit test which passes locally. An in memory SQLite DB is created (by default) for the tests. When my Travis CI build runs the same tests the tests pass but the test command fails with the following error: django.db.utils.OperationalError: near "SCHEMA": syntax error The command "python manage.py test --settings=myapp.dev_settings" exited with 1. One strange thing I notice is that when the tests are run on Travis, it's says it's reusing an existing DB and never destroys it after the tests are run: $ python manage.py test --settings=myapp.dev_settings Using existing test database for alias 'default'... I don't really get that, because it should be an in memory DB and when I run it locally, a new database is created each time: Creating test database for alias 'default'... . . . Destroying test database for alias 'default'... My dev_settings.py file has a sqlite db on the filesystem, but that is only used for running the local development server: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Travis installs all the dependencies and they match my local environment (I'm fairly sure). Any help would be great, … -
Django 1.11 querysets: Get all objects of a relationship set
If have a model for companies. These companies have an attribute employment_set, because workers are assigned to companies via the employment relation. How can I query all employees for a given company? The model for the employements look like this: class Employment( SoftDeletableModel, TimeStampedModel, models.Model ): company = models.ForeignKey(Company, on_delete=models.CASCADE) employee = models.ForeignKey(UserWorkerProfile) employed_by = models.ForeignKey(UserOwnerProfile) I tried using company.employment_set.values("employee"), but this returns a strange activatorquery set. Is there a way to return the normal queryset? Or is values() already the correct method? Edit: To eloborate a little more: I want to end up with a queryset containing all the UserWorkerprofile model instances. In the documentation for values() it says: Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable. and I want exactly a queryset of model instances. -
Order in which HTTP error codes 403, 404 and 405 should be expected
So I need to know what is the best practice regarding the order in which some error codes must be returned. Suppose I try to: PUT /api/v1/objects/non-existing-id/ And all three problems occur: There is no resource. If there was a resource PUT wouldn't be allowed as action. If there was a resource I (the user) wouldn't have access to it. I would like to know what error: 404, 405 or 403 I should expect first, and second, and third. I assume there must be a globally accepted standard for this. My own belief is that permission errors should come first, then action errors, and at last existence errors. That is: 403 then 405 then 404. -
Django: Make ajax call to a class based view method
So in my Django project I make an ajax call to a method in a view. urls.py line is: url('scores/get_player_status', views.get_player_stats, name='player-stats'), Ajax code is: $.ajax({ url: '/scores/get_player_status/', data: { 'game': game_id }, dataType: 'json', success: function (data) { showScoresTable(data) } }); Then in views.py I have a method called get_player_stats def get_monthly_stats(request): # here I compute the player stats and return it # ... return JsonResponse(resp) This works fine. However all my views are class based views, so I have a ScoreView(TemplateView) class in the views.py and ideally I would to move the get_player_stats method inside this class and have ajax call this method. However I do not know how to do it. When I move the method inside this class and call scores/get_player_stats it just renders the whole view instead of returning me the result of the player stats computation. Any pointers will be very helpful as I am pretty new to django. Thank you! -
Django: How to assign foreign keys with custom commands
I'm working on a custom command to populate Django model objects with JSON data. import json import dateparser from django.core.management.base import BaseCommand, CommandError from concerts.models import Concert class Command(BaseCommand): name = "load_concerts" help = "Load JSON concert data" def add_arguments(self, parser): parser.add_argument('concert_file', type=str) def handle(self, *args, **options): with open(options['concert_file']) as f: data = json.load(f) for concert in data: Concert.objects.create(**concert) Each Concert object has a foreign key, Venue. The JSON data reflects the correct venue name as a string, but when I run the custom command, I get the error: ValueError: Cannot assign "u'The Moon'": "Concert.venue" must be a "Venue" instance. How would I tackle this issue? Could I could assign the ID of each Venue instance rather than a string with the name? -
How do you Serialize the User model in Django Rest Framework
Am trying to familiarize myself with the Django Rest Framework. Tried an experiment to list the users I created but the serializer always returns blank objects. Here's my code: serializers.py from rest_framework import serializers from django.contrib.auth.models import User class CurrentUserSerializer(serializers.Serializer): class Meta: model = User fields = ('username', 'email', 'id') urls.py from django.urls import include, path from administration import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'admin', views.CurrentUserViewSet) urlpatterns = [ path('', include(router.urls)), ] views.py from django.shortcuts import render from django.contrib.auth.models import User from administration.serializers import CurrentUserSerializer from rest_framework import viewsets # Create your views here. class CurrentUserViewSet(viewsets.ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = CurrentUserSerializer Rest of the code is pretty much boilerplate based on the DRF tutorial. The result I'm getting is blank objects for every user. The number of blanks grows and shrinks if I add/remove a user, which tells me I'm at least partially hooked up to the User model. Example below: [{},{},{}] What I'm expecting is something like: [{"username": "jimjones", "email": "jim&jones.com", "id": 0},{...}] Any help appreciated. -
Moving from sqlite to postgresql database - Django
I am trying to move to a postgresql database in django, to replicate a production environment that will be moving to. I think i've set up the postgresql database OK - and changed settings file in django to the following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'teamexchange', 'USER': 'oliver', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '', } } But when I try to use manage.py to migrate tables and reupload data e.g: python3 manage.py migrate --run-syncdb I get the following error: Traceback (most recent call last): File "/Users/olivermonaghan-coombs/.virtualenvs/my_django_environment/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "teamapp_team" does not exist LINE 1: SELECT "teamapp_team"."team_code" FROM "teamapp_team" ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/olivermonaghan-coombs/.virtualenvs/my_django_environment/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/olivermonaghan-coombs/.virtualenvs/my_django_environment/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/Users/olivermonaghan-coombs/.virtualenvs/my_django_environment/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/olivermonaghan-coombs/.virtualenvs/my_django_environment/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Users/olivermonaghan-coombs/.virtualenvs/my_django_environment/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Users/olivermonaghan-coombs/.virtualenvs/my_django_environment/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked … -
Uploading Multiple Files in Django?
I am trying to upload multiple files with Django. The problem I'm having is once I access the element in request.FILES['ballast-file[]'] it turns into a InMemoryUploadedFile when it should be a list of InMemoryUploadedFile. I know it should be a list because when looking at the contents of request.FILES it is a dictionary with key 'ballast-file[]' and a list of InMemoryUploadedFile's. My function: def upload(request): if request.method == "GET": return render(request, 'upload_pdf.html') print(request.FILES) print(request.FILES['ballast-file[]']) files = request.FILES['ballast-file[]'] print(type(files)) print(files) return render(request, 'upload_pdf.html') The form: <form enctype="multipart/form-data" method="POST" action="/ballast/upload/" id="uploadpdf_form"> {% csrf_token %} <label class="font-weight-bold">Upload PDF</label> <div class="custom-file"> <input type="file" class="custom-file-input" id="ballast-file" name="ballast-file[]" multiple> <label class="custom-file-label" for="ballast-file">Choose file</label> </div> </form> -
Django ALL in query (as opposed to OR / plain IN clause)
Say I have 2 models joined via many-to-many: class Person(models.Model): name = models.CharField(max_length=200, null=False, blank=False) sports = models.ManyToManyField('Sport') class Sport(models.Model): name = models.CharField(max_length=200, null=False, blank=False) people = models.ManyToManyField('Person') I'd like to perform an AND query to filter Person by those who play ALL sports given a list of sport ids. So something like: Person.objects.filter(sports__id__all=[1,2,3]) Or, said differently, exclude anyone that doesn't play ALL the sports. -
How to sum over a computed variable in django?
I have trouble find the solution to the following simple problem. The following command tenta_data = Konstruktion.objects.all().annotate(tid=Sum(F('antal'))) works fine if antal is a variable in the database: class Konstruktion(models.Model): antal = models.FloatField() .... def anumber(self): return ..... but how do I do if I want to sum over anumber? Which is a function. -
Django Datetime Choice field issue
So, I am quite new to Django, and I am trying to put the following idea into practice: In my object creation form I want users to fill a date field in order to put a timestamp of sorts on the object. The catch is that I want to make only two days available for choosing - today and tomorrow. I do not want to use DateTime field and make users type in the dates by hand as it looks quite ugly and not really convenient to use. I decided to try and implement a choice field. It gets rendered well, but so far I have not figured out how to make my form data pass as valid. I have poked around with pdb, as a result read about cleaning/validating methods but I still have no idea how to get this to work. What I already tried: adding functions that return today and tomorrow as date objects and as strings (here is the latter) the error text is: select a valid choice, is not one of the available choices I perceive that it fails during clean() method somehow. Or, if it is not a reasonable idea (which it probably is … -
Autocomplete jquery django
I'm having problems with autocomplete, autocomplete works for everyword I type in the text are that are separated with a -.The problem is that everytime I'm autocomplete a new word, the text that alredy exist in the textarea is replaced with the new autocomplete, how can I do In order to keep the new value and the values that alredy exist in the textarea.I have tried with append but doesn't works id_eacheris the id of the textarea that have the fuction autocomplete here is my autocomplete code: $(function() { $("#id_teacher").autocomplete({ source:"/inicio/api/get_asesores/", select: function (event, ui) { //item selected AutoCompleteSelectHandler(event, ui) }, minLength: 1, }); }); function AutoCompleteSelectHandler(event, ui) { var selectedObj = ui.item; console.log(selectedObj.value) var data="-"+selectedObj.value $('#id_teacher').append(data) } and this is my code in django view.py: def get_asesores(request): if request.is_ajax(): q = request.GET.get('term', '') q=q.title() if q.find("-")!=-1: q=q.split('-')[-1] teacherlastname= Teacher.objects.filter(lastname__icontains=q) teachername= Asesor.objects.filter(Firstname__icontains=q) results = [] a=q.split() if len(a) == 2: asesor2name=Asesor.objects.filter(lastname__icontains=a[0],MomLastname__icontains=a[1]) for teacherin asesor2lastname: teacher_json = {} teacher_json = teacher.lastname+ " " + teacher.MomLLastname+" "+teacher.Firstname results.append(teacher_json) for asesor in asesoresAp: teacher_json = {} teacher_json = teacher.lastname + " " + teacher.MomLastname+" "+teacher.Firstname results.append(teacher_json) for teacher in asesoresname: teacher_json = {} teacher_json = teacher.lastname + " " + teacher.MomLastname+" "+teacher.Firstname results.append(teacher_json) … -
Struggling to turn JSON data into Django model object instances
I'm trying to take a list of JSON objects, turn them into Python dicts, then populate the Concert model with an object for each of the Python dicts. import json from models import Concert with open('output.json') as f: data = json.load(f) for concert in data: Concert.objects.create(**concert) I'm getting an error message I haven't seen before: ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Is this something that can be easily addressed? There is a foreign key in my model that corresponds to one of the key-value pairs in the JSON objects; is that relevant to this error? -
Facing issues on implementing text editor
I'm using django 2.0 and now trying to add a Text editor into one of my post options. My text editor powered by Quill.js. After coding it into my from section the code looks like that -- <form action="" method="post"> {% csrf_token %} <div id="editor-container"> <input type="text" name="description"> </div> <input class="ui button" type="submit" value="Post" /> </form> If I use id into Input field, text editor does not work properly such as Bold option doesn't work, weird font. on the other hand, if I put id into div elements then into my template text editor works properly but It is not taking any post. javascript code var quill = new Quill('#editor-container', { modules: { toolbar: [ ['bold', 'italic'], ['link', 'blockquote', 'code-block', 'image'], [{ list: 'ordered' }, { list: 'bullet' }] ] }, placeholder: 'Compose an epic...', theme: 'snow' }); Or any better suggestion for alternatives. -
How can I create a predefined group with permissions?
I want to create several groups with predefined permissions. But I can not find how to do it. auth application use post_migrate to create permissions. So I can't use the signal because I can't be sure that my callback will be called after the auth. For the same reason, I can't do it in migration. -
How to apply a responsive size to an image in Django imagekit
I'm using Django-imagekit to cut down image file sizes in my website since their current sizes are around hundreds. Django-imagekit provides several ways, but I can't use the way done in Django models because I already have about a thousand of images. They need me to upload images to get converted images with smaller sizes. So, using the thumbnail template tag seems the only way for me right now. However, I'm confused about setting responsive sizes of images in the template tags. {% thumbnail "100x160" pic.photo %} Like you see the above code, it requires me to put some specific size as a string format, and this forcibly cuts my images to make them fit into the size. How can I set a flexible size in the template tag?