Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django on Production for POST request throws Server Error(500) on compute engine
I have deployed my Django 1.10 with python 3.6 Project on Google compute engine when I have changed Debug = True in my settings.py to Debug = False it throws Server Error (500) on one of my post requests.Even other post requests like signup are working fine. How can i solve this issue as i'm using Django 1.10.5, Python 3.6 on Compute Engine. Help me, please! Thanks in Advance! Here's my settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*************************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', 'brainresearchtagging.com'] # INTERNAL_IPS = ['127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'users', 'article', 'import_export', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'brain.urls' 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', ], }, }, ] WSGI_APPLICATION = 'brain.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'DB_NAME', 'USER': 'DB_USER', 'PASSWORD': 'DB_PASS', … -
Django create a view to generate a receipt
I want to create a small app that creates a kind off receipt record in to a db table, from two other tables. very much like a receipt from a grocery store where a cashier makes a sell and the ticket contains multiple items, calculates a total and subtotal and return values to the database. I currently have 3 tables: the Ticket table where i would like to insert the values of all calculations and ticket info, the services table that acts like an inventory of services available. this has the service name and price for each service and my responsible table that has a list of "cashiers" or people that will make the sale and their percentage for their commissions, i have the views to create , edit and delete cashier's and services. What I don't have is a way to create the ticket. I am completely lost. can you guys point me in to the correct path on what to look for. i am learning to program son i don't have a lot of knowledge in this if its even possible. i don't need the system to print i just want to have all record stored this way … -
Dajngo custom user error
I have a custom user model that extends an AbstractBaseUser, as well as my own user manager (GenericUserManager): class GenericUserManager(BaseUserManager): def create_user(self, username, email, password, key_expires): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError("users must have a username") if not password: raise ValueError('users must have password') user = self.model( username=username, email=self.normalize_email(email), key_expires=key_expires, ) user.set_password(password) user.save(using=self._db) return user def get_by_natural_key(self, username): return self.get(username=username) class BaseRegistrationUser(AbstractBaseUser): username = models.CharField(max_length=150, unique=True) email = models.EmailField( verbose_name='email address', max_length=255, unique=False, ) activation_key = models.CharField(max_length=90) key_expires = models.DateTimeField() is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(('date joined'), default=datetime.datetime.now) is_merchant_or_customer = models.CharField(max_length=20, null=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['username, email'] def __str__(self): return self.username ... def natural_key(self): return (self.email,) ... class Customer(BaseRegistrationUser): first_name = models.CharField(max_length=150, default="", null=True) last_name = models.CharField(max_length=150, default="", null=True) slug = models.SlugField(max_length=175, default="", null=True) objects = GenericUserManager() ... These work fine for registration purposes, however, whenever I attempt to log a 'customer' user I get the following error: File "C:\Users\OEM\Documents\repos\repo\ecommerce\myapp\views.py" in get_profile 126. user = authenticate(username=username, password=password) File "C:\Users\OEM\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\contrib\auth\__init__.py" in authenticate 70. user = _authenticate_with_backend(backend, backend_path, request, credentials) File "C:\Users\OEM\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\contrib\auth\__init__.py" in _authenticate_with_backend 115. return backend.authenticate(*args, **credentials) File "C:\Users\OEM\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\contrib\auth\backends.py" in authenticate 18. user = … -
How can I set the field unique in django?
I have a model class: class PysicalServer(models.Model): serial_number = models.CharField(max_length=64) # I want to add the unique name = models.CharField(max_length=16) I know use the primary_key can set unique, but the serial_number is not my id field, I can not use the primary_key, is there other property I can set field unique? -
Accessing Images in Static Folder
I've placed some images in /static/some_directory and Django cannot find them. But when the same images are placed in /static/images, Django is able to find them. My settings.py has the following: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' # Added to make "static" directory path relative to BASE_DIR STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) What do I need to add to make this work? Any help would be appreciated. Thanks. -
Is there a headless web driver that can run client side through a web page?
I am trying to gather information on a request by request basis. I was wondering if there was something like phantomjs that can run client side through a chrome engine or through a browser, and gather data rather than a serverside application. I came across ghost.py which can be used through django but I am not sure if that is truley client side. Does such a thing actually exist? Or does a java applet have to be used? I'm just tinkering around and I don't exactly know what to look for. Thanks in advance. -
How to persist event data in Fullcalendar when moving on and off scheduler
I have been trying to get two third party apps to play nice together, and it just hasn't been working for me, due to their names. The two apps I am trying to get to work are django-user-accounts and django-allauth. The problem is, both apps are using the same namespace "account", and I don't understand the way I'm supposed to fix them. I did find some things like this, which seem to be the way to go about fixing it, but when I try to implement it, I have two problems. It doesn't seem to do anything at all for django-user-accounts. With django-allauth, there are many different apps underneath the allauth package, and to get the account app folder for it, I have to also create the allauth folder first, which makes those other apps inaccessible. Here's what I have so far. Under my project folder I created this structure: allauth ├── account │ ├── apps.py │ └── __init__.py └── __init__.py In allauth.account.__init__, I have: from django.apps import AppConfig default_app_config = 'allauth.account.apps.CustomAccountAppConfig' In allauth.account.apps I have: from django.apps import AppConfig class CustomAccountAppConfig(AppConfig): verbose_name = 'custom account' name = "allauth.account" label = "custom_account" def __init__(self, app_name, app_module): AppConfig.__init__(self,app_name, app_module) This appears … -
Nginx Proxy-ing based on login and token
I have Nginx in front of various worker servers. I'd like to know how to proxy to a particular server based on the username which is passed in the http header, and then based on the token which is returned as a response to the login? I will need to do a database lookup with the username and store the response token for this user. Nginx is designed to be fast and doing this calculation will be costly. For my situation, it is acceptable to be slow. It is a corner case and should only be a small percentage of traffic. I see some have used Nginx's request_body here and here but this looks like a static regular expression match on the content and not a way to put in a calculation and DB access. I've knocked up a little test Django app which does the man in the middle processing, this way I can see the username and token. Currently, this is very slow and I was wondering if there is a better method before going further down this rabbit hole. LB -
Django wagtail accesing parent page variables from block templates
I have created a stream block with a custom template in my models.py file for my 'work' page as: section = StreamBlock( [ ('section', SectionStreamBlock( template = 'personal_web/blocks/work_block.html') ]) Now I am trying to access the 'work object' itself in my block template. (I am using jinja2 ) I know that I can not pass it via {% include_block block %}. Is there a way to pass it? -
Django 'debug' is False inside template (django app is running inside docker container)
So for some reason the following code is not working inside django templatge {% load staticfiles i18n %} {% load static %} <!DOCTYPE html> <html lang="en" ng-app> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>{% block title %}LIVECHAT{% endblock title %}</title> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css"> {% block css %} {% if debug %} <link href="{% static 'css/vendor.css' %}" rel="stylesheet"> <link href="{% static 'css/frontend.css' %}" rel="stylesheet"> {% else %} <link href="{% static 'css/vendor.min.css' %}"rel="stylesheet"> <link href="{% static 'css/frontend.min.css' %}" rel="stylesheet"> {% endif %} {% endblock css %} </head> I always get css/vendor.min.css and css/frontend.min.css loaded, however if I enter inside docker container and run commands inside shell_plus I see the following In [1]: from django.conf import settings In [2]: settings.INTERNAL_IPS Out[2]: ('0.0.0.0', '127.0.0.1', 'localhost', '172.29.0.7', '840bf5fa322b') In [3]: settings.DEBUG Out[3]: True In [4]: import socket ...: socket.gethostbyname(socket.gethostname()) Out[4]: '172.29.0.7' In [5]: socket.gethostname() Out[5]: '840bf5fa322b' my config contains import os import socket from .development import * host = socket.gethostname() INTERNAL_IPS = ( '0.0.0.0', '127.0.0.1', 'localhost', host ) import os from .paths import BASE_DIR DEBUG = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': … -
404 fail with pytest when 'manage.py shell' and browser don't
I want to use pytest to test a web app I'm working on. I'm starting small: def test_loading_page(client): response = client.get('/') assert response.status_code == 200 assert b'Congratulations on your first Django' in response.content According to the output of pytest, this looks to be working as intended: platform win32 -- Python 3.6.1, pytest-3.0.7, py-1.4.33, pluggy-0.4.0 Django settings: test_project.settings (from ini file) rootdir: C:\--\---\---\---\---\---, inifile: pytest.ini plugins: django-3.1.2 collected 1 items test_project.py F ================================== FAILURES =================================== ______________________________ test_loading_page _______________________________ client = <django.test.client.Client object at 0x000002440F0A17F0> def test_loading_page(client): response = client.get('/') > assert response.status_code == 200 E assert 404 == 200 E + where 404 = <HttpResponseNotFound status_code=404, "text/html">.status_code test_test_project.py:7: AssertionError ========================== 1 failed in 0.36 seconds =========================== So while the django dev server is running, test_loading_page fails because of the 404. If use my browser to go to http://127.0.0.1:8000/ the loading page is displayed. Also if I use the python manage.py shell, the following code runs correctly: from django.test import Client client = Client() response = client.get('/') response.status_code == 200 #Returns True In case it's useful, the pytest.ini file contains: [pytest] DJANGO_SETTINGS_MODULE = flawlesslinguistics.settings Versions I'm using are: Python 3.6.1 pytest-3.0.7 django-3.1.2 It's difficult to identify which articles/docs are referring to pytest … -
Connecting the symptom name and description data to the specific patient.
I am attempting to build a patient database that renders the Symptom_name and Symptom_description to the document object model. Each name and description should be attached to the patient for which it was created, however each time the fields are populated and saved the Symptom_name and Symptom_description is seen in all the patients created which is not what I want. In the below image both James and Jimmy has the same Symptom_name and Symptom_description however I only clicked the James Timmerson a tag to add the Symptom_name and Symptom_description. How do I ensure that only James Timmerson has that symptom_relation data. Essentially I want to ensure the relevant symptoms connect to the relevant patients. Here is my code : models.py from django.db import models from django.contrib.auth.models import User from Identity import settings import datetime Create your models here. class Identity_unique(models.Model): NIS = models.CharField(max_length = 200, primary_key = True) user = models.ForeignKey(settings.AUTH_USER_MODEL) Timestamp = models.DateTimeField(auto_now = True) First_Name = models.CharField(max_length = 80, null = True, ) Last_Name = models.CharField(max_length = 80, null = True, ) location = models.CharField(max_length = 100, blank = True) date_of_birth = models.DateField(auto_now = False, auto_now_add = False, blank = True, null = True) Contact = models.CharField(max_length = … -
Django ManagementForm data is missing with csrf_token and management_form
I have a form and a formset, each with its' submit button, The formset saves. and the form process data and display result on the same page. When I submit data with the form, Django shows ['ManagementForm data is missing or has been tampered with']. I have {% csrf_token %}& {{ formset.management_form }} for the formset. Not sure why, but if I use only one and one for both forms then it works fine. -
how to remove reloading the page?
How to get votes data from database without reloading the page? my models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class Post(models.Model): post = models.CharField(max_length=500) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) post_img = models.ImageField(upload_to='posts_img/') votes = models.IntegerField(default=0) my views.py def upvote(request, post_id): vote = Post.objects.get(pk=post_id) vote.votes += 1 vote.save() return redirect('home:home') my home.html {% if post.post_img %} <img class="post-img" src="{{ post.post_img.url }}"> <a href="upvote/{{ post.id }}"> vote </a>{{ post.votes }} {% endif %} <p><i>Posted on <b class="date">{{ post.created }}</b></i</p> my urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^upvote/(?P<post_id>[0-9]+)/$', views.upvote, name='upvote'), ] If I click vote link in the home page, page will reloaded and will get votes result, How do i remove reloading the page.??? my English is not good but I need your help please!. -
Python Django 1.11 "ValueError Incomplete format" in admin action when trying to update FK field
I have a simple master/detail model of Quotation (Master) containing the header info and totals, and QuotationDetail (Detail) containing the Quotation Items, this child model has a PriceLevel FK field used to calculate the markup for each individual item. I am trying to implement a Django Admin Action so the admin can change this PriceLevel on several Items at once, but I get the error: [myProjectPath]\lib\site-packages\django\contrib\admin\options.py", line 812, in get_action_choices choice = (name, description % model_format_dict(self.opts)) ValueError: incomplete format This is my models.py (on the relevant models: class NivelDePrecio(models.Model): # PriceLevel # Fields nombre = models.CharField(max_length=50) slug = extension_fields.AutoSlugField(populate_from='nombre', blank=True) valor = models.DecimalField(max_digits=7, decimal_places=4) factor = models.DecimalField(max_digits=7, decimal_places=6, null=True, blank=True) class Meta: ordering = ('-valor',) def __str__(self): return self.nombre def save(self, *args, **kwargs): self.factor = 1 / (1 - self.valor) super(NivelDePrecio, self).save() class Cotizacion(models.Model): # Quotation (master) # Fields nombre = models.CharField(max_length=100) slug = extension_fields.AutoSlugField(populate_from='nombre', blank=True, overwrite=True) fecha_ida = models.DateField(default=date.today) fecha_regreso = models.DateField(default=date.today) # Relationship Fields itinerario = models.ForeignKey(Itinerario, on_delete=CASCADE, verbose_name='itinerario') nivel_de_precio = models.ForeignKey(NivelDePrecio, verbose_name='nivel de precio', on_delete=models.PROTECT, null=True, blank=True) class Meta: ordering = ('itinerario__cliente__codigo', '-fecha_ida') def __str__(self): return str(self.nombre) class CotizacionDetalle(models.Model): # QuotationDetail (detail) # Fields descripcion = models.CharField(max_length=100, null=True, blank=True) cantidad = models.DecimalField(max_digits=10, decimal_places=2) costo = models.DecimalField(max_digits=10, decimal_places=2, … -
Django: Multiple joins between two tables on different rows
Using the Django QuerySet API, how can I perform multiple joins between the same two tables/models? See the following untested code for illustration purposes: class DataPacket(models.Model): pass class Field(models.Model): packet = models.ForeignKey(DataPacket, models.CASCADE) name = models.CharField(max_length=25) value = models.FloatField() I want to grab a list of data packets with only specific named fields. I tried something like this: pp = DataPacket.prefetch_related('field_set') result = [] for p in pp: result.append({ f.name: f.value for f in p.field_set.all() if f.name in ('latitude', 'longitude') }) But this has proven extremely inefficient because I'm working with hundreds to thousands of packets with a lot of other fields besides the latitude and longitude fields I want. Is there a Django QuerySet call which translates into an efficient SQL query performing two inner joins from the datapacket table to the field table on different rows? For example (again, untested code for illustration purposes): SELECT f1.value, f2.value FROM datapacket INNER JOIN field as f1 ON datapacket.id = f1.packet_id INNER JOIN field as f2 ON datapacket.id = f2.packet_id WHERE f1.name = 'latitude' AND f2.name = 'longitude' -
Serializing an array of data on the basis of foreign key django rest framework.
I am using django rest framework to post property_id in favorites table as a foreign key and on the basis of foreign key i want to get all fields from property table. class Favorites(models.Model): """Store favorite property""" user_id = models.ForeignKey(User, on_delete=models.CASCADE) property_id = models.ForeignKey(Property, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, blank=True) Serializer: class FavoriteSerializer(serializers.ModelSerializer): """Favorite Properties serializer""" class Meta: model = Favorites fields = ('user_id','property_id', ) Viewset: class FavoriteViewSet(viewsets.ModelViewSet): http_method_names = ['get','post' ] serializer_class = FavoriteSerializer queryset = Favorites.objects.all() Output: This is my first output. then i sync my property Serializer and get this one: This is the output i need but it creates problem during post. During post i only need user_id and property_id but it makes my post form like this: Any suggestions how i can achieve my results? -
Django Query same week last year
I need to compare sums of events in the same week (isocalendar), year over year. class MyModel(models.Model): date = models.DateTime(... hits = models.IntegerField(... I've got this sorted for last year, last month, same month last year, same day last year using variations on: same_month_last_year = MyModel.objects.filter(date__month = (datetime.datetime.now().month), date__year = (datetime.datetime.now() - relativedelta(years = 1)).year).aggregate(total=Sum('hits')['total'] I don't see an equivalent 'week' function. I can use .isocalendar()[1] on the right side of the equation but that's of no help on the left. Any ideas? Thanks. -
django query evaluation creating partition sets
I have a model foo, which has a status bar (1 - 4, say). I also have a template where I display all the records from foo for a specific user. Depending on the status bar I have slight styling differences within the template going on. Moreover I would like to seperate the different statuses with a header. How do I efficiently create these 4 partition sets? is there a difference in terms of efficiency when I use foo_user = foo.objects.filter(USER_ID = user_id) foo_user_1 = foo_user.filter(bar = 1) foo_user_2 = foo_user.filter(bar = 2) ... versus foo_user_1 = foo.objects.filter(USER_ID = user_id, bar = 1) foo_user_2 = foo.objects.filter(USER_ID = user_id, bar = 2) ... I read in the documentation that evaluation of a query is lazy which makes me think these are the same statements. But I think it would be more efficient to query the foo_user set vs the entire table over and over, or am I wrong on this? -
how does one get the profile from a user in DJango
I have code that is like the following for people logging in: if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: # Check it the account is active if user.is_active: # Log the user in. login(request, user) I have extended the User to create a UserProfile. It contains other information. Ex: address, city, state, etc. How would one extract the User profile from this situation? For Java under Eclipse, if I typed in "user", I would see all of the valid methods that would apply to the object "user". It does not appear that PyCharm has such a feature. With that being said, how can one find the profile information associated with a user? TIA -
Using Django REST Framework to display Rich Text Uploading Field
I have a Django application running on Python3 which has a basic blogging application set up. In my Post model, I have the following set up for the content of a specific post. from ckeditor_uploader.fields import RichTextUploadingField class Post(models.Model): content = RichTextUploadingField() I also have the REST framework for Django set up so that when I do a GET request to /api/posts/slug=abc-123 it runs this: class PostViewSet(viewsets.ViewSetMixin, generics.ListAPIView): """ API endpoint that allows posts to be viewed. """ serializer_class = PostSerializer def get_queryset(self): queryset = Post.objects.all() # A bunch of Django filters return queryset And would return something like this: { "title" : "Abc 123", "slug" : "abc-123, "content" : "According to a survey, &#39;93% of executives believe that an employee&rsquo;s style of dress at work influences his/her chance at a promotion&#39;.</p>\r\n\r\n<p> This is more content blah blah blah." } (Ignore the fact that the JSON has line breaks, that is for readability, assume it is a correctly formatted JSON file) As you can see the content of the result has characters like \r and \n. This gets rendered in Django using this {{content | safe}} which works fine when Django is rendering the page, but I want to display … -
Django: Problems changing the current language
I want to change the current language of my page. I'm using this HTML code to make the buttons: <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ request.get_full_path|slice:'3:' }}" /> <ul class="nav navbar-nav navbar-right language menu"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <li> <h1>{{ language }}</h1> <button type="submit" name="language" value="{{ language.code }}" class="{% if language.code == LANGUAGE_CODE %}selected{% endif %}"> {{ language.name_local }} </button> </li> {% endfor %} </ul> </form> I have no problems when I'm switching from Spanish 'es' to US English 'en-us' but when I try to switch from US English to Spanish send me this error: Not Found: /i18n/setlang/-us/ -
Push Selenium webdriver to a mixin
Django==1.11.6 Will you be so kind as to have a look at the code below. Before I commented out a part of the code, it worked fine. But then I decided to organize SeleniumMixin. Just because a lot of other tests will will need a selenium webdriver. Well, the code blows up. Could you give me a kick here? class SeleniumMixin(): @classmethod def setUpClass(cls): super(SeleniumMixin, cls).setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.selenium.quit() super(SeleniumMixin, cls).tearDownClass() class GeneralTestCaseMixin(SeleniumMixin): def __init__(self, *args, **kwargs): super(GeneralTestCaseMixin, self).__init__(*args, **kwargs) self.fixtures = ['users.yaml'] # @classmethod # def setUpClass(cls): # super(GeneralTestCaseMixin, cls).setUpClass() # cls.selenium = WebDriver() # cls.selenium.implicitly_wait(10) # # @classmethod # def tearDownClass(cls): # cls.selenium.quit() # super(GeneralTestCaseMixin, cls).tearDownClass() def login_user(self): pass ====================================================================== ERROR: test_not_loggedin_user_visits_search_page (search.tests.PermissionTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/michael/PycharmProjects/photoarchive_4/search/tests.py", line 33, in test_not_loggedin_user_visits_search_page self.selenium.get('{}{}'.format(self.live_server_url, reverse('search:form'))) AttributeError: 'PermissionTestCase' object has no attribute 'selenium' ---------------------------------------------------------------------- Ran 1 test in 7.041s FAILED (errors=1) -
Failling to build a Django project in VS 2015
I'm having a hard time building my Django project in VS 2015. Background: I have this project up and running on Eclipse so far, but I would like to import it to VS 2015 (Professional). I've download and installed VS IDE and Python Tools for VS 2.2.6. -- First, I have had a Build FAILED error with no error messages. After some googling, I've changed the options from Build output messages from Minimal to Diagnostic, and found out that the problem seemed to be with my PYTHONPATH. Then, I've added a Search Path to my python34 site-packages folder (again, after some research, I believe this is the right path). After doing so, the build now fails again, but there are several "unexpected token" errors in the same file, localed in django/contrib/admin/widgets.py. I've compared my file with the file in the official github page of django, and both files have some differences. Running the get version from the interactive window, I can see that my Django version is 1.11.6. Is overwritting this file for the one in the github a good solution? Perhaps the installation have gone wrong at some point? What should I do? -
Django - Q Object - 'i__contains' to include accents?
i have the following line of code: list = Database.objets.filter(Q(name__icontains=searchstring)) So for example if: searchstring = Georges Méliès It returns the result, but if: searchstring = Georges Melies It doesn't get it. Is there any way i can "tell" Django to ignore accents on letters? Such as here in the case of e?