Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to specify dedicated sub domain for authentication views in Django Rest Framework
I'm building and API using DRF and will be using it with a React SPA. I've chosen session authentication for my project because of the following reasons: It's built-in to DRF, so no dependence on 3rd party developers (a lot of auth packages or their dependencies are not maintained) CSRF + Cookie protection Ability to use Secure and HTTPOnly cookies However, I'm aware that it's recommended that we use Django's authentication views for the authentication pages and the single page app for the post authentication API calls. In this scenario, there are some views (i.e. Login, Logout, Password Reset, Register) for which the server responds with HTML and the rest return JSON. I would like to use different subdomain for these views i.e. different subdomain for HTML views and different subdomain for the JSON views. I'm a Django newbie and would really appreciate some suggestions on the best way to handle the separation of subdomains. I have some idea that the few ways I could achieve this are: using django-hosts using django sites (although I'm not sure if the cookie made by one site, would work on the other) point 2 domains to my server and handle the separation bit … -
django project always trying (and failing) to load file in separate app
I'm going back to an old django project and am trying to make a new site in a new app I just made, popularify. I want to load an httpResponse and nothing else when I go to the /popularify path , but it keeps trying and failing to get a favicon.ico file, the 404 error always appears in the chrome web console and django logs. I have it set up correctly so my popularify page loads a basic httpResponse: my main urls.py file in my project folder has a path: path('popularify/', include('popularify.urls')), The popularify app urls.py file looks like this: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] And the popularify views.py file looks like this from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") All very basic to just load some text, but in console I am getting a unrelated 404 error trying to load a file I never directly specified, and dont want to load: If I click the favicon.ico link it shows the html file _base.html I have in my templates folder, a file I use as a base file in … -
How do I accept the friend request in django after sending a hyperlink in mail which redirects the user to accept/reject page?
models.py : class Friend(models.Model, LoginRequiredMixin): status = models.CharField(max_length=10) from_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name = 'from_user') to_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="to_user") date_modified = models.DateTimeField(auto_now=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def create(self,request, **kwargs): friend = self.create(from_user_id=request.user.id, status="pending") return friend views.py : This view contains 2 buttons: Accept and reject and based on user response it will be updated in the database def accept_friend_request(request, uidb64, status): """Accept button will lead to entry in database as accepted and reject button will lead to entry in database as rejected based on status flag""" try: uid = urlsafe_base64_decode(uidb64).decode() friend_user = User.objects.get(id=Friend.to_user.id) & Friend.from_user print(friend_user) f = Friend.objects.filter(friend_id = friend_user) print(f) if f: f.status = "accepted" f.save() return render(request, 'users/friend_list.html', {"uidb64": uid, "status": status}) else: f.status = "rejected" f.save() return render(request, 'users/friend_list.html', {'uidb64':uid, 'status':status}) except(FieldError, AttributeError): return render(request, 'blog/base.html') Thanking you in advance, -
How to work with drf-extension (Django Rest Framework) if the model has lookup_fields assigned
It would be better if I give an example that I was working on. The Models are class Author(models.Model): id = models.IntegerField(db_column='a_id', primary_key=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) class Book(models.Model): id = models.IntegerField(db_column='b_id', primary_key=True) title = models.CharField(max_length=60) author = models.ForeignKey(Author, on_delete=models.CASCADE) And the Serializers are, class AuthorSerializer(ModelSerializer): class Meta: model = Author fields = ('id', 'first_name', 'last_name') class BookSerializer(ModelSerializer): class Meta: model = Book fields = ('id', 'author', 'title') And the view sets are, class AuthorViewSet(NestedViewSetMixin, ModelViewSet): serializer_class = AuthorSerializer queryset = Author.objects.all() class BookViewSet(NestedViewSetMixin, ModelViewSet): serializer_class = BookSerializer queryset = Book.objects.all() Now The following APIs are working okay, /authors/ /authors/{author_id}/ /authors/{author_id}/books/ However, If I change the Author Views to class AuthorViewSet(NestedViewSetMixin, ModelViewSet): serializer_class = AuthorSerializer queryset = Author.objects.all() lookup_field = 'first_name' Then, the following APIs work /authors/ /authors/{author_first_name}/ But the following doesn't work. /authors/{author_first_name}/books/ I understand that it's because of the Foreign key relations between these two tables. I was just wondering whether there is any workaround if I want to keep the lookup_fields. Thanks -
Unable to customize django-oscar model
I am trying to customize a django-oscar model. ( I am using version 2.0.3 ) I have created a separate folder labeled apps and have created my app in it. I want to customize Product model in catalogue My INSTALLED_APPS look like this INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'oscar', 'oscar.apps.analytics', 'oscar.apps.checkout', 'oscar.apps.address', 'oscar.apps.shipping', # 'oscar.apps.catalogue', # 'oscar.apps.catalogue.reviews', 'oscar.apps.partner', 'oscar.apps.basket', 'oscar.apps.payment', 'oscar.apps.offer', 'oscar.apps.order', 'oscar.apps.customer', 'oscar.apps.search', 'oscar.apps.voucher', 'oscar.apps.wishlists', 'oscar.apps.dashboard', 'oscar.apps.dashboard.reports', 'oscar.apps.dashboard.users', 'oscar.apps.dashboard.orders', 'oscar.apps.dashboard.catalogue', 'oscar.apps.dashboard.offers', 'oscar.apps.dashboard.partners', 'oscar.apps.dashboard.pages', 'oscar.apps.dashboard.ranges', 'oscar.apps.dashboard.reviews', 'oscar.apps.dashboard.vouchers', 'oscar.apps.dashboard.communications', 'oscar.apps.dashboard.shipping', # 3rd-party apps that oscar depends on 'widget_tweaks', 'haystack', 'treebeard', 'sorl.thumbnail', 'django_tables2', 'rest_framework', 'apps.catalogue' ] and apps/catalogue/models.py looks like this from django.db import models from oscar.apps.catalogue.abstract_models import AbstractProduct # from oscar.apps.catalogue.models import * class Product(AbstractProduct): custom_tag_field = models.CharField(default="Pending", max_length=100) from oscar.apps.catalogue.models import * I keep getting this error when I try to migrate and unable to solve it. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/abhijit/e-commerce-wig/oscar/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/abhijit/e-commerce-wig/oscar/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/abhijit/e-commerce-wig/oscar/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/abhijit/e-commerce-wig/oscar/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/abhijit/e-commerce-wig/oscar/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File … -
How to pass data from Django template (after submission) to DRF API without using a model?
I have a form in my template which allows a user to upload an image. Once the image is uploaded and submitted, it gets stored in a specified directory (not 'media'). Note: The image is not stored in a Django model since I didn't create one (don't need it). After doing so, I need to create an API using the Django Rest Framework. When calling the API URL, I intend to display that stored image name. The result will look like this: {"image_name" : <'stored_image_name_after_form_submission'>} This is what I had done so far: views.py: from rest_framework.views import APIView #code for uploading an image def upload(request): if (request.method == 'POST'): uploaded_file = request.FILES['image'] fs = FileSystemStorage(location=settings.PRIVATE_STORAGE_ROOT) image_path = fs.save(uploaded_file.name, uploaded_file) #name of the image file messages.success(request, 'Uploaded The Image.') return render(request, "template/upload.html") class API(APIView): def get(self, request): #API code comes here. The thing is, I can't seem to visualize how to create the API since I am fairly new to it. How can I capture the image name after the form submission and present it in my API view? Can someone explain how it works and what I should do to meet the requirement? Million thanks in advance. -
serving Angular build pack from django project
Hi have a django project with multiple apps. My project structure is: apt.yml DCMS_API/ infra/ manage.py* odbc-cfg/ requirements.txt static/ templates/ Authorize/ facility/ manifest.yml Procfile runtime.txt i have got angular6 buildpack from front end team, which i have copied it to static folder: ls: 3rdpartylicenses.txt fontawesome-webfont.af7ae505a9eed503f8b8.woff2 scripts.5bde77e84291ce59c080.js assets/ fontawesome-webfont.b06871f281fee6b241d6.ttf Staticfile devManifest.yml fontawesome-webfont.fee66e712a8a08eef580.woff json-data/ styles.38614f36c93ac671679e.css favicon.ico index.html main.e7b9143f2f482d6d3cc7.js fontawesome-webfont.674f50d287a8c48dc19b.eot polyfills.f3fc5ca24d1323624670.js fontawesome-webfont.912ec66d7572ff821749.svg runtime.a66f828dca56eeb90e02.js in settings.py i have added whitenose to serve the static build pack: middleware:'whitenoise.middleware.WhiteNoiseMiddleware', installed apps: 'whitenoise.runserver_nostatic', from my Authorize app: calling def dcmsApi(request): return render(request, 'index.html', {}) which opens index.html file. it however loads the home page, but if i click on anything it says Not Found The requested resource was not found on this server. is this is the right way to server static angular build pack from django Am i missing something? -
JSON parse error - 'utf-8' codec can't decode byte 0xc9 in position XXX when I try to upload Excel Sheet using Angular+REST
I am trying my hands on File Upload using Django REST and Angular. Following is the angular directory structure: app |-----uploadcomponent |-----uploadcomponent.module.ts |-----uploadcomponent.html |-----app.module.ts |-----app.component.ts |-----app.service.ts uploadcomponent.htl: <div> <form [formGroup]="form" (ngSubmit)="onSubmit()"> <input type="file" name="profile" enctype="multipart/form-data" accept=".xlsm,application/msexcel" (change)="onChange($event)" /> <button type="submit">Upload Template</button> <button id="delete_button" class="delete_button" type="reset"><i class="fa fa-trash"></i></button> </form> </div> uploadcomponent.ts: import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms'; import { Component, OnInit } from '@angular/core'; .... export class UploadComponent implements OnInit { form: FormGroup; constructor(private formBuilder: FormBuilder, private uploadService: AppService) {} ngOnInit() { this.form = this.formBuilder.group({ profile: [''] }); } onChange(event) { if (event.target.files.length > 0) { const file = event.target.files[0]; this.form.get('profile').setValue(file); console.log(this.form.get('profile').value) } } onSubmit() { const formData = new FormData(); formData.append('file', this.form.get('profile').value); this.uploadService.upload(formData).subscribe( (res) => { this.response = res; console.log(res); }, (err) => { console.log(err); }); } } app.service.ts: upload(formData) { const endpoint = this.service_url+'upload/'; return this.http.post(endpoint, formData, httpOptions); } Now in the backend I am using Django Rest Framework: Following are the required files of code: models.py: from __future__ import unicode_literals from django.db import models from django.db import connection from django_mysql.models import JSONField, Model import uuid import os def change_filename(instance, filename): extension = filename.split('.')[-1] file_name = os.path.splitext(filename)[0] uuid_name = uuid.uuid4() return file_name+"_"+str(uuid_name)+"."+extension class UploadTemplate (Model): id = … -
django do not save thumbnails from imagekit
from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFill class Image(models.Model): image = models.ImageField(upload_to='home/', blank=True) thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(50, 50)],format='JPEG', options={'quality':60}) when I uploading image. Everything OK with original image. But there is no thumbnail image. I guess this problem is related with cache. Maybe I am wrong. Can't figure out what to do... Please help. -
Django crispy-form changes lay on production server
I cannot seem to understand why crispy-form has changed the layout on my production server vs. the test server. Looking at the html code the only thing I can see is that classes for the form list is changes on the production server. Production Server HTML <div id="div_id_pants" class="control-group"> <label for="id_pants" class="control-label "> Test Server HTML <div id="div_id_pants" class="form-group"> <label for="id_pants" class=""> also noticed that on the test server there is a css file forms.scss.171 that provides the form-group class. Which is not being listed at all on the production site. Any info on where this might be mismatching would be greatly aprieciated. It doesn't look very good atm :( -
HTML file not understanding Django content
I'm using Django in HTML file. Normally whatever IDE you use, understands the syntax the highlights "load" in {% load xxxxx %}. But in my case, Pycharm or Intelllij Idea is not understanding the syntax and the output file too give a result as text, {% load xxxxx %} included in the result page. The environment I am using I have already included Django in that. I'm not able to understand the issue. Can anyone please help me with this -
TypeError: argument of type 'function' is not iterable : django error
i am creating an api for polls app and i struck into this error.TypeError: argument of type 'function' is not iterable : django error my models:how can i deal with it ..it seems like there is no error in code . from django.db import models from django.contrib.auth.models import User class Poll(models.Model): question = models.CharField(max_length=100) created_by = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now=True) def __str__(self): return self.question class Choice(models.Model): poll = models.ForeignKey(Poll, related_name='choices', on_delete=models.CASCADE) choice_text = models.CharField(max_length=100) def __str__(self): return self.choice_text class Vote(models.Model): choice = models.ForeignKey(Choice, related_name='votes', on_delete=models.CASCADE) poll = models.ForeignKey(Poll, on_delete=models.CASCADE) voted_by = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: unique_together = ("poll", "voted_by") my views: from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse from .models import Poll def polls_list(request): MAX_OBJECTS = 20 polls = Poll.objects.all()[:MAX_OBJECTS] data = {"results": list(polls.values("question", "created_by__username", "pub_date"))} return JsonResponse(data) def polls_detail(request, pk): poll = get_object_or_404(Poll, pk=pk) data = {"results": { "question": poll.question, "created_by": poll.created_by.username, "pub_date": poll.pub_date }} return JsonResponse(data) -
How to find whether django hits db [duplicate]
This question already has an answer here: Force evaluate a lazy query 2 answers As per my knowledge, django querysets are lazy and wont hit db until evaluated, in such case after assigning the queryset to a key in a dict, will the following lines cause db to be hit everytime? Please advice abc = model1.objects.all() content = { 'entry' : abc, # Once assigned will the below lines hits db? 'entry_count' : abc.count(), # will this hit db 'entry1_count' : abc.filter(name__icontains = 'a').count(), # will this hit db 'entry2_count' : abc.filter(name__icontains = 'b').count(), # will this hit db again? } return render(request, template, content} -
How to show number of rows in django
I have 6 tables and I had grab the total no of rows like this genre=Genere.objects.all().count() mood=Mood.objects.all().count() artist=Artist.objects.all().count() song=Song.objects.all().count() customuser=CustomUser.objects.all().count() favorite=Favorite.objects.all().count() Now I want to show number of rows in view so I try directly {{genre}} but it's saying name 'Genere' is not defined -
Django ORM unable to retrieve database model instances
I am working on a custom user model that subclasses AbstractBaseUser and a custom model manager that subclasses BaseUserManager.This model, Employee, authenticates by email address - USERNAME_FIELD is set to email. While I can create Employee instances and check my PosgreSQL DB to verify they are being saved, I am unable to retrieve them with the Django ORM and my custom model manager. If I try to retrieve all the employees, or 'get' one employee when running Employee.objects.get(id=1), I get an error that from_db_value() expected 4 arguments but received 5. I am stumped here. I had this same kind of custom user in another Django 1.11 app and worked fine. I have spent two days trying to resolve this. Any help? models.py from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) from phone_field import PhoneField from django.core.validators import RegexValidator # to ensure leading zeroes are captured in badge number numeric = RegexValidator(r'^[0-9]*$', 'Only numeric characters are allowed.') # Create your models here. class EmployeeManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) … -
CharField(editable=False) with local variable as deault
im new to django and am trying to figure out how to add a specific field to a django model. I want to upload a csv document and save its headers. As you can see, i want to use the headers i send with the document, or if they arent send, the ones from the first line of the document. from django.db import models class CSV_API_DB(models.Model): headers = models.CharField(max_length=250, blank=True) delimiter = models.CharField(max_length=1, default=';') filefield = models.FileField(upload_to='uploads/', max_length=100, default='empty') actual_headers = '' def __str__(self): actual_headers = '' if not self.headers: file_path = str(self.filefield) file = open(file_path) for line in file: string_line = str(line[:-1]) actual_headers = string_line.split(self.delimiter) break else: actual_headers = self.headers.split(self.delimiter) return str(actual_headers) true_headers = models.CharField(max_length=250, default = str(actual_headers), editable=False) The issue seems to be, that true_headers does not get overridden from the '__ str __' function, since the values in the database for true_headers are always just empty strings. -
Github doesn't change the database in our teams django environment
Our team is using a django environment to develop a website, the main issue is one team member recently updated one of the databases and the change will not care through mysql. We are literally on the same branch but the database tables are completely different. We are using the current version of django, python, and mysql are the development environment and github to share work. -
debug=true django not showing errors on deployment
My site has been deployed successfully on linode. All pages are working just fine, but except for one particular url. Whenever I click on that link, it gives an internal server error without showing any error messages even though DEBUG=TRUE. But when I go to a non existing url Django shows the errors. Here is the error log: [Tue Nov 19 09:18:37.378891 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] mod_wsgi (pid=22728): Exception occurred processing WSGI script '/home/shahid/django_project/djecommerce/wsgi.py'. [Tue Nov 19 09:18:37.379959 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] Traceback (most recent call last): [Tue Nov 19 09:18:37.380186 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] File "/home/shahid/django_project/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner [Tue Nov 19 09:18:37.380235 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] response = get_response(request) [Tue Nov 19 09:18:37.380283 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] File "/home/shahid/django_project/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response [Tue Nov 19 09:18:37.380330 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] response = self.process_exception_by_middleware(e, request) [Tue Nov 19 09:18:37.380388 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] File "/home/shahid/django_project/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response [Tue Nov 19 09:18:37.380435 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] response = wrapped_callback(request, *callback_args, **callback_kwargs) [Tue Nov 19 09:18:37.380567 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] … -
Django Register Issues
I receive this error after registering. AttributeError at /accounts/register/ 'AnonymousUser' object has no attribute '_meta' When I look at the admin panel, the user seems to be registered. But no password. I added the required codes below. Where am I doing wrong? Thanks. forms.py from django import forms from django.contrib.auth import authenticate from django.contrib.auth.models import User class LoginForm(forms.Form): username = forms.CharField(max_length=100, label='Kullanıcı Adı') password = forms.CharField(max_length=100, label='Parola', widget=forms.PasswordInput) def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError('Kullanıcı adını veya parolayı yanlış girdiniz!') return super(LoginForm, self).clean() class RegisterForm(forms.ModelForm): username = forms.CharField(max_length=100, label='Kullanıcı Adı') password1 = forms.CharField(max_length=100, label='Parola', widget=forms.PasswordInput) password2 = forms.CharField(max_length=100, label='Parola Doğrulama', widget=forms.PasswordInput) class Meta: model = User fields = [ 'username', 'password1', 'password2', ] def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError("Parolalar eşleşmiyor!") return password2 views.py from django.shortcuts import render, redirect from .forms import LoginForm, RegisterForm from django.contrib.auth import authenticate, login def login_view(request): form = LoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) return redirect('home') return render(request, 'accounts/form.html', {'form': form, 'title': 'Giriş Yap'}) def register_view(request): form = RegisterForm(request.POST … -
Python Django strangely does mapping towards unexpected URL
I tested 1st Django web app project. That app project does mapping towards http://127.0.0.1:8000/api/ when the URL of http://127.0.0.1:8000 comes The test was successful. And then, I tested 2nd Django web app project. That Django app should have performed mapping towards http://127.0.0.1:8000/blog/ when the URL of http://127.0.0.1:8000 occurs. But Django strangely moves towards http://127.0.0.1:8000/api/ which was target URL of 1st Django web app. There is no /api/ URL configuration in 2nd project Following code snippets are URL configuration of 2nd Django web app # AskDjango_webfrontend_begin/askdjango/urls.py urlpatterns = [ path('admin/', admin.site.urls), # If the client enters in "localholst:8000", the page is redirected to localholst:8000/blog/ path("", RedirectView.as_view(url="/blog/", permanent=True)), # If the client enters in "localholst:8000/blog/", connect to blog.urls.py path("blog/", include("blog.urls")), ] # AskDjango_webfrontend_begin/blog/urls.py urlpatterns = [ path("",views.index,name="index"), path('<int:pk>', views.post_detail, name="post_detail") ] -
Django: How to store user specific data like bookmarks, questions
I just learned the basic authentication system in django. I am trying to make a learning website where the user can add courses and ask questions. How do I make the user authentication in a way that each user can have different data on the courses they have added(course completed %, you were views the chapter # etc) and can see all of these in their dashboard. I would also like to have a community for the users to discuss and ask questions. I would be really thankful if someone could explain the courses part to me in a simple way or if there's a link to the topic already on stack overflow or any other website please link it here. Thanks in advance. -
Celery Tasks Won't Purge Properly and Keep Restarting
have a frustrating problem with Celery I was hoping you can help me with. I'm using Redis as my message broker and am using celery in conjunction with Django and celery-beat. I tested a periodic job before that had a mistake in it and could not succesfully run. I terminated celery, typed celery flush, flushed redis and have restarted and million times. No matter what I do, everytime I start celery backup, my old child processes start right where I left them (I think, see console log below). I cannot figure out how to make these things go away! I want every child process that was ever run to DIE! Any suggestions? [2019-11-18 19:50:03,432: INFO/SpawnPoolWorker-3] child process 15748 calling self.run() [2019-11-18 19:50:03,435: INFO/SpawnPoolWorker-1] child process 14028 calling self.run() [2019-11-18 19:50:03,442: INFO/SpawnPoolWorker-8] child process 24924 calling self.run() [2019-11-18 19:50:03,445: INFO/SpawnPoolWorker-11] child process 19120 calling self.run() [2019-11-18 19:50:03,445: INFO/SpawnPoolWorker-2] child process 12808 calling self.run() [2019-11-18 19:50:03,447: INFO/SpawnPoolWorker-4] child process 20976 calling self.run() [2019-11-18 19:50:03,452: INFO/SpawnPoolWorker-7] child process 27288 calling self.run() [2019-11-18 19:50:03,453: INFO/SpawnPoolWorker-6] child process 3104 calling self.run() [2019-11-18 19:50:03,457: INFO/SpawnPoolWorker-5] child process 16752 calling self.run() [2019-11-18 19:50:03,459: INFO/SpawnPoolWorker-9] child process 18144 calling self.run() [2019-11-18 19:50:03,475: INFO/SpawnPoolWorker-12] child process 17232 calling self.run() … -
How to debug Django with allauth package error
I am struggling with an error all day long. I have a Django app deployed on Heroku. Everything works perfectly offline with the social authentication. When I deploy the application I receive an error: SocialApp matching query does not exist. I have tried settings the SITE_ID but nothing changes. Also I have checked that my DB have the Site objects created. Any help would be appreciated. -
Using prefetch_related on specific attributes?
I have the following code: pictures_of_model: Model3D.objects.prefetch_related('Pictures') Pictures is another table in which I store id's for pictures, the pictures themselves in an ImageField and an modelid that is a foreign key. How do I make sure that django prefetches the attribute with the ImageField and not the id of the picture? pictures_of_model: Model3D.objects.prefetch_related('Pictures').picture that can't be correct, right? Picture is my ImageField that holds, well, the picture. I appreciate every answer that helps me learn, thank you! -
Django Rest Framework : Only last record is saved in DB when trying to call "perform_create" function iteratively
I'm newbie in Django and trying to build API server using Django Restframework. With sincere help from @cagrias, I got a success in parsing json and save several records in my DB. Now, I'm struggle in saving multiple records in my DB with iteratively call 'perform_create' function. My View.py function is as follows. models have 6 tables BankA, BankB, BankC, and CardA, CardB, CardC. What I want to is save 4 records when call the post api, but now, only last one(('카드매출', sales_card)) is saved. I hope your help, and it will be very grateful for me. Thank you. # API to save trading history (aggregated Purchase/Sales for Bank/Card) class SalesAndPurchaseInPeriodListView(ListCreateAPIView): def post(self, request): quiry = request.data serializer = SalesAndPurchaseInPeriodListSerializer(data=request.data) banklist = [BankA, BankB, BankC] cardlist = [CardA, CardB, CardC] # Purchase Bank purchase_bank = 0 for bank in banklist: records_bank = bank.objects.filter(resAccountIn='0', creator_id=request.user.id) for record in records_bank: purchase_bank += record.resAccountOut # Purchase Card purchase_card = 0 for card in cardlist: records_card = card.objects.filter(creator_id=request.user.id) for record in records_card: purchase_card += record.resUsedAmount # Sales Bank sales_bank = 0 for bank in banklist: records_sales_bank = bank.objects.filter(resAccountIn='0', creator_id=request.user.id) for record in records_sales_bank: sales_bank += record.resAccountOut # Sales Card sales_card = 0 for card …