Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Migration foreign key field type not matching current type
I am working with MSSQL database and I have some tables that were already created before Django enters the show, so with inspectdb I got the models with managed=False Meta option. Then I create others that work with Django migrations. This models are something like this: class ModelAlreadyCreated(models.Model): # This PK field is set as varchar(16) id = models.CharField(primary_key=True, db_column='CVE', max_length=16) ...other fields class Meta: managed=False class DjangoModel(models.Model): model_ac_fk = models.ForeignKey(ModelAlreadyCreated) ... other fields When I create the migrations file using makemigrations I get this: migrations.CreateModel( name='DjangoModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('model_ac_fk', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='ModelAlreadyCreated')), ... ], ), Until this point everything seems ok, but with the migrate command this error is shown: django.db.utils.OperationalError: (1778, "Column 'CVE' is not the same data type as referencing column 'model_ac_fk' in foreign key 'model_ac_fk_fk_CVE'.DB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\nDB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n") This error comes out because Django is trying to create a nvarchar(16) foreignkey field and the actual referenced field is varchar(16) I can get the SQL using sqlmigrate and alter the field types, then run it directly in the DB … -
duplicate key value violates unique constraint "auth_user_username_key"DETAIL: Key (username)=(None) already exists
I want to register a user using a custom register model but I keep getting the following error : duplicate key value violates unique constraint "auth_user_username_key"DETAIL: Key (username)=(None) already exists How do I fix this error. This is the code I have created thus far: In urls.py I create url configurations for the various pages. from django.conf.urls import url from django.contrib.auth.views import login from . import views urlpatterns = [ url(r'^$', views.nest, name = 'nest'), url(r'^login/$', login, {'template_name' : 'Identities/login.html'}, name = 'login'), url(r'^register/$', views.register, name = 'register'), ] In forms.py I create the custom registration form. from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm # Create custom user registration class CreateAccountForm(UserCreationForm): email = forms.EmailField(required = True) class Meta: model = User fields = ( 'first_name', 'last_name', 'email', 'password1', 'password2' ) def save(self, commit = True): user = super(CreateAccountForm, self).save(commit = False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user In views.py I created the register view function. from django.shortcuts import render, redirect from Identities.forms import CreateAccountForm # Create your views here. def nest(request): return render(request, 'Identities/nest.html') def register(request): if request.method == 'POST': form = CreateAccountForm(request.POST) if form.is_valid(): form.save() else: … -
Django and Reactjs
Good day. Let me start by saying I'm new to react js. I've seen a lot of write-ups on using react and Django using django-webpack-loader and webpack-bundle-tracker and I must say that I've followed them but no success. First of all, I'm confused. Which server do I run? py manage.py runserver Or webpack --config webpack-config.js -watch What does django-webpack-loader do? I don't even know if I've asked all the questions I should ask. How do I go about this? -
I Want View where a list of posts under a Category displays alone
am working on a simple news website using Django. My issue is that, i want to be able to have posts under a certain category listed under it in one view when a user clicks on a category (e.g Sports)... i made two classes in my models and they are: class Category(models.Model): POLITICS = 'Politics' SPORTS = 'Sports' ENTERTAINMENT = 'Entertainment' TECHNOLOGY = 'Technology' CHOICE_CATEGORY_TYPE = ( (POLITICS, 'Politics'), (SPORTS, 'Sports'), (ENTERTAINMENT, 'Entertainment'), (TECHNOLOGY, 'Technology'), ) category_type = models.CharField(max_length=50, choices=CHOICE_CATEGORY_TYPE, default=None) def __str__(self): return self.category_type class Post(models.Model): category_type = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=100) author = models.CharField(max_length=100) pub_date = models.DateField() photo = models.ImageField() body = models.TextField() def __str__(self): return self.title Secondly, here are my views: def index(request): posts = Post.objects.all() return render(request, 'blog/index.html', {'posts': posts}) def detail(request, pk): article = get_object_or_404(Post, pk=pk) return render(request, 'blog/detail.html', {'article': article}) def categories(request, category_type=None): category_post = get_object_or_404(Category, category_type=category_type) post_list = Post.objects.all() return render(request, 'blog/category.html', {'category_post': category_post, 'post_list': post_list}) Lastly my urls: from django.conf.urls import url from . import views app_name = 'blog' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<pk>[0-9]+)/$', views.detail, name='detail'), url(r'^categories/(?P<category_type>[0-9]+)/$', views.categories, name='categories'), ] lastly, this is the error i get when i try create a hyperlink in a Category name to lead … -
Pulling and Treating NHL data to handle it in Excel
I have a friend who wants to pull NHL data from an API in such a way he could treat it directly in Excel. In fact, he has got a tremendous experience with Excel and wants to make predictions with it. I would like to create a little web application so that he could make his request easily, directly from an interface. https://www.quora.com/Is-there-any-JSON-API-available-for-getting-NHL-information-rosters-lineups-statistics-etc Questions: 1- If I pull NHL data inside a .csv file, ill he be able to process information in Excel from that file? 2- Assume I finished this web application, and the API used is no longer supported. I will need to change of API and refactor the entire code so that it will work with the new one. Is there a sort of wrapper I could use to avoid that kind of problem? A type of problem I could encounter is to have to reformat the 'pulling file' so that it could work with my application. -
Why I have only one album?
I'm started learning Django and there are some problems with it:) This is views.py from django.http import HttpResponse from .models import Album def index(request): all_albums = Album.objects.all() html = '' for album in all_albums: url = '/music/' + str(album.id) + '/' html += '<a href ="' + url + '">' + album.album_title + '</a><br>' return HttpResponse(html) There is class Album. This is models.py from django.db import models class Album(models.Model): artist = models.CharField(max_length=250) album_title = models.CharField(max_length=250) genre = models.CharField(max_length=250) I created two albums(for example "Red" and "Destiny" and I want my albums with references appears on page http://127.0.0.1:8000/music/ . But there is only one album "Red". I think that my loop "for" doesn't working, but I can't understand why. I hope you'll understand my question. Help me please, I want to sleep :) -
Invalid object when adding geoJSON data on a Leaflet map with Django serializer
I'm developing a Django application using Leaflet and Postgresql / PostGIS. When I'm trying to add a MultiLineString layer on a map sending a GeoJSON Feature Collection object, it raises an invalid object error. At first my views.py: from geonode.geoloc.models import Transport from django.template import RequestContext from django.core.serializers import serialize class LookupView(FormView): template_name = 'geoloc/lookupresults.html' form_class = LookupForm def get(self, request): return render_to_response('geoloc/lookup.html', RequestContext(request)) def form_valid(self, form): # Get data latitude = form.cleaned_data['latitude'] longitude = form.cleaned_data['longitude'] # Look up roads roads = Transport.objects.all()[0:5] roads_json = serialize('geojson', roads, fields=('geom',)) # Render the template return self.render_to_response({ 'roads_json': roads_json }, content_type = 'json') my template when the form is valid: {% extends "geoloc/geoloc_base.html" %} {% block content %} {% load leaflet_tags %} {% leaflet_js %} {% leaflet_css %} <div id="mapid" style="width: 600px; height: 400px;"></div> <script> var geojsonFeature = "{{ roads_json }}"; var mymap = L.map('mapid').setView([51.505, -0.09], 13); L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'}).addTo(mymap); var myroads = L.geoJSON().addTo(mymap); myroads.addData(geojsonFeature); </script> {% endblock %} When I tested the geoJSON object (that Django serializer sends) in http://geojsonlint.com/, I realized that the object is invalid because of the following lines: "crs": { "type": "name", "properties": { "name": "EPSG:4326" } which as I read is "an old-style … -
After upgrade to Django 1.11 append_slash no longer works
In Django 1.9 (and Python 3.4) the default of APPEND_SLASH worked correctly, i.e. I could enter 'localhost:8000/ideatree/videos' and the trailing slash would be added. After an upgrade to Django 1.11 (and Python 3.6), APPEND_SLASH is no longer working. I've looked for deprecation notices but so far found nothing that seems to apply. (side question: how do you turn 'loud deprecation warnings' back on, as they were in previous versions?) Here is my main urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^(?i)ideatree/', include('ideatree.urls'), name='home'), ] and the urls.py from the included app_space: from django.conf.urls import url from . import views app_name = 'ideatree' urlpatterns = [ url(r'^$', views.index,name='index'), url(r'^(?i)features/$', views.features, name='features'), url(r'^(?i)videos/$', views.videos, name='videos') ] Both these url.py files are unchanged except that in Django 1.9 I had from django.conf.urls import patterns, include, url in the main urls.py, but 'patterns' is now deprecated and throws a warning. As before, I do not have APPEND_SLASH set in settings.py, relying on its default value of True, though I tried explicitly setting it to True with the same result. Here's my middleware: MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Here's the error: Page … -
Django-admin dynamics variables
% block content %} <div id="content-main" class="inner-two-columns"> <form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="{{ form_url }}" method="post" id="{% firstof opts.model_name opts.module_name %}_form" class="form-horizontal" novalidate> <div class="inner-right-column"> <div class="box save-box"> {% block submit_buttons_bottom %}{% submit_row %}{% endblock %} <input type="submit" value="Kaydet ve Kapat"> </div> i just wondering where is coming from these variables such as {submit_button_bottom} {submit_row}. I couldnt find anything about these variables. -
Django 1.11.5 on Apache with mod_wsgi giving ImportError: No module named site
[Fri Sep 29 14:46:35.808072 2017] [wsgi:info] [pid 35637] mod_wsgi (pid=35697): Process 'swpdoc' has died, deregister and restart it. [Fri Sep 29 14:46:35.808113 2017] [wsgi:info] [pid 35637] mod_wsgi (pid=35697): Process 'swpdoc' terminated by signal 1 [Fri Sep 29 14:46:35.808116 2017] [wsgi:info] [pid 35637] mod_wsgi (pid=35697): Process 'swpdoc' has been deregistered and will no longer be monitored. [Fri Sep 29 14:46:35.808944 2017] [wsgi:info] [pid 35699] mod_wsgi (pid=35699): Starting process 'swpdoc' with uid=48, gid=48 and threads=15. [Fri Sep 29 14:46:35.809868 2017] [wsgi:info] [pid 35699] mod_wsgi (pid=35699): Python home /var/www/swpdoc/venswpdoc. [Fri Sep 29 14:46:35.809895 2017] [wsgi:info] [pid 35699] mod_wsgi (pid=35699): Initializing Python. ImportError: No module named site If i use a project with django 1.9.5. it is working find and updating the django to newer version giving this error. Anyone help ? -
How can I use xgboost in heroku
I'm creating my first Django machine learning app on Heroku, but there is an error even that code passed in development env. Here are a code and an error message. from sklearn.externals import joblib clf = joblib.load('clf.pkl') clf.predict_proba(x) File "/app/.heroku/python/lib/python3.6/site-packages/xgboost/sklearn.py", line 475, in predict_proba class_probs = self.booster().predict(test_dmatrix, TypeError: 'str' object is not callabl ※ I already confirmed "x" has no string. I can use this code in development env. How can I use xgboost in heroku? -
Not properly render image from Django model
I am making a simple app(Django version 1.11+python3.5+). I want to show images on my homepage(web app) from Django models. I can upload successfully from Django admin panel. But image cant renders properly. The image does not show in the homepage. This is my HTML file. {% extends "shop/base.html" %} {% block content_area %} {% for name in products %} <div class="col-lg-3 col-md-3"> <div class="main_content_sidebar"> <div class="content_title"> <h2>{{name.product_name}}</h2> </div> <div class="image_space"> <img src="{{name.product_image.url}}" class="img-thumbnail" alt=""> </div> <div class="content_p"> <p>Retail Price:{{name.product_retail_price}}</p> <p>Quantity: {{name.product_quantity}}</p> <p>Date: {{name.product_sell_date}}</p> </div> </div> </div> {% endfor %} {% endblock %} This is my models.py file. class ProductsName(models.Model): product_name=models.CharField('name', max_length=50) product_retail_price=models.IntegerField('retail price TAKA') product_quantity = models.IntegerField('quantity') product_sell_date=models.DateTimeField('buy date', auto_now_add=True) product_image = models.ImageField(upload_to='upload/', blank=True, null=True) def __str__(self): return self.product_name When I visit my homepage, I can't see any image. But I see image link If I open my browser dev tools. chrome dev tool if I click that image link from chrome dev tool. I got andjango doesn/t found that image url error. -
How to use Django template context processor and form together?
I am a newbie to Django. In a project I have to take inputs for multiple models in Django using forms. For every model I have written functions (in views.py) and its corresponding Django template (in template folder). Such as,my Add Teacher function is, def add_teacher(request): form = TeacherForm() if request.method=="POST": form = TeacherForm(request.POST) if form.is_valid(): form.save(commit=True) return index(request) else: print(form.errors) return render(request,"billing/add_teacher.html",{"form":form}) And billing/add_teacher.html template is, <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Add Teacher</title> </head> <body> <h1>Add a Discipline</h1> <div> <form id="teacher_form" method="post" action="/billing/add_teacher/"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% for field in form.visible_fields %} {{ field.errors }} {{ field.help_text }} {{ field }} {% endfor %} <input type="submit" name="submit" value="Add Teacher"/> </form> </div> </body> </html> Now, I want to use a template for all of my functions.Such as, I want to use this template for all functions with the help of Django template context processor. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ title }}</title> </head> <body> <h1>{{ h1 }}</h1> <div> <form id={{ form_id }} method="post" action="{{ action }}"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% for field … -
Django URL complicated patterns and paths
I'm trying to generated nested url paths. So far I could only generate 1 level urls. When I try second level urls it doesn't get called anymore, it still only shows the first level url although the address bar on the browser does direct to the second level url. Is this possible or do I need to create a new app? urls.py from django.conf.urls import url, include from django.views.generic import ListView, DetailView, TemplateView from dashboard.models import IPARate,PCPRate from dashboard import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^medicare/', ListView.as_view(queryset=IPARate.objects.all().order_by("id"), template_name='dashboard/medicare.html')), url(r'^medicare/medicarepcp/$', ListView.as_view(queryset=PCPRate.objects.all().order_by("id"), template_name='dashboard/medicarepcp.html')), url(r'^medicare/', views.medicaid, name='medicare'), url(r'^medicare/medicarepcp/$', views.medicarepcp, name='medicarepcp'), ] -
jQuery keyup event is activated multiple times, doubling every time its triggered
I added an auto-completing search bar to my website. It queries the database for elements that start with the entered string every time the user types a new character. It works fine, however every time the user adds another character or does any keyboard event like backspace it doubles the event activation. 1,2,4,8,16, etc.. times. How could I make it so that it doesn't accumulate event triggers and only triggers .keyup() one time per keyboard event? Here's the HTML code: <form> <div class="nav-item"> <input class="search-query form-control" placeholder="Items" type="text" name="items" value="" id="id1" /> </div> </form> <hr> <div id="id2"> </div> And here's the jQuery code: $(document).ready(function() { $('#id1').keyup(function(){ var query = $(this).val(); $.get('/url/', {items: query}, function(data){ $('#id2').html(data); }); }); -
django create gif and store in DB
I'm receiving files from an input via a POST request. I'd like to take to those create a GIF from them and store it directly in a sqlite database. I have found various ways in python to create GIFs out of images and save them to the file system like the one here VALID_EXTENSIONS = ('png', 'jpg') def createGIF(data, duration=0.2): images = [] for d in data: images.append(imageio.imread(d)) output_file = 'Gif-%s.gif' % datetime.datetime.now().strftime('%Y-%M-%d-%H-%M-%S') imageio.mimsave(output_file, images, duration=duration) but I was not able to find a way of creating the GIF and either store it into variable or save it into the DB directly. Is there any way of creating a GIF and not have to save it to disk first before putting it in a DB? -
django dropdown item hyperlink not working when clicking
I am building a Django app and everything is working except the link in a dropdown menu. I have followed everything that was necessary, but somehow the link does not make Django to render the page. Under More the link About should work, but it does not. I include the code and also I have deployed it temporarily for a production inspection: http://azeribocorp.pythonanywhere.com/index html: {% load static %} {% load staticfiles %} {% block stylesheets %} <link rel="stylesheet" type="text/css" href="{% static 'css/_topnavbar.css' %}"> {% endblock %} <!--Top Navigation--> <nav role="navigation" class="nav" id="topnav"> <ul class="nav-items"> <li class="{% if request.resolver_match.url_name == 'index' %} nav-item active {% else %} nav-item {% endif %}"> <a href={% url 'index' %} class='nav-link'><span>Home</span></a> </li> <!--<li class="nav-item"> <a href={% url 'index' %} class="nav-link" ><span>Home</span></a> </li>--> <li class="{% if request.resolver_match.url_name == 'track_containers' %} nav-item active {% else %} nav-item {% endif %}"> <a href={% url 'track_containers' %} class='nav-link'><span>Track Containers</span></a> </li> <nav class="submenu"> <ul class="submenu-items"> <li class="submenu-item"><a href="#" class="submenu-link">Product #1</a></li> <li class="submenu-item"><a href="#" class="submenu-link">Product #2</a></li> <li class="submenu-item"><a href="#" class="submenu-link">Product #3</a></li> </ul> </nav> </li> <li class="{% if request.resolver_match.url_name == 'search' %} nav-item active {% else %} nav-item {% endif %}"> <a href={% url 'search' %} class='nav-link'><span>Search</span></a> </li> <li class="{% if request.resolver_match.url_name … -
Python web application installer packages?
Has anyone ever made an installer package for a Flask or Django (or other WSGI framework) application that lays down the code, virtualenv, configures the WSGI server (Gunicorn or uWSGI for example)? I've tried Googling the topic but I only find documentation about installing the frameworks themselves or deploying the applications to cloud services like AWS and Heroku. I know that all of the above could be scripted, but I'm interested in building actual installer packages for different platforms that get the WSGI app up and running and leaves the other needed components (such as database, cache, proxy, etc.) up to the administrator. Are there existing examples of this someone could point me to? Does anyone have suggestions on where to start for learning how to create these packages? -
Django DRY - how to simplify similar views using same template?
Please note: Just to make clear '[app_name]' is a placeholder for the actual app name. Not Django substitution code. Just imagine it says 'Stuff' instead of [app_name], if it's confusing. My question: How do I make this more DRY? There is a lot of code repetition, and there must be a way of unifying some of it. If you do answer, I would be really grateful if you write out explicitly what and why. As a lot of answers assume quite a bit of knowledge and I am trying into good habits in Django coding style and practice. Thank you for your time. [app_name]/urls.py from django.conf.urls import url from . import views app_name = 'things' urlpatterns = [ url(r'^cars/$', views.CarThingIndexView.as_view(), name='Car_index'), url(r'^trees/$', views.TreeThingIndexView.as_view(), name='Tree_index'), .... ] [app_name]/model.py from django.db import models class Tree(models.Model): """ Tree """ name_text = models.CharField(max_length=200) def __str__(self): return self.name_text class Car(models.Model): """ Car """ name_text = models.CharField(max_length=200) def __str__(self): return self.name_text [app_name]/view.py from django.views import generic from inventory.models import Car, Tree class CarThingIndexView(generic.ListView): template_name = '[app_name]/index.html' context_object_name = 'thing_list' def get_queryset(self): return Car.objects.values() class TreeThingIndexView(generic.ListView): template_name = '[app_name]/index.html' context_object_name = 'thing_list' def get_queryset(self): return Tree.objects.values() [app_name]/template/[app_name]/index.html {% extends '[app_name]/base.html' %} {% block content %} {% if … -
Gmail open tracking, set cookie with Django
I'm working on a simple app to embed a transparent pixel into emails being sent out manually with Gmail and then cookie the user. I'm inserting this <img> into the email: <img height="1" src="https://example.net/pixel.png?guid=1234" style="visibility:" width="1"> The intent is that when the email is opened it should request the image from example.net/pixel.png The Django app with an endpoint of pixel.png has this view: def set_cookie(request): PIXEL_GIF_DATA = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data = base64.b64decode(PIXEL_GIF_DATA) response = HttpResponse(data, content_type='image/gif') response.set_cookie('some_cookie_name', 'some_cookie_value') return response If I visit `example.net/pixel.png?guid=1234' it's setting the cookie appropriately, so we're good there. The only issue I'm running into is that when the email is opened the request is not being made out to my server. As the recipient if I go into the developer tools and watch the network requests I'm not seeing the request being made to mysite.net However, if I view the original email, down in the footer I can see that my <img> tag is included. If I try using an external image like static.example.net/images/sometest123.png the image does come through and is visible. -
Can I Use One view In a Django Project?
I´m new to web dev, and I was wondering if it´s possible to make a website,that just need to present informations of a company (HMTL), in just one View. Like rendering the Entire bootstrap in one view. -
Unable to install mysqlclient on centos
I am building a django app and for which i need to configure mysql.I am trying to install mysqlclient module for sql connection and this is what i am trying pip install mysqlclient --no-cache-dir It is throwing me following error.It is throwing error while linking to gcc library. Collecting mysqlclient Downloading mysqlclient-1.3.12.tar.gz (89kB) 100% |################################| 92kB 4.0MB/s Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error Complete output from command /home/admin/awx.varadev.com/awxenv/bin/python2 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-6m2TNP/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-WFoARo-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/admin/awx.varadev.com/awxenv/include/site/python2.7/mysqlclient: running install running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb creating build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.linux-x86_64-2.7 gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic … -
Django model django.db.utils.InternalError Can't DROP COLUMN
I have two models: I wanted to implement many-to-one relationship When I uncommented the school field in Weather. While migrating to the database. The error occured: django.db.utils.InternalError: (1091, "Can't DROP COLUMN school_id; check that it exists") Is there any posible reason to cause the error? class Weather(models.Model): time = models.DateTimeField() temperature = models.DecimalField(max_digits=3,decimal_places=1,default=None,null=True) humidity = models.DecimalField(max_digits=3,decimal_places=1,default=None,null=True) uv = models.IntegerField(default=None,null=True) light = models.IntegerField(default=None,null=True) rainfall = models.IntegerField(default=-1,null=True) #school = models.ForeignKey(School,related_name="weather",default=None,on_delete=models.CASCADE) def __str__(self): weather = '{0.time} {0.temperature} {0.humidity} {0.uv} {0.light} {0.rainfall}' return weather.format(self) class School(models.Model): name = models.CharField(max_length=10,null=False) eng_name = models.CharField(max_length=50,null=False) school_abbreviation= models.CharField(max_length=8,null=False) def __str__(self): school = '{0.name} {0.eng_name} {0.school_id}' return school.format(self) -
Angular couldn't find service
I'm building Angular 1.6.6 app with Django Rest Framework following tutorial by TrackMaven. My app couldn't find any services: ReferenceError: Can't find variable: retail Here is my service file: retail .factory('Chain', function ($resource) { return $resource( 'http://localhost:8000/chains/:id/', {}, { 'query': { method: 'GET', isArray: true, headers: { 'Content-Type': 'application/json' } } }, { stripTrailingSlashes: false } ) }); And my app.js: 'use strict'; var retail = angular.module("retail", []); angular .module('SampleApplication', [ 'appRoutes', 'retail', 'ngResource', ]); I think it's all about scopes but I can't figure out what's wrong. -
Can't rebuild indexes in django-haystack
I've installed Apache Solr 4.10.4, django-haystack 2.4.0, pysolr 3.3.2 and Django 1.8.6. I'm finishing make a simple blog application in Django framework. I typed following command in terminal: (my_env) pecan@tux ~/Documents/Django/mysite $ python manage.py rebuild_index but it return me an error: WARNING: This will irreparably remove EVERYTHING from your search index in connection 'default'. Your choices after this are to restore from backups or rebuild via the `rebuild_index` command. Are you sure you wish to continue? [y/N] y Removing all documents from your index because you said so. All documents removed. Indexing 3 posts ERROR:root:Error updating blog using default Traceback (most recent call last): File "/usr/lib64/python3.4/xml/etree/ElementTree.py", line 1080, in _escape_attrib if "&" in text: TypeError: argument of type 'int' is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/haystack/management/commands/update_index.py", line 188, in handle_label self.update_backend(label, using) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/haystack/management/commands/update_index.py", line 233, in update_backend do_update(backend, index, qs, start, end, total, verbosity=self.verbosity, commit=self.commit) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/haystack/management/commands/update_index.py", line 96, in do_update backend.update(index, current_qs, commit=commit) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/haystack/backends/solr_backend.py", line 75, in update self.conn.add(docs, commit=commit, boost=index.get_field_weights()) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/pysolr.py", line 807, in add m = ET.tostring(message, encoding='utf-8') File "/usr/lib64/python3.4/xml/etree/ElementTree.py", line 1125, in tostring short_empty_elements=short_empty_elements) File "/usr/lib64/python3.4/xml/etree/ElementTree.py", line 777, in write short_empty_elements=short_empty_elements) …