Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to annotate count based on nested JSONField in Django 1.11 and postgres 9.6
My model currently looks like: class Review(models.Model): source = models.CharField(max_length=80, blank=True, null=True) metadata = JSONField(default=dict) entity_type = models.CharField(max_length=255, blank=True, null=True) Example object of class Review: { "source": "amazon", "entity_type": "media", "metadata": [ { "product": 123456 }, { "product": 012345 } ] } I want to annotate count based on "source", "entity_type", "metadata_product" I am talking about Django query similar to: Review.objects.filter().values( "source","entity_type","metadata__product" ).annotate(count=Count('id')) which will obviously not work. I want to get output query set similar to: [{"source": "amazon", "entity_type": "media", "metadata_product": 123456, "count": 1}, {"source": "amazon", "entity_type": "media","metadata_product": 012345, "count": 1}] I want to achieve this using Django ORM and not resort to python because the table contains data close to 10 or 20 million. If that is not possible it will be really good if someone can suggest raw SQL query which can be put in Django ORM raw SQL method. -
uwsgi segmentation fault when serving a django application
I am trying to migrate a django application from one server to another. The application is working fine on the old server. On the new server, the application works fine when used using Django's runserver. To test the django application under uwsgi, I used uwsgi --http :8000 --module mysite.wsgi This opens the django admin page as expected but as soon as I try to login, uwsgi gets a segmentation fault error which is as follows. Would greatly appreciate if anybody could help understand what this means, and how might I fix this. *** uWSGI is running in multiple interpreter mode *** spawned uWSGI worker 1 (and the only) (pid: 15398, cores: 1) !!! uWSGI process 15398 got Segmentation Fault !!! *** backtrace of 15398 *** uwsgi(uwsgi_backtrace+0x35) [0x5569e2f17555] uwsgi(uwsgi_segfault+0x23) [0x5569e2f17903] /lib/x86_64-linux-gnu/libc.so.6(+0x35fc0) [0x7f0dd221bfc0] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/./libssl-1d6df745.so.1.0.2p(ssl3_cleanup_key_block+0xb) [0x7f0dd0241cab] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/./libssl-1d6df745.so.1.0.2p(ssl3_clear+0x16) [0x7f0dd023f5a6] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/./libssl-1d6df745.so.1.0.2p(tls1_clear+0x9) [0x7f0dd024b219] /usr/lib/x86_64-linux-gnu/libssl.so.1.1(SSL_new+0x43f) [0x7f0dd2bf376f] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(+0x23969) [0x7f0dd04d6969] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(+0x24fc5) [0x7f0dd04d7fc5] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(PQconnectPoll+0xb78) [0x7f0dd04c1ba8] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(+0xfa28) [0x7f0dd04c2a28] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(PQconnectdb+0x1f) [0x7f0dd04c541f] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/_psycopg.cpython-36m-x86_64-linux-gnu.so(+0x12651) [0x7f0dd0716651] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/_psycopg.cpython-36m-x86_64-linux-gnu.so(+0x133df) [0x7f0dd07173df] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x1fcab2) [0x7f0dd25d9ab2] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyObject_FastCallDict+0x89) [0x7f0dd2645e99] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyObject_CallFunction_SizeT+0x124) [0x7f0dd26468b4] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/_psycopg.cpython-36m-x86_64-linux-gnu.so(+0xc1a8) [0x7f0dd07101a8] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(PyCFunction_Call+0x96) [0x7f0dd25f0fe6] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x7940) [0x7f0dd2561f10] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17ba3f) [0x7f0dd2558a3f] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(PyEval_EvalCodeEx+0x3e) [0x7f0dd25594fe] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x23cc63) [0x7f0dd2619c63] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(PyObject_Call+0x48) [0x7f0dd26466d8] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x3de5) [0x7f0dd255e3b5] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17a8a3) [0x7f0dd25578a3] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17c2eb) [0x7f0dd25592eb] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x4ec2) [0x7f0dd255f492] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17a8a3) [0x7f0dd25578a3] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17c2eb) [0x7f0dd25592eb] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x4ec2) [0x7f0dd255f492] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17a8a3) [0x7f0dd25578a3] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17c2eb) [0x7f0dd25592eb] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x4ec2) [0x7f0dd255f492] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17ba3f) [0x7f0dd2558a3f] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17c11e) [0x7f0dd255911e] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x4ec2) [0x7f0dd255f492] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17a8a3) … -
How to write unit tests for csv file upload method in django
I've written a method for csv file upload in django now I'm trying to write unit tests for that method. can we mock csv file using from django.core.files.uploadedfile import SimpleUploadedFile, or should I use something else? Can someone discuss that what approach(mocking, upload) should I follow for this problem? -
Django form prefix separator hyphen to underscore
The naming process for django-formtools seems to be breaking the ability to access variables in session data. The form I have named patient_details but it's fields are being separated by - for example patient_details-upper_arch. I'm trying to access the session data to manipulate a form further along in the wizard based on a selection in the first form. However when trying to access {{ ...patient_details-upper_arch }} it throws a TemplateSyntaxError Could not parse the remainder: '-upper_arch' from ...patient_details-upper_arch Is there a way to set the separator to an underscore to make this variable accessible in the template, or another way around this? -
redirect to account activation resend url if user is not active
My forms.py : class UserLoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs= {'class':'form-control form-control-lg','placeholder':'Username'})) password = forms.CharField(widget=forms.PasswordInput(attrs= {'class':'form-control form-control-lg','placeholder':'Password'})) def clean(self, *args, **kwargs): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") if username and password: user = authenticate(username=username, password=password) if user is None: raise forms.ValidationError("This user does not exist") elif user is not None: if not user.is_active: raise forms.ValidationError("This user is not longer active.") elif not user.check_password(password): raise forms.ValidationError("Incorrect password") return super(UserLoginForm, self).clean(*args, **kwargs) I want the user to be redirected to the resend activation link page if he hasnt activated already .Now after i register the user and skip account activation and then try to login ,it shows validation error "This user does not exist" eventhough this user is registered in the User model . -
Django DRF APITestCase chain test cases
For example I want to write several tests cases like this class Test(APITestCase): def setUp(self): ....some payloads def test_create_user(self): ....create the object using payload from setUp def test_update_user(self): ....update the object created in above test case In the example above, the test_update_user failed because let's say cannot find the user object. Therefore, for that test case to work, I have to create the user instead test_update_user again. One possible solution, I found is to run create user in setUp. However, I would like to know if there is a way to chain the test cases to run one after another without deleting the object created from previous test case. -
Validate form and formsets with django
I'm trying to set my form validation in my view and I would like to get you help because I have a little issue. This is my formset : DocumentFormSet = inlineformset_factory(Publication, Document, form=DocumentForm, extra=1, max_num=4, can_delete=True) This is my code : def get_context_data(self, **kwargs): context = super(PublicationCreateView, self).get_context_data(**kwargs) document_queryset = Document.objects.all() context['FormSets'] = DocumentFormSet(self.request.POST or None, self.request.FILES or None, prefix='doc', queryset=document_queryset) return context def form_valid(self, form): try: context = self.get_context_data() formsets = context['FormSets'] if form.is_valid(): self.object = form.save(commit=False) if formsets.is_valid(): formsets.instance = self.object formsets.save(commit=False) for element in formsets: element.save(commit=False) self.object = form.save() formsets.save() return super(PublicationCreateView, self).form_valid(form) except IntegrityError: ... I read some things, especially form has to be save before forms in formset if there is ForeignKey between form and forms in my formset. The issue comes if I have wrong field in my formset. As the first form is saved, it creates an object with only the first form and not with the associated form in my formset. This is an example : As you can see, it saves my first form, but I don't want until all the formset is valid. I have to switch between .save(commit=False) and .save() methods. Thank you -
Multi select in django
I am very new in Django, I want to create an API which shows me cities of selected states,but more than one state I created this view: def get(self,request,State_id1,State_id2): cities = city.objects.filter(state__in= [State_id1,State_id2]) I have two problem here: 1. how to correct this view because user may not select only two states,there may be more than one states 2. how should I define urlpattern -
convert double to time in python
I have a TimeField() in my django models. I want to convert the sum of the record of this to hours. Here's my actual code into my view: hours_week_decimal = Timesheet.objects.filter(owner = request.user.pk, week = datetime.datetime.now().isocalendar()[1]).aggregate(total=Sum('working_hour')) # this method return a dict of decimal total_hours_week = convertDecimalToHours(hours_week_decimal) and the related function: def convertDecimalToHours(times): total_time = 0 for k, v in times.items(): total_time += int(v) print("type: {} - value: {}".format(type(total_time), total_time)) He returned me: type: int - value: 166000 I have two hours: Monday (08:30) and Tuesday(08:30), so he must returned me "17:00" Hope you can help me to pass this problem :) -
Reverse relationships in Nested serializer in django rest framework
My models.py is as as follows: class Group(models.Model): name = models.CharField(max_length=50, unique=True) class Policy(models.Model): name = models.CharField(max_length=50, unique=True) source_group = models.ForeignKey(Group, related_name='source_group') destination_group = models.ForeignKey(Group, related_name='destination_group') Since I have two foreign keys, pointing to the same model, I am using related name to avoid clashes. Now, when I try to create a serializer for Groups in order to list all Policies associated with it, I do the following: class PolicySerializer(serializers.ModelSerializers): class Meta: model = Policy fields = "__all__" class GroupSerializer(serializers.ModelSerializer): policy = PolicySnippetSerializer(source ='source_group', many=True) class Meta: model = Group fields = ['id', 'name', 'policy'] However, this will give me only policies for a a source_group.How did i get all groups associated with a group, source and destination ? -
add django paginator on records
This is my record app views.py, i want to add pagination on result of records list, the list generated by following code and also give solution for templates. Please help me. Thank you. from django.shortcuts import render from purchase_report.views import * import datetime from datetime import datetime from purchase_report.models import * from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def display_records(request): start_date = request.GET.get('start_date') end_date = request.GET.get('end_date') purchase_date = PurchaseReport.objects.filter(purchase_date__range=[start_date, end_date]) return render(request, 'records.html', {'purchase_date': purchase_date, 'start_date': start_date, 'end_date': end_date}) parsed_start_date = None parsed_end_date = None if start_date and end_date: errors = {} try: parsed_start_date = datetime.datetime.strptime(start_date, "%d/%m/%Y") except ValueError: errors["start_date"] = "Invalid date" try: parsed_end_date = datetime.datetime.strptime(end_date, "%d/%m/%Y") except ValueError: errors["end_date"] = "Invalid date" if parsed_start_date and parsed_end_date: purchase_date = PurchaseReport.objects.filter(purchase_date__range=[parsed_start_date, parsed_end_date]) else: purchase_date = PurchaseReport.objects.none() return render(request, 'records.html', {'purchase_date': purchase_date, 'start_date': start_date, 'end_date': end_date, 'errors': errors}) -
uwsgi segmentation fault for one specific route
My django apps works correctly locally, but when I deployed it facing a uswgi seg fault for one specific route. Every others routes works correctly. Here the view: def bunny(request): """ Filter crawler, bot and real user :param request: :return: serve rendered page to crawler / SPA to user """ ......some other codes .... path = request.get_full_path_info() if path.startswith('/news_paper'): # <<-- seg fault for this routes only in production server news_paper = utils(unquote(path[12:])) if news_paper[1] == 0: # if news paper is not found return default list return render(request, 'site_list.html') news = News.objects.filter(news_paper=news_paper[1]).order_by('-created_at')[:15] return render(request, 'news.html', {'news': news, 'title': news_paper[0]}) elif path == '/about/': return render(request, 'about.html') else: return render(request, 'site_list.html') uWsgi conf file: [uwsgi] chdir=/home/.. home = /home/../.env module=xyz.wsgi master=True process = 5 pidfile=/run/xyz.pid socket= /run/xyz.sock stats=/tmp/xyz.stat vacuum=True max-requests=500 logto = /home/../logs/xyz.log log-maxsize = 200480 uid = prism gid = www-data die-on-term = true chmod-socket = 666 chown-socket = www-data and the log file: !!! uWSGI process 4668 got Segmentation Fault !!! *** backtrace of 4668 *** uwsgi(uwsgi_backtrace+0x2c) [0x46d0ac] uwsgi(uwsgi_segfault+0x21) [0x46d471] /lib/x86_64-linux-gnu/libc.so.6(+0x354b0) [0x7f1c373b84b0] /home/../.env/lib/python3.6/site-packages/psycopg2/.libs/./libssl-1d6df745.so.1.0.2p(ssl3_cleanup_key_block+0xb) [0x7f1c32d3fcab] /home/../.env/lib/python3.6/site-packages/psycopg2/.libs/./libssl-1d6df745.so.1.0.2p(ssl3_clear+0x16) [0x7f1c32d3d5a6] /home/../.env/lib/python3.6/site-packages/psycopg2/.libs/./libssl-1d6df745.so.1.0.2p(tls1_clear+0x9) [0x7f1c32d49219] /usr/lib/x86_64-linux-gnu/libssl.so.1.1(SSL_new+0x462) [0x7f1c387a5d22] /home../.env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(+0x23969) [0x7f1c32fd4969] /home/../.env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(+0x24fc5) [0x7f1c32fd5fc5] /home/../.env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(PQconnectPoll+0xb78) [0x7f1c32fbfba8] /home/../.env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(+0xfa28) [0x7f1c32fc0a28] /home/../.env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(PQconnectdb+0x1f) [0x7f1c32fc341f] /home/../.env/lib/python3.6/site-packages/psycopg2/_psycopg.cpython-36m-x86_64-linux-gnu.so(+0x12651) [0x7f1c33214651] /home/../.env/lib/python3.6/site-packages/psycopg2/_psycopg.cpython-36m-x86_64-linux-gnu.so(+0x133df) [0x7f1c332153df] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x16cb06) [0x7f1c37af1b06] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyObject_FastCallDict+0x8b) [0x7f1c37aa810b] … -
Django - Request resolution
I would like to know how Django is resolving request urls urlpatterns in general. My theory: Django at some point turns all its urlpatterns into list of regexes, and then tries to match them against incoming Request's url. Question: Am I correct? If yes, can somebody point me out where in source code is this happening? Looks like there is nothing about this mentioned in django docs, and I feel like I am doing a blind search in source code. Any insights appreciated. -
Django: Table Doesn't exist after shifting MySQL db to server MySQL
Summary: After uploading mysql "site_dump.sql" into server MySQL, and applying proper settings to point to database, I get error 'Table doesn't exist' Error Details: ProgrammingError: (1146, "Table 'evaluation.Evaluator_skill' doesn't exist") Observations: Only User table is showing all the data I had. All other tables are throwing the same error . If I login to MySQL shell, use that new db, and see table data, all the tables and their data is present. What I did exactly: On my local PC, took a sql dump like this: mysqldump -u root -p --databases db_name > mysite_26_11_2018.sql Copied this file into server. Launched MySQL shell on server using root username and created a new db: mysql>create database db_server; Then on prompt uploaded the copied db like this: mysql -u root -p db_server < mysite_26_11_2018.sql Again logged-in to mysql, and execute these steps: mysql>create user server_admin identified by 'admin_password'; mysql>grant all on db_server.* to 'server_admin'@'%'; mysql>flush privileges; What I tried: - 1) Ran makemigrations amd migrate, but no changes . 2) Checked using MySQL shell that all data is present in t he db . 3) Checked using django shell that User data is all present but all other tables give the same error. -
Identify origin of POST request in Django (Active Campaign)
I have set up a webhook to receive POST requests from the Active Campaign API in order to update my CRM data. The problem is that Active Campaign doesn't send any token or credential information with the POST request, so I cannot be sure that the request is really coming from them. Is there a way in Django to check where the request is coming from, in order to prevent anyone from sending POST data to this webhook? -
The permission codenamed 'view_audiofile' clashes with a builtin permission for model 'audiofield.AudioFile'
I am trying to implement django-audiofield app into my model but i get the following error. ERRORS: audiofield.AudioFile: (auth.E005) The permission codenamed 'view_audiofile' clashes with a builtin permission for model 'audiofield.AudioFile'. I've done everything according to the docs and can't find where is the problem... -
Django JSONField filter greater than an attribute value
I have the following Django model: class Student(models.Model): student_id = models.CharField(primary_key=True, max_length=10) student_info = JSONField() My data looks like: { “student_id": “1", “student_info":{ “student_name": “Parker", “age": "21", “num_classes": “5", “highest_score": “75", “credits_complete": “13”, “credits_remaining”:”20" } } I want to select all students with credit complete greater than 13. I tried the following which returns me an empty Queryset: Student.objects.filter(student_info__credits_complete__gt='13’) Any idea how to filter greater than or less than the attribute value in JSONField? Thanks! -
How to create union of two different django-models?
I have two django-models class ModelA(models.Model): title = models.CharField(..., db_column='title') text_a = models.CharField(..., db_column='text_a') other_column = models.CharField(/*...*/ db_column='other_column_a') class ModelB(models.Model): title = models.CharField(..., db_column='title') text_a = models.CharField(..., db_column='text_b') other_column = None Then I want to merge the two querysets of this models using union ModelA.objects.all().union(ModelB.objects.all()) But in query I see (SELECT `model_a`.`title`, `model_a`.`text_a`, `model_a`.`other_column` FROM `model_a`) UNION (SELECT `model_b`.`title`, `model_b`.`text_b` FROM `model_b`) Of course I got the exception The used SELECT statements have a different number of columns. How to create the aliases and fake columns to use union-query? -
using templatetags with if in Django
I'm using Django 2.x. I have a simple_tag with returns True or Flase. from django import template register = template.Library() @register.simple_tag(takes_context=True) def aws_require(context): print('test') request = context['request'] if request.user: return True return False Now, I'm using it in the template {% load accounts_tag %} {% aws_require as aws_r %} {% block force_popup %} {% if aws_r %} {% include 'base/force_popup.html' with aws_status=aws_status %} {% endif %} {% endblock force_popup %} But it seems to be not working. It does not go inside if block. I tried printing something in the template tag print('test') but it is not printing in the console log as well. -
Django : Custom save method with queryset
I'm trying to create a custom save method in my model and I would like to get your help in order to improve this one. I'm generating a unique code based on some variables in my form. I generate the code and I make a research before to save it. If another document already gets this code, I generate another one, else I save the object. This is my save() method in my models.py file : def save(self, *args, **kwargs): import random self.code = f"{self.publication.pub_id}-{self.language.upper()}-{self.format.upper()}-{random.randint(1,10001)}" document = Document.objects.filter(code=self.code) if document: self.code = f"{self.publication.pub_id}-{self.language.upper()}-{self.format.upper()}-{random.randint(1,10001)}" super(Document, self).save(*args, **kwargs) I think it could me improved, by while instead of if condition. What do you think about it ? Thank you -
How to show Kibana Visualization dashboard in Website?
I have a csv file and I have passed through the ElasitcSearch and create a dashboard in Kibana. Is there any way to display this dashboard in the website. Like any bootstrap kind of script available? Or Any other way to embed in Django or Flask frame work -
Django filter ManyToMany filed in query
I need to filter field with ManyToMany in queryset. There must stay only active Products class Product(model.Model): name = models.CharField(max_length=100) active = models.BooleanField(blank=True, default=True) class Package(model.Model): name = models.CharField(max_length=100) products = models.ManyToManyField(Product) I tried something like this. packages = Package.objects.all() for package in packages: active_products = package.products.filter(active=True) package.products = active_products but it updates my packages in database, when i need only change queryset. expectation: packages = [ {'id': 1, 'name': 'First package', 'products': [ {'id': 1, 'name': 'first product', 'active': True}, {'id': 2, 'name': 'second product', 'active': True}, ]}, {'id': 2, 'name': 'Second package', 'products': [ {'id': 2, 'name': 'first product', 'active': True}, {'id': 3, 'name': 'third product', 'active': True}, ]} ] I thought about creating a list of dictionaries from Packages by .values(), then iterate it and exclude all not active products. Do you know any more elegant way to do it? -
django rest framework " TypeError: 'type' object is not iterable " error
I do not know what configuration to modify. My git repository URL : https://github.com/Nomadcoders-Study/Nomadgram Internal Server Error: /images/all/ Traceback (most recent call last): File "/usr/local/var/pyenv/versions/3.6.1/envs/nomadgram/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/var/pyenv/versions/3.6.1/envs/nomadgram/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/var/pyenv/versions/3.6.1/envs/nomadgram/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/var/pyenv/versions/3.6.1/envs/nomadgram/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/var/pyenv/versions/3.6.1/envs/nomadgram/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/var/pyenv/versions/3.6.1/envs/nomadgram/lib/python3.6/site-packages/rest_framework/views.py", line 478, in dispatch request = self.initialize_request(request, *args, **kwargs) File "/usr/local/var/pyenv/versions/3.6.1/envs/nomadgram/lib/python3.6/site-packages/rest_framework/views.py", line 380, in initialize_request authenticators=self.get_authenticators(), File "/usr/local/var/pyenv/versions/3.6.1/envs/nomadgram/lib/python3.6/site-packages/rest_framework/views.py", line 274, in get_authenticators return [auth() for auth in self.authentication_classes] TypeError: 'type' object is not iterable -
uwsgi.ini says the Address already in use but running uwsgi with parameter works
If I run the uwsgi command this way and then start nginx then my site loads up and it works fine. uwsgi --socket site1.socket --module main.wsgi --chmod-socket=777 However if I use an wsgi.ini with the following content [uwsgi] # ----- Django-related settings ----- # the base directory (full path) chdir=/home/ec2-user/fooVenv/fooWeb/ # Django's wsgi file module=main.wsgi # the virtualenv (full path) home=/home/ec2-user/fooVenv/ # pidfile=/path/to/site1.pid # max-requests=5000 # ----- process-related settings ----- # master master=true # maximum number of worker processes processes=1 # the socket (use the full path to be safe) socket=/home/ec2-user/fooVenv/fooWeb/ # ... with appropriate permissions - may be needed #chmod-socket=664 chmod-socket=777 # clear environment on exit vacuum=true and then run the file using uwsgi --ini uwsgi.ini I get the error ... ... thunder lock: disabled (you can enable it with --thunder-lock) error removing unix socket, unlink(): Is a directory [core/socket.c line 198] bind(): Address already in use [core/socket.c line 230] Any suggestions on why this might be happening ? -
Migrations can't run due to evaluation of QuerySet in Serializer?
Trying to solve this chicken-and-egg issue. I've defined a new model which an existing model foreign keys into, and made the new migrations, including a data migration that provisions some defaults for the new model. In the serializer for the existing model, I wanted to define a default like so: new_thing = serializers.PrimaryKeyRelatedField( queryset=NewThing.objects.all(), default=NewThing.objects.get(id=DEFAULT_NEW_THING_ID), ) I don't understand django's specific mechanism, but this seems to cause problems while running the migrations (although the makemigrations seems fine). It seems the migration runs a series of app checks on the views and eventually the serializer, where it evaluates the NewThing QuerySet and returns an error that the relation for NewThing does not exist (since the migration hasn't been run yet).