Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(1062, "Duplicate entry '2' for key 'user_id'")
I am trying to update a profile by cropping the image, after cropping the image it is giving me a base64 string which i have to covert it into the image and store on the server as well as its url in the database. I am getting the image on the server but unable to store its url in the database. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.FileField(default='default.jpg', upload_to='profile_pics') def __str__(self): return self.user.username def save(self, *args, **kwargs): #super(Profile, self).save(*args, **kwargs) super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) forms.py class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] views.py #profile view @login_required def profile(request): #if any changes POST data if request.method == 'POST': image_data = request.POST['image'] format12,img = image_data.split(';base64,') ext = format12.split('/')[-1] imageObj = ContentFile(base64.b64decode(img+"==")) file_name = "myphoto."+ext #print(file_name) #Profile.image = data #Profile.save(file_name, data, save=True) #Profile.save() profile = Profile() profile.user_id = request.user.id #profile.image= imageObj u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES,instance=request.user.profile) #check if both forms are valid if u_form.is_valid() and p_form.is_valid(): u_form.save() # if yes Save profile.image.save(file_name, imageObj) profile.save() #p_form.save() # if yes save messages.success(request, format('Your Profile has been updated.')) return redirect('profile') else: u_form = UserUpdateForm(instance=request.user)#instance … -
Upgrade Django project to Python3 - migrations fail
I have a Django project which has been developed with Python2.7, it is currently using Django version 1.10. I am now in the process of upgrading - first to Python3, and then afterwards I will do the Django upgrade. When I make Python3 virtual environment and run the tests: venv bash% ./manage.py tests I get a massive traceback: Traceback (most recent call last): File "./manage.py", line 9, in <module> execute_from_command_line( sys.argv ) File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/core/management/commands/test.py", line 72, in handle failures = test_runner.run_tests(test_labels) File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/test/runner.py", line 549, in run_tests old_config = self.setup_databases() File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/test/runner.py", line 499, in setup_databases self.parallel, **kwargs File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/test/runner.py", line 743, in setup_databases serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True), File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 70, in create_test_db run_syncdb=True, File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 130, in call_command return command.execute(*args, **defaults) File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 202, in handle targets, plan, fake=fake, fake_initial=fake_initial File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 97, in migrate state = self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/hove/sleipner/venv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 132, in … -
Create Model field based on existing models
I am currently working to implement review app in Django. In models.py of this review app: from salon.models import salon from services.models import Service from packages.models import Packages MODEL_OBJECTS = ( ('salon':salon), ('service':service), ('package':package), ) class Reviews(models.MODEL): user = models.ForeignKey(User, verbose_name=_("user"), on_delete=models.CASCADE) comment = models.TextField(_("User Comment")) rating = models.IntegerRangeField(min_value=1, max_value=5, blank=True) rate_object = models.CharField(_("Model Choice") choices=MODEL_OBJECTS,default='salon') rate_object_id = models.IntegerField(_("rate_object_id")) i want rate_object to contain model for which the rating is being done and rate_object_id to contain the instance id of the model selected in rate_object. I am not able to think forward on implementing this. any help will be helpful, Thanks -
Typescript, --outFile argument and "Cannot find module"
I'm trying to use vuejs/typescript with django and django-compressor. I have this files /project-root/tsconfig.json /project-root/packages.json /project-root/static/main.ts File content tsconfig.json { "compilerOptions": { "target": "es5", "strict": true, "module": "es2015", "moduleResolution": "node" } } packages.json { "name": "project", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "vue": "^2.5.21", "vue-class-component": "^6.3.2", "vue-property-decorator": "^7.2.0" } } main.ts import Vue from 'vue' export const app = new Vue({ el: '#app', data: { message: 'Hello Vue!' } }); So when I run command tsc --outFile static/main.js --module amd static/main.ts I got the following error static/main.ts:1:17 - error TS2307: Cannot find module 'vue'.. How to properly setup typescript and use it with --outFile argument? -
Nginx Gunicorn Django -- upstream prematurely closed connection Error
I am pretty new to NGINX, GUNICORN, DJANGO setup. I am using supervisor between nginx, gunicorn. Without NGINX, setup works well with supervisor and gunicorn and I can see the result through my server IP. But when i am using nginx to serve the requests, the error "upstream prematurely closed connection while reading response header from upstream" occurs. please anyone help me in this? Supervisor command I am using: sudo /path/to/gunicorn/gunicorn -k gevent --workers 4 --bind unix:/tmp/gunicorn.sock --chdir /path/to/application wsgi:application --timeout 120 -
Reset password of custom users model on django rest auth?
I am using custom user in django rest framework for authentications and now I need to reset password but I am not able to do that. url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/password/reset/', include('rest_auth.urls')), url(r'^rest-auth/password/reset/confirm/<uidb64>/<token>/', include('rest_auth.urls')), I am using these url and this is working for default django user but not woking for custom users. So, How can I reset the password of my custom users on django rest auth. -
Getting task timeout error when accessing the django application which is deployed on AWS
I have my django application deployed on AWS. It is working fine as of now but when i tried to hit an api which is deployed on ec2 instance it is showing task time out error.is there any way to overcome it. [1556766665330] [DEBUG] 2018-12-14T05:46:25.330Z 98072431-ff63-11e8-97db- 2d7bd216d81f Starting new HTTP connection (1): 1.2.3.4:3000 [1544799995279] 2018-12-14T05:46:55.279Z 98072431-ff63-11e8-97db-2d7bd216d81f Task timed out after 30.03 seconds my django application is deployed on aws through zappa -
{ % extends parent _ template|default:"base.html" % } vs {% extends "base.html" %} in Django?
What is the difference between { % extends parent _ template|default:"base.html" % } vs {% extends "base.html" %} in template inheritance in django ? I've seen both being used. -
How to read a file in my local storage as in memory and attach it into email?
This snippet is to generate an xlsx file and then attach that file into an email Note: I'm not saving any file, it is in memory. import io a = io.BytesIO() from django.core.mail import EmailMessage import xlsxwriter workbook = xlsxwriter.Workbook(a, {'in_memory': True}) worksheet_s = workbook.add_worksheet('abcd') worksheet_s.write(0, 0, 'Hello, world!') workbook.close() a.seek(0) email = EmailMessage('Subject', 'Body', 'sentby@mailinator.com', ['sentto@mailinator.com']) email.attach('file.xlsx', a.getvalue()) email.send() Similarly to this, I want to attach a file in my storage to email but first want to open it in in memory. As I am Trying to write a generic code to send Email from one place whether it has attachments(self-generated file or file in storage) or not. Thanks in advance. -
How to deploy Django under subdirectory with correct mod_rewrite?
To install Django app under root folder is much easier but I have a project that I have to set up an app under a subfolder although I know most of the experienced developer wouldn't do it this way. I have a website hosted with NameCheap, http://www.sctongye.com , a WordPress blog is installed under the root folder, now I'm trying to set up a Django app under a subfolder thru cPanel http://sctongye.com/thoughts/ with settings.py shown below STATIC_URL = 'thoughts/static/' # on server STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) Everything seems to be working fine, but when I tried to login thru admin http://sctongye.com/thoughts/admin/ or http://sctongye.com/thoughts/xadmin/ (another admin I installed) the path of all the static files are wrong, as shown below: GET http://sctongye.com/thoughts/xadmin/thoughts/static/thoughts/static/xadmin/vendor/bootstrap/css/bootstrap.css 404 (Not Found) GET http://sctongye.com/thoughts/xadmin/thoughts/static/xadmin/css/themes/bootstrap-xadmin.css 404 (Not Found) GET http://sctongye.com/thoughts/xadmin/thoughts/static/thoughts/static/xadmin/css/xadmin.main.css 404 (Not Found) As you can see, tons of duplicated static name in the path link. In order to have the subfolder Django app work, I'll have to set up a .htaccess file right under the subfolder # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/username/thoughts" PassengerBaseURI "/thoughts" PassengerPython "/home/username/virtualenv/thoughts/3.6/bin/python3.6" RewriteCond %{REQUEST_URI} !^/thoughts (<== I had to add this line to make it work, but I … -
Big O Notation: Using multiple forloops within Django template VS multiple queries using a filter in views.py
This is a specific question based on an attempt to increase performance speeds when querying data. So I was trying to figure out within a Django template itself, how to break a conditional on the first attempt. It seems that it is not possible, and the suggestions were all to use the views.py for the logic instead. This led me to try filtering based on a condition being met. In my example, I have two scenarios that I'm comparing. (1) In the first one, I have one query inside my views.py to get all items. Naturally, Item is a schema I have in my models. Anyway, inside the template I want to render, I have the context being passed and have 11 separate forloops all iterating over the same all_items loop. Then based on the condition (ie item.category), the appropriate html is rendered. Again, what I wanted to do was have 1 loop, and then based on the condition, rendering to the appropriate places. Unfortunately, I'm not able to break the loop in the template after the condition to not over-render html I don't want on each successive iteration. So this led me the next scenario: (2) In my views … -
how to send a form to html in django
I am trying to send a form to html using django. this is the form from django import forms class contactForm(forms.Form): name = forms.CharField(required=False, max_length=100,help_text='100 characters max.') email = forms.EmailField(required=True) comment = forms.CharField(required=True, widget=forms.Textarea) The view file is from django.shortcuts import render from .forms import contactForm # Create your views here. def contact(request): form = contactForm(request.POST or None) if form.is_valid(): print (request.POST) context = locals() template = 'contact.html' return render(request, template, context) and the html file which is named correctly is, {% extends 'base.html' %} {% block content %} <h1> Contact </h1> <form method='POST' action=''> {% csrf_token %} {{ form.as_p }} <input type='submit' value='submit form' class='btn btn-default' /> </form> {% endblock %} When you visit the page the only thing that shows up is the h1 tag how do i fix this? -
Django DateField TypeError expected string or bytes-like object
I'm a Django newbie, I'm getting an error when submitting and attempting to save the updated value selected in one of the dropdown lists. I think it's related to the date being passed to the form, but I'm unsure how to fix this. The trace back error : match = date_re.match(value) TypeError: expected string or bytes-like object My models.py from django.db import models class Person(models.Model): person_name = models.CharField(max_length=50, unique=True) person_dept = models.ForeignKey('Department', default='1', on_delete=models.CASCADE) number = models.CharField(max_length=10, unique=True) email = models.EmailField(max_length = 100, unique=True) class Meta(): db_table = 'person' def save(self, *args, **kwargs): for field_name in ['person_name']: val = getattr(self, field_name, False) if (val): setattr(self, field_name, val.title()) super(Person, self).save(*args, **kwargs) def __str__ (self): return self.person_name class Department(models.Model): dept_desc = models.CharField(max_length=100, unique=True) class Meta(): db_table = 'dept' def __str__ (self): return self.dept_desc class Roster(models.Model): roster_date = models.DateField() oss_person = models.ForeignKey('Person', on_delete=models.CASCADE, related_name='+', limit_choices_to={'person_dept': 1},) nw_person = models.ForeignKey('Person', on_delete=models.CASCADE, related_name='+', limit_choices_to={'person_dept': 2},) class Meta(): db_table = 'roster' def __str__(self): return str(self.roster_date) My forms.py from datetime import datetime, timedelta from django import forms from django.core import validators from roster.models import Roster, Person, Department class UpdateRosterForm(forms.ModelForm): class Meta(): model = Roster fields = '__all__' labels = { "roster_date":"Start On Call Date", "oss_person":"Servers", "nw_person":"Networks", } … -
django how to pass bookinstance.id for a particular book to function-based view
I have a django library application, wherein the customer can view a book from a book list(and is redirected to book_detail.html page), and if the book is available, can borrow the book. book_detail.html - borrow book button {% for copy in book.bookinstance_set.all %} {% if copy.status == 'a' %} <form method="POST" action ="{% url 'borrow_book' book_instance.id%}" enctype="multipart/form-data"> # none of these alternatives work # OR 'borrow_book' book_instance.id # OR 'borrow_book' book_instance.pk # OR 'borrow_book' book_instance.book_id # OR 'borrow_book' book_instance.book.id {% csrf_token %} <button type="submit" class="btn btn-success">Borrow the book</button> </form> {% endif %} {% endfor %} This is the urls.py routing within the app project path('book/<uuid:pk>/borrow/', views.borrow_book, name='borrow_book'), And the function borrow_book is invoked: def borrow_book(request, pk): book_instance = get_object_or_404(BookInstance, pk=pk) if request.method == 'POST': if request.user.is_authenticated: book_instance.borrower = request.user book_instance.due_back = datetime.date.today() + datetime.timedelta(weeks=3) book_instance.status = STATUS_ON_LOAN book_instance.save() return HttpResponseRedirect(reverse('dashboard_customer')) context = { 'book_instance': book_instance, } return render(request, 'catalog/book_detail.html', context) When user clicks on Borrow book button, I need to create an instance of the book hence I am using the book_instance model. Here is the relation between the Book and BookInstance model: class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) class BookInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique … -
Check/verify if in Django template, there are real numbers in decimal places, and if zeros, round off
I couldn't seem to find a specific answer for this question. So, my question differs based on two different scenarios: (1) In my Django template, can I use some kind of filter to round real numbers in the decimal position, to only 2 digits, but still round any zeros to the nearest whole number/integer? (ie $1.25 and 1.00 would look like $1.25 and $1 respectively) ** Unfortunately, |floatformat:2 includes the zeros (2) If the above is not possible, is there some kind of conditional where I can check beforehand in the Django template if there are real numbers in the decimal position instead of zeros, and perform some kind of logic as a result? Thanks in advance! -
Django & ReactJS no template rendered
Already 24 hours and still can't figure out, template not being rendered whenI browse 127.0.0.1:8000 or localhost:8000 in my browser. I configured this with react js as my frontend please see my path in the picture. I am printing in my views and it shows in my terminal, but when in the browser, I can't see my template, only blank page. settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'webpack_loader', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, "templates") ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/', # end with slash 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats-local.json'), 'POLL_INTERVAL': 0.1, 'TIMEOUT': None, } } STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'app/static'), ] urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('app.urls')), ] **urls.py ** [inside app folder] from django.conf.urls import url, include from .views import * urlpatterns = [ url(r'^$', homePage, name = 'home_page'), ] views.py from django.shortcuts import render def homePage(request): # landing page context = {} template = 'base.html' print('testing terminal') #this comment in termninal is printing when I … -
How to fail any Django REST Framework requests with unknown parameters?
Django REST Framework API ignores any unknown parameters. This has led to several issues. For example, when a model filter was missing, a client received all records rather than the single one they were expecting. How can I force DRF to return 400 Bad Request whenever an API call includes an unknown parameter? -
How are my Heroku web dynos executing code outside of a standard HTTP request loop?
I'm running a Django application on Heroku with logging via Papertrail. I'm seeing a peculiar phenomenon in my Papertrail logs where web dynos are executing code outside of the regular HTTP request/response loop. To explain further, I have a function that is highly resource intensive and takes much longer than 30 seconds. This function isn't triggered inside any Django view handler. However, the papertrail logs from my web dynos clearly show that this function is being executed. I'm confident that this function isn't being triggered by an actual HTTP request because: 1) I've thoroughly code reviewed the URL's that were called up to 30s prior to these logs and none of them call this function 2) The function executes for much longer than 30s. If it was being called from within a HTTP request, it would have terminated with a H12 timeout error. How is this possible? I've pasted my Procfile below in case it helps add context. web: gunicorn -t 6000 project.wsgi --log-file - worker: python -u manage.py rqworker queue_name worker-hp: python -u manage.py rqworker queue_name2 clock: python clock.py -
How do i create seperate tasks for every objects with celery beat in Django models
Let's assume we have following model field: class Project(models.Model): project_name = models.CharField(max_length=200,unique=True) project_scan = models.IntegerField() ### Scan interval project_status = models.BooleanField() ### To Enable "Scan" or Disable "Scan" Tasks Assume We have 2 Project Objects: 1. Project(project_name='test1',project_scan=5) ### Scan `test1` every `5` hour 2. Project(project_name='test2',project_scan=10) ### Scan `test2` every `10` hour Tasks.py @task(name='project_tasks') def Project_Tasks(): get_all_projects = Project.objects.all() for each_project in get_all_project: if each_project.project_status == True: ### Checking if it "Scan" is allowed. get_interval = each_project.project_scan get_name = each_project.project_name print(get_name) My Question : How do i run tasks on each object based on given project_scan Interval ? , Since Celery beat takes Tasks name as argument to perform scan like: PeriodicTask.objects.create(interval=given_interval, name='I dont know', task='project_tasks', ) How do i create separate instance for each project task ? I Tried creating intervalSchedule field in models.py but didn't worked: class Project(models.Model): project_name = models.CharField(max_length=200,unique=True) project_scan = models.IntegerField() ### Scan interval project_status = models.BooleanField() ### To Enable "Scan" or Disable "Scan" Tasks schedule = IntervalSchedule() -
How to set dynamic page_size in DRF PageNumberPagination
In class PostByFilters, I'm getting limit as a url parameter, and I want to assign the value into page_size in class BasicSizePagination. I tried to use global variable outside of the two classes, but it didn't work. Is there anyway reinitialize the BasicSizePagination in PostByFilters so that I can directly assign the value in PostByFilters? class BasicSizePagination(pagination.PageNumberPagination): page_size = 10 class PostByFilters(ListAPIView): serializer_class = serializers.PostSerializer pagination_class = BasicSizePagination def get_queryset(self): limit = self.request.query_params.get('limit', None) ... return queryset -
How To Build a DRY Image Gallery - in Django
I've been tinkering with a small image gallery for my project for a few days now, but I feel that I'm not going about it in a very pythonic manner thus far in terms of this part of the project. A lot of questions have risen during the tinkering, alas being new to python and django I cannot immediately see how I ought to go about improving what I'd like to improve in the code. Here's the user profile model; I reckon it will sort of jump at you what I mean: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from PIL import Image, ImageOps from ckeditor_uploader.fields import RichTextUploadingField class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_visible = models.BooleanField(null=True) activation_key = models.CharField(max_length=120, blank=True, null=True) name = models.CharField(max_length=30, blank=True, null=True) surname = models.CharField(max_length=30, blank=True, null=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics') slogan = models.CharField(max_length=250, blank=True, null=True) bio = RichTextUploadingField( external_plugin_resources=[( 'youtube', '/static/ckeditor/ckeditor/plugins/youtube/', 'plugin.js' )], blank=True, null=True, ) phone = models.CharField(max_length=20, blank=True, null=True) reddit = models.CharField(max_length=30, blank=True, null=True) facebook = models.CharField(max_length=30, blank=True, null=True) twitter = models.CharField(max_length=30, blank=True, null=True) youtube = models.CharField(max_length=30, blank=True, null=True) linkdin = models.CharField(max_length=30, blank=True, null=True) img_1 = models.ImageField(default='default.jpg', upload_to='images') img_2 = models.ImageField(default='default.jpg', upload_to='images') img_3 … -
Acces data from other table - Foreign Key in Django Rest Api - Unknown column
I created Django Rest Models from existing MySQL database with inspectdb. I have two models, and I want to access some data from other model. My models: class Impreza(models.Model): year = models.IntegerField() tytul = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = '2006_impreza' class Description(models.Model): year = models.IntegerField() year_id = models.IntegerField() id_imprezy = models.IntegerField(blank=True, primary_key=True) class Meta: managed = False db_table = '2006_description' My serializer: class ImprezaSerializer(serializers.ModelSerializer): desc = serializers.StringRelatedField(many=True) class Meta: model = Impreza fields = ('year', 'tytul', 'desc') My problem is that Django is searching for id named 'impreza_id', but it exists with other name - 'id_imprezy'. As you can see, I tried to give 'id_imprezy' a 'primary_key=True' to tell Django that this is the right name but it doesn't work. It still gives me error: (1054, "Unknown column '2006_description.impreza_id' in 'field list'"). In my database both tables have id, but it doesn't show up in the model. I read that Django isn't showing id columns in models. How can I do it right? How to add foreign key? Sorry, but I'm realy new to Django ;-) -
How add photo encodings to db with django?
I try but it doesn't work... My model: class Staff(models.Model): photo = models.FileField() encodings = models.TextField() def get_encodings(self): enc = face_recognition.face_encodings(self.photo) return enc def save(self, *args, **kwargs): self.encodings = self.get_encodings() super(Staff, self).save(*args, **kwargs) The error which i have when try to add new object __call__(): incompatible function arguments. The following argument types are supported: 1. (self: dlib.fhog_object_detector, image: array, upsample_num_times: int=0) -> dlib.rectangles Invoked with: <dlib.fhog_object_detector object at 0x0000023D8CD9E570>, <FieldFile: photo_2018-12-05_23-09-20.jpg>, 1 -
Successful saving in post_ajax with status code 200 but not save on django database
I would like to ask if what’s wrong if your application returns status code 200 then it won’t saved on backend. Here’s the code of the CBV. def post_ajax(self, request, *args, **kwargs): ..... if fetch_pk: form = SomeForm(data=self.request.post()) else: form = SomeForm(data=self.request.post(), instance=fetch_pk if form.is_valid(): fetcher = form.save() #throws json response I tried to print self.request.post() the data is coming through and status is okay but the problem is it is not saved. And there’s no error being thrown. Thanks in advance -
Django logging only works when restart
I've asked a similar questions before, but having trouble getting more information on what the problem is. I have a Django app, and its running with channels. So, Django, Daphne, Channels, NGINX, Redis I have logging configured like this: # Logging LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'propagate': True, 'level': 'INFO' }, 'dashboards': { 'handlers': ['console'], 'propagate': False, 'level': 'DEBUG', }, }, } Channels: CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, "ROUTING": "app.routing.channel_routing", }, } In my view: import logging loger = logging.getLogger(__name__) def index(request): loger.debug(":dsfasdfasdfasdfasdfasdfasdfasdfasdfasdf") return render(request, 'site/index.html', context) Using supervisor to manage service: [program:Daphne] environment=PATH="/opt/site/venv/bin" command=/opt/site/venv/bin/daphne -b 0.0.0.0 -p 8000 site.asgi:channel_layer --proxy-headers -v2 directory=/opt/site/site autostart=true autorestart=true redirect_stderr=true stdout_logfile=/tmp/daphne.out.log [program:Worker] environment=PATH="/opt/site/venv/bin" command=/opt/site/venv/bin/python manage.py runworker -v2 directory=/opt/site/site process_name=%(program_name)s_%(process_num)02d numprocs=10 autostart=true autorestart=true redirect_stderr=true stdout_logfile=/tmp/workers.out.log I can see the worker logs upon request to the page, and I can also see the exceptions hit the log (/tmp/workers.out.log). 2018-12-13 21:36:22,396 - DEBUG - worker - Got message on http.request (reply daphne.response.SrXmOkzSNt!bUdAxibnQp) 2018-12-13 21:36:22,396 - DEBUG - runworker - http.request 2018-12-13 21:36:22,397 - DEBUG - worker - Dispatching message on http.request to channels.staticfiles.StaticFilesConsumer …