Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle multiple variables for the same parameter name (for checkbox)?
I'm writing a code for quiz app, which is having multiple choice for each question.According to my requirement one question may contains multiple correct answer. i'm able to check for single answer if its radio button rather than checkbox. But i need checkbox instead of radio. So i given checkbox for multiple selection. i used request.POST.getlist('choice') which returns only the order of selection. I can't able to check it with my model whether its correct answer or not. views.py def checkanswer(request, question_id): question = TestQuestion.objects.get(pk=question_id) #for single answer checking(if its radio button) i used the following #selected_choice = question.testchoice_set.get(pk=request.POST.get('choice')) a = request.POST.getlist('choice') #print(selected_choice.is_answer) #if selected_choice.is_answer == 'Yes': #return HttpResponse('Right') return HttpResponse('Wrong') test.html <form action="{% url 'polls:checkanswer' question.id %}" method="post"> {% csrf_token %} {% for choice in question.testchoice_set.all %} <input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_opt }}</label><br /> {% endfor %} <input type="submit" value="Vote" /> </form> I expect, each option chooses by the user need to be checked with data base whether its right or not. -
Pdfkit and Django On CentOS 6: No wkhtmltopdf executable found: ""
I am able to convert an html file to pdf using pdf kit just fine, but if run within Django I get the error No wkhtmltopdf executable found: "" I installed from the rpm and then used pip to install the pdfkit config= pdfkit.configuration(wkhtmltopdf="/usr/local/bin/wkhtmltopdf") pdfkit.from_file(html_file,pdf_file,config) I could not find any solution online and i tried uninstalling and reinstalling the libraries -
No Testimony matches the given query
I am trying to set up a comment function for each individual instance with valid id's. But i am getting "No Testimony matches the given query" by clicking the link below. Any help is appreciated. template <a href="{% url 'commentform' testimony.id %}">Make a comment</a> urls urlpatterns = [ ... path('<int:id>/commentform/', views.CommentForm, name='commentform'), ] Views def CommentForm(request, id=None): print('1') testimony=get_object_or_404(Testimony, id=id) print('2') print('3') form=CommentForm(request) if request.method=='POST': form=CommentForm(request.POST or None, request.FILES or None) print('d') if form.is_valid(): print('e') comment=form.save(commit=False) comment.testimony=testimony comment.save() return redirect('details', id=testimony.id) else: form=CommentForm(request.POST or None, request.FILES or None) return render(request, 'comment_form.html', {'form':form}) -
Relationship among many Field in Django
I am doing my college project Invigilator Management System. For this, I want to create Exam model , Exam contains many dates (ex. date-1,date2 ) and for each day there are many shift and for each shift there should be many rooms. I don't know how to relate all this from Django Model. SO, If I enter Exam Name , Date, Shift and Room, I should be getting single object and I have to assign Invigilator to this object. Please help me with this. -
PUT request not appearing in allowed requests using ModelViewSet
I'm not able make put request using ModelViewSet like in the documentation. My views, serializers are as below class PostsViewSet(viewsets.ModelViewSet): queryset = PostsModel.objects.all() serializer_class = PostsSerializer class PostsSerializer(serializers.ModelSerializer): class Meta: model=PostsModel fields=('id','title', 'author', 'body') PUT method is there in allowed methods as you can see in the picture. And this is my urls.py router = DefaultRouter() router.register('', PostsViewSet) urlpatterns = [ path('', include(router.urls)) ] -
Resize an image in UpdateView
I have an UpdateView where the user can update/create their profile details. The details include the profile picture, bio, and gender. I want to be able to take the user's uploaded profile image, crop it, and then save it. However, in my current implementation it only saves the image to a path I specify and that's it. I have tried to add a save method in my models view to resize the image, however, I get this error: 'Image' object has no attribute '_committed' Here is my code: class Profile(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.CharField(max_length=200, null=True) avatar = models.ImageField(upload_to="img/path") gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) def save(self, *args, **kwargs): if self.avatar: image = Image.open(self.avatar) self.avatar = image.resize((200, 200), Image.ANTIALIAS) super(Profile, self).save(*args, **kwargs) UpdateView class ProfileSettings(UpdateView): model = Profile template_name = 'profile/settings.html' form_class = ProfileForm success_url = reverse_lazy('profile:settings') def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) if form.is_valid(): bio = form.cleaned_data['bio'] gender = form.cleaned_data['gender'] avatar = form.cleaned_data['avatar'] Profile.objects.update_or_create(user=self.request.user, defaults={'avatar':avatar, 'bio':bio, 'gender':gender}) return HttpResponseRedirect(self.success_url) -
problems integrating bootstrap and django
i am trying to integrate Bootstrap with Django by copying and pasting the folders from Bootstrap to static folder. But I'm not able to get access to the Bootstrap.css file. It shows 404 error. I did everything as documentation says , but no luck . i am using django 2.x , but I also tried /static , and <% static %>. . ├── blackowl │ ├── blackowl │ │ ├── admin.py │ │ ├── apps.py │ │ ├── __init__.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ └── views.cpython-36.pyc │ │ ├── tests.py │ │ └── views.py │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ ├── settings.cpython-36.pyc │ │ ├── urls.cpython-36.pyc │ │ └── wsgi.cpython-36.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── index.html ├── manage.py ├── static │ ├── bootstrap │ │ ├── css │ │ │ └── bootstrap.min.css │ │ └── js │ │ └── bootstrap.min.js │ ├── css │ │ ├── Login-Form-Dark.css │ │ └── styles.css │ ├── fonts │ │ ├── ionicons.eot │ │ ├── ionicons.min.css │ │ ├── ionicons.svg │ … -
How to set up the Django ModelForm MultipleChoiceField widgets like on the admin?
This is the admin form that we want: Hot to set our widget in forms.py to get the form like the admin? -
Django css no longer working for print after deleting static file
I was developing a website using django and the css was working ^retty fine ,i deleted the static directory after facing a problem with loading a picture then i created it once again , once i refreshed the css on the page it no longer worked . this is my setting.py file : """ Django settings for ecommerce project. Generated by 'django-admin startproject' using Django 2.0.7. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os from os.path import dirname, join, abspath # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] #static files upload_to # MEDIA_ROOT = join(__dir__, 'static') # MEDIA_URL = '/media/' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'commandes', 'contact', 'evenement', 'templates', 'static', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ecommerce.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates/')], 'APP_DIRS': True, … -
unable to run manage.py
I am a student (using Ubuntu 18.04) learning django and mysql. I have a problem when I try to run manage.py. When I type: 'python manage.py runserver', then I get an error message at the end saying django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: NO)"). Is there any a solution for this problem? Thank you. -
Django template tag variables are not working
{{ user }} shows users only in the index.html home page. In my other pages {{ user }} doesn't work. I tried to put a simple "Test Text" and the text doesn't show up as well until I delete {% extends 'locator/base1.html' %} Here is my base1.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>EME</title> <!-- Bootstrap core CSS --> <link href="{% static 'locator/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="{% static 'locator/vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'> <!-- Plugin CSS --> <link href="{% static 'locator/vendor/magnific-popup/magnific-popup.css' %}" rel="stylesheet"> <!-- Custom styles for this template --> <link href="{% static 'locator/css/creative.min.css' %}" rel="stylesheet"> </head> <body id="page-top"> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav1"> <div class="container"> <a class="navbar-brand js-scroll-trigger" href="{% url 'index' %}#page-top">Home</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="{% url 'index' %}#about">About</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="{% url 'index' %}#areas">Areas</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="{% url 'index' %}#locate">Church Locator</a> </li> <li class="nav-item"> … -
django query compare two models
I have three models, i want to display users who apply for leave but i don't know how to accomplish that. The relationship between user to newleave is one to many and the leave balance to newleave is many to many and user to balance is one to one. i only want to display data from user and newleave class newleave(models.Model): user=models.ForeignKey(User,default='',on_delete=models.CASCADE) leave_balance=models.ManyToManyField(Leave_Balance) leave=( ('annual','annual'), ('sick','sick'), ) Leave_type=models.CharField(max_length=100,choices=leave,blank=False,default='') dp=( ('test','test'), ('test1','test1'), ) department=models.CharField(max_length=100,choices=dp,blank=False,default='') Start_Date=models.DateField(null=True, blank=False, default=None) End_Date=models.DateField(null=True, blank=False, default=None) Total_working_days=models.FloatField(null=True, blank=False, default=None) def __unicode__(self): return self.Leave_type class Leave_Balance(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True,) Outstanding_balance=models.FloatField(null=True, blank=True, default=None) Monthly_entitlement=models.FloatField(null=True, blank=True, default=None) Monthly_consumption=models.FloatField(null=True, blank=True, default=None) Leave_current_balance= models.FloatField(null=True, blank=True, default=None) Month=models.CharField(max_length=100,default="",null=True) Year=models.CharField(max_length=100,default='') def __unicode__(self): return self.Year -
urls.E004 path not working in Python Django
So, everytime I try to run the server it sends this error: ?: (urls.E004) Your URL pattern b'["Aquaman", "Glass", "Bumblebee", "Polar", "Bohemian Rhapsody", "Widows", "Creed II", "Escape Room", "Dragon Ball Super: Broly", "Mortal Engines", "6.9", "6.9", "6.5", "6.4", "8.2", "6.7", "6.6", "6.6", "7.5", "5.9", "297802", "450465", "424783", "483906", "424694", "401469", "480530", "522681", "503314", "428078", "143", "129", "114", "119", "135", "130", "130", "100", "101", "128", "Action", "Thriller", "Action", "Action", "Drama", "Crime", "Drama", "Horror", "Action", "Science Fiction"]' is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances. This is the code import requests import json from django.conf.urls import url, include, re_path from django.contrib import admin from django.http import JsonResponse, HttpResponse from django.urls import path def lookForValue(value, list, moves, number_of_values): i = 0 valuesFound = [] for string in list: if string == value and i < number_of_values: pointer = list.index(string) valuesFound.append(list[pointer + moves]) i += 1 list[pointer] = None return valuesFound def getData(apiurl): payload = {} data = requests.request("GET", apiurl, data=payload) data = data.text data = data.split('\"') return data url = "https://api.themoviedb.org/3/discover/movie?api_key=31563efa3563f61e00e5f0e2ed88c4bb&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1" list = getData(url) titles = [] release_dates = [] ratings = [] uids = [] runtimes = [] genres = [] total = [] i = 0 … -
"string indices must be integers" when trying to load test yaml data
I'm trying to figure out how to load test data in Django and Python 3.7. I have the below YAML file website: - id: 1 path: "/test" Pretty basic. In my unit test, I attempt to load it using management.call_command('loaddata', 'test_data.yaml', verbosity=0) But this results in teh below error. What's wrong with my YAML file taht would cause the below error? ====================================================================== ERROR: test_add_articlestat (mainpage.tests.FirstTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/serializers/pyyaml.py", line 73, in Deserializer yield from PythonDeserializer(yaml.load(stream, Loader=SafeLoader), **options) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/serializers/python.py", line 91, in Deserializer Model = _get_model(d["model"]) TypeError: string indices must be integers -
Why my custom.css file isn't modifying my materialize.css?
I wanted to modify the grid system, add some borders to rows, columns etc. I know, that I should create separate folder (in my case it's custom.css) and write it there, but it looks like my site sees this file, but doesn't see changes in there. I tried this in my custom.css .row-custom { border: 5px solid #42a5f5; } and just add row-custom to row class Like this <div class="row row-custom"> <div class="col s12 ">This div is 12-columns wide on all screen sizes</div> <div class="col s6 ">6-columns (one-half)</div> <div class="col s6">6-columns (one-half)</div> </div> If I add .row-custom into my header in layout.html it works properly. Here's my custom.css file: https://imgur.com/sNy6z9G and here's my custom.css view in sources from the website: https://imgur.com/zXKiHxG (these css I also had to put into header because otherwise it wasn't working, I deleted it earlier) My header: https://imgur.com/fAI72el Also, my materialize.min.css works correctly. I have no idea why there is no changes in sources custom.css, what I'm doing wrong? -
How do I convert strings into objects in Django or python?
has been defined: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('name', 'account', 'mobile') then i define tem_str = 'UserSerializer' . how to convert tem_str to a UserSerializer object and get its Meta content in python or django class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('name', 'account', 'mobile') -
Weird POST request posting csrf_token as password
I have a view for my Django API that signs up users. From my client-side ReactJS code, I have passed in a CSRF token, but when I call it I get: [30/Jan/2019 23:45:04] "OPTIONS /newuser/ HTTP/1.1" 200 108 Rather than a successful POST call. Here is the Django code: path('newuser/', views.SignUp.as_view()), API View: class SignUp(APIView): parser_classes = (JSONParser,) permission_classes = (AllowAny,) def post(self, request, format = None): username = request.data['username'] password = request.data['password'] user = User.objects.create_user(username = username, password = password) login(request, user) returnData = UserSerializer(user) return Response(returnData.data) Here is the client-side. loginSubmit() { var csrftoken = document.getElementById('token').getAttribute('value'); console.log(csrftoken); fetch('http://localhost:8000/newuser/', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ username: this.state.username, password: this.state.password, }), }) } This is my React POST form code, just in case: const LoginScreen = (props) => { return ( <div> <form onSubmit={props.loginSubmit}> <CSRFToken /> <label className="loginLabel"> <h3>Username</h3> <input name="username" style={{position: 'relative', height: '50%', top: '50%'}} type="text" value={props.value} onChange={props.handleChangeUserName} /> </label> <label className="loginLabel"> <h3>Password</h3> <input name="password" type="text" value={props.value} onChange={props.handleChangePassword} /> </label> <button type="submit" id="loginButton" className="loginButton"><Link to="/app">Login</Link></button> </form> </div> ); } -
Block content on admin template not overridden
I extended django admin site according to Customize Django admin template and official doc {% extends 'admin/base_site.html' %} {% load static %} {% block branding %} <div class="head"> <h1 id="name">Admin Dashboard abc</h1> </div> {% endblock %} {% block content %} <h2>Custom Content</h2> {% endblock %} {% block nav-global %} <img class="brand_img" src="{% static 'images/ic_launcher.png'%}" width="50" height="50" alt="logo logo"> {% endblock %} "block branding" & "block nav-global" is displaying correctly but "block content" is not making any change to admin site. The official doc says.. If you want to use the admin layout, extend from admin/base_site.html: {% extends "admin/base_site.html" %} {% block content %} ... {% endblock %} And I did what the doc says but is not working. What am I doing wrong? -
How do I run Django unittests in PyCharm?
I'm using Python 3.7, Django, within PyCharm 2018.2.4. I have loaded my project in PyCharm and have opened my file, ./mainpage/tests.py, which is from django.test import TestCase from mainpage.models import ArticleStat, Article import unittest class TestModels(unittest.TestCase): fixtures = ['/mainpage/fixtures/test_data.yaml',] # Test saving an article stat that hasn't previously # existed def test_add_articlestat(self): id = 1 article = Article.objects.filter(id=id) self.assertTrue(article, "A pre-condition of this test is that an article exist with id=" + str(id)) articlestat = ArticleStat(article=article,elapsed_time_in_seconds=250,votes=25,comments=15) articlestat.save() article_stat = ArticleStat.objects.get(article=article) self.assertTrue(article_stat, "Failed to svae article stat properly.") I want to run this test file in PyCharm. I go to the "Run" menu and select "Run unit tests for Tests.models." But I get this error Error running 'Unittests for tests.TestModels': Can't find file where tests.TestModels declared. Make sure it is in project roo What do I need to do in PyCharm in order to run my tests within the IDE? -
Properly serialize a value so it is passed to CurrentUserField() properly
I started using Django REST this week, and I am running into something I do not understand. I building a POST that takes in the following payload: { "requestor":"naughtron", "test_name":"testName", "workers":"2" } The value for requestor in our data model is set to CurrentUserField() When the payload comes into the serializer class TestSuiteRequestSerializer(serializers.Serializer): requestor = what_do_use_here? test_name = serializers.CharField(required=True, allow_blank=False, max_length=100) workers = serializers.CharField(required=True, allow_blank=True, max_length=3) the following error is thrown database_1 | ERROR: null value in column "requestor" violates not-null constraint because I am believe it is not being serialized properly therefore the model has no idea what to do. I looked through the documentation and the current list of Serializer fields. Nothing seems to be helping. -
Django: Listing all permissions specific to a model, and listing them in a table
I'm having trouble listing all model-specific permissions in a table. I'm able to pull out permissions through {{ perms.account }} in the html, but it won't filter for permissions specific to the account model. Futhermore i want to list each permission in a html table, with the permissions description, and a checkmark if its granted: Permission1 Desc1 V <!-- Granted --> Permission2 Desc2 X <!-- Not granted --> I have tried for-looping all permissions, and filtering out the ones related to the model account, and then for looping to get the different rows in the table. This, however, just returned a long string of all permissions names. I have also tried the code bellow, but was not able to retrieve data in the html template through {{ permissions }}, {{ account.permissions }} or {{ permissions.account }} class cms_users_user_permissions(generic.DetailView): model = Account template_name = 'cms/users/cms-users-user-permissions.html' content_type = ContentType.objects.get_for_model(Account) permissions = Permission.objects.filter(content_type=content_type) views.py class cms_users_user_permissions(generic.DetailView): model = Account template_name = 'cms/users/cms-users-user-permissions.html' models.py class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) site = models.CharField(max_length=50, choices=(('all', 'all'), ('danielk', 'danielk')), blank=True) role = models.CharField(max_length=50, choices=(('Administrator', 'Administrator'), ('Moderator', 'Moderator'), ('Editor', 'Editor'))) phone_number = models.CharField(max_length=8) birth_date = models.DateField() street_adress = models.CharField(max_length=255) note = models.TextField(blank=True); zip_code = models.CharField(max_length=4) city = … -
Django Model Many-to-Many and Bridge Tables
I'm trying to understand how to properly setup my models in order to have a many-to-many relationship, I noticed that there is a ManyToManyField option while creating models but I can't seem to understand the logic of it and how to properly make it work. I'd like to share my code and explain along the way. from django.db import models class Major(models.Model): name = models.CharField(max_length=30, db_index=True) class School(models.Model): name = models.Charfield(max_length=50, db_index=True) majors = models.ManyToManyField(Major) class Professor(models.Model): ProfessorIDS = models.IntegerField() ProfessorName = models.CharField(max_length=100) ProfessorRating = models.DecimalField(decimal_places=2,max_digits=4) NumberOfRatings = models.CharField(max_length=50) school = models.ForeignKey(School , on_delete=models.CASCADE) major = models.ForeignKey(Major , on_delete=models.CASCADE) Notice that the School TABLE (Class) has a many-to-many for Majors, which is essentially what I want, the goal to have a database allowed to store multiple majors under an individual school. After doing some research I've come to conclusion that this doesn't make sense, it would be better to create a Bridge Table So I decided to create my model like so... from django.db import models class Major(models.Model): name = models.CharField(max_length=30, db_index=True) class School(models.Model): name = models.Charfield(max_length=50, db_index=True) class School_Majors(models.Model): school = models.ForeignKey(School, on_delete=models.CASCADE) major = models.ForeignKey(Major, on_delete=models.CASCADE) class Professor(models.Model): ProfessorIDS = models.IntegerField() ProfessorName = models.CharField(max_length=100) ProfessorRating = models.DecimalField(decimal_places=2,max_digits=4) NumberOfRatings … -
Django POST view called twice with jQuery
My post method of a view is executed twice every time when jQuery call it. However, the first call is successful and is handled completely correctly, but the second one has problem with request body and leads to exceptions. Here is my view code: class SingleView(View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): print('- SingleView Init!!!') return RawListsView.dispatch(self, request, *args, **kwargs) def post(self, request, obj_id, *args, **kwargs): print('- SingleView POST!!!') print(id(self), id(request)) instance = get_object_or_404(Contacts, pk=obj_id) body_unicode = request.body.decode('utf-8') j = json.loads(body_unicode) # ... work with DB ... Which is called by jQuery: $.ajax({ url: '/contacts/314', method: 'POST', data: "<data>", contentType: 'application/json', dataType: 'json', crossDomain: true }).done(function (data, textStatus, jqXHR) { if (data.code == 1) { location.reload(); } else { alert('Some problem!'); } }).fail(function (jqXHR, textStatus, errorThrown) { console.log("Error: " + errorThrown); console.log(jqXHR); console.log(textStatus); }); And this is the server output: - RawSingleView Init!!! - RawSingleView POST!!! 140662482468424 140662495531808 [30/Jan/2019 22:25:17] "POST /raw/1 HTTP/1.1" 200 11 - RawSingleView Init!!! - RawSingleView POST!!! 140662482482232 140662482467864 Internal Server Error: /raw/1 Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, … -
Could running a Heroku one-off dyno as `:detached` cause it to consume more memory?
When I run my management command in a detached one-off dyno, it exceeds the memory quota almost immediately. When I run non-detached, it works perfectly. I would like some insight as to how that could possibly be. Any answer that points to any documentation on this phenomenon would be amazing. This is for a Python management command (addfeederpolygons) that I estimate to use a few hundred megabytes of memory, as it does some intensive spatial joins with geodjango. Are there ways that the underlying code could perform differently in a detached one-off dyno vs. a non-detached one-off dyno? I expect the results to be the same, regardless of whether or not the dyno is running detached. But here is the actual output: When running un-detached $ heroku run -a kevala-api-stage python manage.py addfeederpolygons --geography 25 --overwrite › Warning: heroku update available from 7.0.33 to 7.19.3 Running python manage.py addfeederpolygons --geography 25 --overwrite on ⬢ kevala-api-stage... up, run.8817 (Standard-1X) initialized redis cache Imported all multipolygon data for 328922 Imported all multipolygon data for 329602 ...etc... this does not crash, and runs much faster than the other scenario... When running detached $ heroku run:detached -a kevala-api-stage python manage.py addfeederpolygons --geography 25 --overwrite … -
Typeerror: sequence item 0: expected str instance, Paragraph found
I am using below code to open a doc file and store the paragraphs as a string in a Django view. doc = docx.Document('media/%s'%(filename)) fulltext = [] for para in doc.paragraphs: fulltext.append(para) docdata1 ='\n'.join(fulltext) I am getting an error Typeerror: sequence item 0: expected str instance, Paragraph found