Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Authenticate a Django user from another application
I want to redirect a user from my Django application to another web application. Only permitted users can be allowed access to visit the other web application, this permission is set in the Django User model. I want that other web application to verify whether the visited user has permission by querying the Django application using API endpoint. But the other web application no longer has the request.user parameter or other way to authenticate the user based on Django User model (don't wan't him to login again). Is there any way like setting a cross-domain session cookie or something, i can achieve it? -
Django web-server runs locally on windows server 2016 but is not available remotely
Django web-server runs locally on windows server 2016 at http://127.0.0.1:8000 I have access to a web-page and all its functions, but when I try to access it remotely using http://193.124.64.241:8000 the page is not available. I've opened port 8000 in windows brandmauer settings for incoming and outcomming connections but it hasn't helped. -
How can I make two models the same "type"?
I have 3 models. Rhyme, CommunityRhyme, and AssortedRhymes. Rhyme(s) are collected by a bot. CommunityRhyme(s) are rhymes added by the community. AssortedRhymes contains a ManyToManyField that references only the Rhyme model. How can I make it so that Rhyme and CommunityRhyme are of the same "type" so that the AssortedRhymes ManyToManyField that references the Rhyme model can also reference (add) CommunityRhymes? Thank you in advance -
No module named 'django' uWSGI
in a nutshell I am getting the following error message from uWSGI when I try to test my installation against the examples found here: $ uwsgi --socket 127.0.0.1:3031 --chdir /home/user/~Env/proj0/proj0 --wsgi-file wsgi.py --master --processes 4 --threads 2 --stats 127.0.0.1:9191 *** Starting uWSGI 2.0.15 (64bit) on [Wed May 31 14:10:35 2017] *** compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-11) on 30 May 2017 20:50:53 os: Linux-3.10.0-514.10.2.el7.x86_64 #1 SMP Fri Mar 3 00:04:05 UTC 2017 nodename: echo.com machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 2 current working directory: /home/user/~Env detected binary path: /usr/local/bin/uwsgi chdir() to /home/user/~Env/proj0/proj0 your processes number limit is 4096 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uwsgi socket 0 bound to TCP address 127.0.0.1:3031 fd 3 Python version: 3.6.1 (default, May 29 2017, 14:21:37) [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] Python main interpreter initialized at 0x1639580 python threads support enabled your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 415360 bytes (405 KB) for 8 cores *** Operational MODE: preforking+threaded … -
Django DATABASES are not configure
So I am building a Django site that is connecting to a view legacy DBs. Because of some of the limitations of the legacy MySQL dbs I need to access a view. From what I can tell the easiest way is to insert sql directly. (inspectdb doesn't work for the views). Here is the code I have so far: from django.db import connection cursor = connection.cursor() sqlstring = 'SELECT * FROM Site_Call_Counts' cursor.execute(sqlstring) result = cursor.fetchall() This code works when I enter it into the manage.py shell but breaks when I try and run it complete. Here is the traceback. /usr/bin/python2.7 /root/Desktop/IPNV/django-test/src/djangotest/viewTest.py Traceback (most recent call last): File "/root/Desktop/IPNV/django-test/src/djangotest/viewTest.py", line 3, in <module> cursor = connection.cursor() File "/usr/local/lib/python2.7/dist-packages/django/db/__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 208, in __getitem__ self.ensure_defaults(alias) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 176, in ensure_defaults conn = self.databases[alias] File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 156, in databases self._databases = settings.DATABASES File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 39, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. So really I have 2 Questions. First, is this the easiest way to accomplish … -
RedirectView.as_view V/s redirect
I tried searching documentation but I could not understand, is there any difference between the two or both these can be used interchangeably with slight modifications. Or redirect is used only in the return statements. I tried searching through the documentation but could not find. Any help would be appreciated. https://docs.djangoproject.com/en/1.11/ref/class-based-views/base/#redirectview https://docs.djangoproject.com/en/1.11/topics/http/shortcuts/#redirect -
Django split String from database
I try to split a String from a database (SQLite). The String has a linebreak \n and I want split it there in 2 parts. It works with a normal String for example text = "Hello \n World". But if I use the string from my database it doesn't work (the text is saved correctly with \n in the database!!) My Code for getting the first part of the string: from django import template from products.models import News register = template.Library() @register.simple_tag def get_first_title(id): search_value = "\n" news = News.objects.values('title') title = news.filter(pk=id) number = str(title).find(search_value) first_title = str(title)[0:number] return first_title -
Django form does not save to database neither does it forward correctly upon POST
I can't figure out why one of my forms does not save nor forward upon submit. This is the model: class Offer(models.Model): """ local offers traveler to take her out based on the trips listed by traveler """ local = models.ForeignKey(User, related_name='local_offers_excursion') message = models.CharField(max_length=500) trip = models.ForeignKey(Excursion, related_name='traveler_trip') traveler_approval = models.BooleanField(blank=True) This is the form: class OfferExcursionForm(forms.ModelForm): def __init__(self, traveler=None, city=None, **kwargs): super(OfferExcursionForm, self).__init__(**kwargs) if traveler and city: self.fields['trip'].queryset = Excursion.objects.filter(traveler=traveler) self.fields['trip'].queryset = Excursion.objects.filter(city=city) class Meta: model = Offer exclude = ('local', 'traveler_approval') This is the other relevant model (Excursion): class Excursion(models.Model): """traveler lists his trips so local could see them and possibly offer to take him out""" traveler = models.ForeignKey(User, related_name='traveler_lists_excursion') city = models.ForeignKey(City, related_name='visited_city', blank=True, null=True) #Each excursion is connected to one City. city_search_text = models.CharField(blank=True, max_length=300) message = models.CharField(max_length=500)#message to all locals of that city "Hey good people of Edinburgh!" date = models.DateField() def __str__(self): return self.traveler.first_name.title() + " " + self.traveler.last_name.title() + "'s trip to " + self.city.name + " on " + str(self.date) This is the view: def offerexcursion(request, username): traveler = User.objects.get(username=username) if request.method == 'POST': offer_excursion_form = OfferExcursionForm(request.POST) if offer_excursion_form.is_valid(): offer = offer_excursion_form.save(commit=False) offer.local = request.user offer.traveler_approval = True offer.save() if 'next' … -
How to create nested models and get nested JSON output in Django Rest Framework?
I have an API currently built that works great for viewing, creating, updating, and deleting data. But I have run into a roadblock while trying to create my last model. The model needs to have a field that has lots of nested data in it. Here is the data I have to store: { "years": { "2017": { "hours_budgeted": 1000, "hours_actual": 1200, "quarters": { "1": { "hours_budgeted": 250, "hours_actual": 300, "weeks": { "1": { "hours_budgeted": 10, "hours_actual": 12, } "2": { "hours_budgeted": 10, "hours_actual": 12, } "3": { "hours_budgeted": 10, "hours_actual": 12, } "4": { "hours_budgeted": 10, "hours_actual": 12, } "5": { "hours_budgeted": 10, "hours_actual": 12, } "6": { "hours_budgeted": 10, "hours_actual": 12, } "7": { "hours_budgeted": 10, "hours_actual": 12, } "8": { "hours_budgeted": 10, "hours_actual": 12, } "9": { "hours_budgeted": 10, "hours_actual": 12, } "10": { "hours_budgeted": 10, "hours_actual": 12, } "11": { "hours_budgeted": 10, "hours_actual": 12, } "12": { "hours_budgeted": 10, "hours_actual": 12, } "13": { "hours_budgeted": 10, "hours_actual": 12, } } } "2": { "hours_budgeted": 250, "hours_actual": 300, "weeks": { } } "3": { "hours_budgeted": 250, "hours_actual": 300, "weeks": { } } "4": { "hours_budgeted": 250, "hours_actual": 300, "weeks": { } } } } "2018": { } … -
Testing Django Rest Framework POST returns 500 despite call working
I have a standard ModelViewSet at /test-endpoint. I am trying to use APIClient to test the endpoint. from rest_framework.test import APIClient ... self.client = APIClient() ... sample_call = { "name": "test_document", "description": "test_document_description" } response = self.client.post('/test-endpoint', sample_call, format='json') self.assertEqual(response.status_code, 201) This call works with the parameters I set in sample_call. It returns a 201. When I run the test, however, I get a 500. How can I modify this to get the 201 passed? I run the tests with python src/manage.py test modulename To rule out the obvious, I copy-pasted the sample call into Postman and run it without issue. I believe the 500 status code is coming from the fact that I'm testing the call and not using it in a live environment. No error messages are being thrown beyond the AssertionError: AssertionError: 500 != 201 -
how can I distinct a queryset but also select what is needed in different field? django
A bit hard to explain within few lines but what I am trying to get from the queryset is to remove all duplicated names but also return a boolean field. I think it'll be easier to show examples. Model.order_by('-selected', 'name').distinct('selected', 'name') this would give me queryset and what's inside would be something like for my output.. [ { "selected": true, "id": 163, "name": "11111111" }, { "selected": true, "id": 178, "name": "22222222222" }, { "selected": false, "id": 152, "name": "152-JE" }, { "selected": false, "id": 163, "name": "11111111" }, { "selected": false, "id": 178, "name": "22222222222" }, { "selected": false, "id": 213, "name": "mingzi" } ] What I want for my output is to distinct all duplicated names and show selected: True (if there is one. If there is no True, show the one that's with False but now it would show both. I wanted to do distinct('name'), I don't have to use order_by but I thought by doing it, it would make the one with True on top and then distinct those at bottom. I cannot only do order_by('select') then distinct('name') since what's in order_by needs to be in distinct. Can someone please give me a hand? Thanks in … -
Django - data migrations + db dump
Consider I have a DB with some initial data loaded using data migrations. Since the initial loading, the data has been further changed by users of the app via the website. Of course, these changes are not recorded in additional data migrations since they happen in realtime. So the data migrations are somewhat redundant since they don't capture all the changes made by the users. Now, I want to deploy the app onto a new server and DB. So I take a dump of the current database, then log onto the new server and use the dump to initialize the new DB. What I'm confused about is: if I then run the aforementioned data migrations on the new DB, they will add redundant outdated data, no? More generally, my confusion lies in how to make data migrations and db dumps work together when deploying an existing web app onto a new server+DB. Is there a better way to think about this? -
Django ajax wouldnt work when in separate file
I have django site that uses ajax. When i use javascript inside html document <script>...</script> everything works fine. But when i move javascript to separate file everything (all javascript) works great, but ajax. On every ajax request i get: 404 (Not Found) and it always show the line of the document where ajax starts. My urls are like this: url(r'^(?P<letnik_id>[1-4])/(?P<classes_id>[A-G])/(?P<subject_id>[\w\-]+)/dodaj$', views.create_exam, name="create_exam"), In views: def create_exam(request, letnik_id, classes_id, subject_id): ... and ajax url: $.ajax({ url: "{% url 'create_exam' letnik_id=letnik_id classes_id=classes_id subject_id=subject_id %}", ... Maybe if in separate file the {% url 'create_exam' letnik_id=letnik_id classes_id=classes_id subject_id=subject_id %} wont work? But is there any other way to point to the url? What am i doing wrong? -
from gcm.models import get_device_model ImportError: No module named models
I got a sample Django Rest project. When I run: python manage.py makemigrations I get the error: from gcm.models import get_device_model ImportError: No module named models in line from gcm.models import get_device_model What is the problem with this line? please help. I am a newbie in python as well as to Django -
How to build up the sub queryset in django in case of follwoing example?
I need to create a queryset in django of the following PostgreSQL statement. SELECT * FROM ( SELECT DISTINCT ON("atech_cars". "model") "atech_cars". "make", "atech_cars". "model", "atech_cars". "trim" FROM "atech_cars" WHERE(UPPER("atech_cars". "make"::text) = UPPER('Ford') AND "atech_cars". "model" IN(SELECT U0. "char_value" AS Col1 FROM "clf_atech_filter_cache" U0 WHERE U0. "filter_id" = 7)) ) Sub ORDER BY CASE WHEN ("model" = 'xD') THEN 0 WHEN ("model" = 'Cayenne') THEN 1 WHEN ("model" = 'Elantra') THEN 297 ELSE NULL END ASC I've already created a query set of the following statement. SELECT DISTINCT ON("atech_cars". "model") "atech_cars". "make", "atech_cars". "model", "atech_cars". "trim" FROM "atech_cars" WHERE(UPPER("atech_cars". "make"::text) = UPPER('Ford') AND "atech_cars". "model" IN(SELECT U0. "char_value" AS Col1 FROM "clf_atech_filter_cache" U0 WHERE U0. "filter_id" = 7)) so eventually, I'm looking for queryset of the following statement. SELECT * FROM ( <Queryset> ) Sub ORDER BY CASE WHEN ("model" = 'xD') THEN 0 WHEN ("model" = 'Cayenne') THEN 1 WHEN ("model" = 'Elantra') THEN 297 ELSE NULL END ASC Here is the django queryset I've created but it's not working. trims = AModel.objects.filter(filter_id = 9).values_list('char_value', flat=True).order_by("counter") preserved = Case(*[When(trim=trim, then=pos) for pos, trim in enumerate(trims)]) return qs.filter(model__iexact = value).filter(trim__in=trims).distinct("trim") Thanks -
Object-level Permissions
I am sure that this is fairly straightforward, but I have scoured the documentation and I can't quite figure out how to do this. I have extended my User class to have two ManyToMany relationships to other users: trainers and teammates. If a user owns an object (defined by a user ForeignKey on the model), then that user should be able to GET, POST, PUT, PATCH, and DELETE. I have set up these endpoints with ModelViewSet. If a user is a trainer of the owner, they should have the same privileges. If a user is a teammate of the owner, they should only be able to GET. In a list view of these objects, a user should only see the objects they own and the objects where they are a trainer or teammate of the owner. If they try and access a detail view of an object where they are not the friend or the teammate of the owner, it should return a 403. I extended BasePermission as follows to try and create this behavior -- I then added it to the ModelViewSet where I wanted this behavior. class TrainerAndOwnerOrTeammate(permissions.BasePermission): def has_object_permission(self, request, view, obj): user = request.user owner = … -
django filter with icontains doesn't work
hey guys i try to execute this query with icontains condition User.objects.filter(email__icontains='something') the situation here is the email field is a custom field, this class storage the encrypt value in the database, and decrypt the value again when i need call the object class AESEncryptedField(models.TextField): def get_prep_value(self, value): if value is not None: return cryptography.encrypt(value) else: return None def from_db_value(self, value, expression, connection, context): try: return cryptography.decrypt( super(AESEncryptedField, self).to_python(value) ) except TypeError: """ Field isnt encrypted on the database, but it will be on the first model.save() """ return super(AESEncryptedField, self).to_python(value) def formfield(self, **kwargs): defaults = {'max_length': self.max_length, 'widget': forms.TextInput} defaults.update(kwargs) return super(AESEncryptedField, self).formfield(**defaults) and here is the model class User(AbstractBaseUser): email = AESEncryptedField( verbose_name='correo', max_length=255, unique=True ) when execute this query works fine User.objects.filter(email='something@example.com') but when use email__icontains condition doesn't work, the result is empty. Someone knows if a need override some method? thanks in advance!! -
PHP or Django ?Which language is better for web developing, specially for creating networking or community websites? [on hold]
Well, guys, I know this is always a burning question for the beginners like me to choose a programming language for creating websites or web applications. But I'm seriously in a fix to choose between PHP and Django ! Although I started with PHP being inspired by Facebook & most other websites, But a month ago my friend told me about Python as well as Django . Then I took a look around the web found that Python is empowering Tech Giants like Google, Youtube & much more. So it's being a little complicated ! I take my greatest interest in making community or networking based website where people can gather and discuss and share things, so can you really help to choose the better one that will enable me to do most work with better power, user friendliness, and support through ensuring better security( data encryption , password hashing, SQL protection etc.) I'm newbie in web developing, so it'll be kind enough to let me suggestion to choose the best one ! Thanks in Advance :) -
Django - Constructing a Model Object With a User
I have the following model: from __future__ import unicode_literals from django.db import models from cms.models import Item from django.contrib.auth.models import User class Cart(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) items = models.ManyToManyField('cms.Item') I tried constructing an object of this type two different ways. Method 1: cart = Cart(owner=request.user) cart.save() Method 2: cart = Cart() cart.owner = request.user cart.save() The first way works and the second generates a NOT NULL constraint failed error. Why does this happen? -
Django-Taggit saving tags from a model field
I am building a post editor for my website. One of the fields I can edit is for tags. However when I save the post everything updates correctly and no errors are thrown but any changes I made to the tags field are not saved. # Views.py class EditPostView(UpdateView): form_class = EditPostForm model = Post template_name = 'myapp/editpost.html' def get(self, request, pk): if (not request.user.is_superuser): return HttpResponseForbidden() post = Post.objects.get(id=pk) if (post is None): return HttpResponseNotFound() form = self.form_class(instance=post) return render(request, self.template_name, {'form': form, 'post': post}) def post(self, request, pk): if (not request.user.is_superuser): return HttpResponseForbidden() post = Post.objects.get(id=pk) if (post is None): return HttpResponseNotFound() form = self.form_class(request.POST, instance=post) if (form.is_valid()): post.title = form.cleaned_data['title'] post.content_type = form.cleaned_data['content_type'] post.screenshot = form.cleaned_data['screenshot'] post.tags = form.cleaned_data['tags'] post.body = form.cleaned_data['body'] post.nsfw = form.cleaned_data['nsfw'] post.allow_comments = form.cleaned_data['allow_comments'] post.display_edited = form.cleaned_data['display_edited'] post.files = form.cleaned_data['files'] post.date_edited = datetime.now() post.save() return redirect('/posts/' + str(post.id)) else: return HttpResponseNotFound() return HttpResponseNotFound() #Forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content_type', 'screenshot', 'body', 'tags', 'nsfw', 'allow_comments', 'files'] widgets = { 'screenshot': forms.TextInput(attrs={'placeholder': 'URL...'}), 'tags': TagWidget(), } labels = { 'files': 'Attachments', } # Models.py class Post(models.Model): title = models.CharField(max_length=256) disclaimer = models.CharField(max_length=256, blank=True) BLOGS = 'blogs' APPLICATIONS = 'applications' … -
pycharm unresolved reference on new file added to Django Project
I added a new python file chartcall.py to my django (1.11.1) project in Pycharm 2017.1.3/ Python 3.6. When I import this new file into my views.py I get an unresolved reference on the import. This is only happening with the scripts I created. chartcall does run when I debug it. Thanks ahead of time for the input. from django.shortcuts import render import chartcall def home(request): orders, dollars = orders_by_day() return render(request, 'home.html', {orders, dollars}) -
Facebook authentication using angular JS and Django
I'm a beginner in both angular JS and django. I was following this particular tutorial in making a facebook authentication app. http://cbdev.blogspot.in/2014/02/facebook-login-with-angularjs-django.html I've followed the tutorial exactly. And when I start the server I get the error. NameError at / name 'strategy' is not defined Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.3.1 Exception Type: NameError Exception Value: name 'strategy' is not defined Exception Location: /root/Documents/django/clueless/clueless_engine/../clueless_engine/views.py in <module>, line 1 Python Executable: /root/Documents/django/clueless/bin/python Python Version: 2.7.13 Python Path: ['/root/Documents/django/clueless/clueless_engine', '/root/Documents/django/clueless/lib/python2.7', '/root/Documents/django/clueless/lib/python2.7/plat-x86_64-linux-gnu', '/root/Documents/django/clueless/lib/python2.7/lib-tk', '/root/Documents/django/clueless/lib/python2.7/lib-old', '/root/Documents/django/clueless/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/root/Documents/django/clueless/local/lib/python2.7/site-packages', '/root/Documents/django/clueless/lib/python2.7/site-packages'] Server time: Thu, 1 Jun 2017 07:30:14 +0530 my views.py file is @strategy() def auth_by_token(request, backend): backend = request.strategy.backend user=request.user user = backend.do_auth( access_token=request.DATA.get('access_token'), user=user.is_authenticated() and user or None ) if user and user.is_active: return user# Return anything that makes sense here else: return None @csrf_exempt @api_view(['POST']) @permission_classes((permissions.AllowAny,)) def social_register(request): auth_token = request.DATA.get('access_token', None) backend = request.DATA.get('backend', None) if auth_token and backend: try: user = auth_by_token(request, backend) except Exception, err: return Response(str(err), status=400) if user: strategy = load_strategy(request=request, backend=backend) _do_login(strategy, user) return Response( "User logged in", status=status.HTTP_200_OK ) else: return Response("Bad Credentials", status=403) else: return Response("Bad request", status=400) -
How in django create last event activity list?
I have model Project. Also I have models as Characterictic and Task which are related with Project. In other words every project has sections like Characterictic and Task. Users can add comment to any characterictic or task objects. I want to show in template last 10 activity which was in current project. Order that list by time. As you can see from the modals every Characterictic and Task has fields like: revision_date (Last time of update) and creation_date (Date of creation). Also Comment model has field created which show when comment was created. For example: 1) Comment was added to Task A in that time 2) Characterictic B was edited in that time. 3) Comment was added To Characterictic C. 4) Characterictic A was created. models.py: class Project(models.Model): name = models.CharField(_('Name'), max_length=250) create_time = models.DateTimeField(auto_now_add=True) # Дата создания записи revision_date = models.DateTimeField(_('Date of last update'), auto_now=True) # Дата последнего обновления записи class Characteristic(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) description = models.TextField(_('Description')) comments = models.ManyToManyField("Comment") create_time = models.DateTimeField(auto_now_add=True) revision_date = models.DateTimeField(_('Date of last update'), auto_now=True) class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) description = models.TextField(_('Description')) comments = models.ManyToManyField("Comment") create_time = models.DateTimeField(auto_now_add=True) revision_date = models.DateTimeField(_('Date of last update'), auto_now=True) class Comment(models.Model): author = models.ForeignKey(User, … -
Django OS dependencies in docker
I'm new to docker, I'm trying to mimic our live env using docker on my macOS for development. I've been through the tutorial https://docs.docker.com/compose/django/#define-the-project-components and was successful with this. However my requirements file is as per below: boto==2.43.0 boto3==1.4.4 botocore==1.5.55 ciscoconfparse==1.2.47 Django==1.10.6 django-appconf==1.0.2 django-auth-ldap==1.2.10 django-dbtemplates==2.0 django-debug-toolbar==1.7 easy-thumbnails==2.3 easysnmp==0.2.4 ipaddr==2.1.11 ipaddress==1.0.18 Jinja2==2.9.5 MySQL-python==1.2.5 netmiko==1.2.8 O365==0.9.5 orionsdk==0.0.6 paramiko==2.1.2 python-dateutil==2.6.0 python-ldap==2.4.32 pytz==2016.10 sqlparse==0.2.3 urllib3==1.10.2 and some of these have OS dependencies (i.e MySQL and ldap to name some) would this mean I cannot use the python:2.7 image in docker my working test file is as below:- #set base image FROM python:2.7 MAINTAINER Alex y <alex@app.com> RUN mkdir -p /var/www/itapp # Set the working directory to /app WORKDIR /var/www/itapp # Copy the current directory contents into the container at /app ADD . /var/www/itapp # Install any needed packages specified in requirements.txt RUN pip install -r requirements.txt I've figured as our live server runs centos7 I would need to use this so I built a new docker file #set base image FROM centos:centos7.2.1511 MAINTAINER Alex y <alex@app.com> #install yum dependencies RUN yum -y update \\ && yum -y install yum-plugin-ovl \ && yum -y install epel-release \ && yum -y install net-tools \ && yum … -
Illicit mix of collations in MySQL when inserting unicode to database
I'm running into this error when inserting lines containing unicode characters during django tests: InternalError: (1267, u"Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8mb4_general_ci,COERCIBLE) for operation '='") Culprit: نعليقات و Now then I did some research and it was suggested for me to do: SET collation_connection = 'utf8_general_ci' ALTER DATABASE your_database_name CHARACTER SET utf8 COLLATE utf8_general_ci ALTER TABLE your_table_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci I followed this example and did this instead in django: cursor = connection.cursor() cursor.execute('SHOW TABLES') results = [] for row in cursor.fetchall(): results.append(row) cursor.execute( 'ALTER DATABASE mydb CHARACTER SET utf8mb4 ' 'COLLATE utf8mb4_general_ci;') for row in results: cursor.execute( 'ALTER TABLE %s CONVERT TO CHARACTER SET utf8mb4 ' 'COLLATE utf8mb4_general_ci;' % (row[0])) Note: The reason why I need it to be mb4 is because I need to support emojis: Happy Birthday! タクミ!🎂🎂