Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Images are not in ImageAndUser model
Images are not in ImageAndUser model.I wrote in views.py like @csrf_exempt def upload_save(request): if request.method == "POST": form = UserImageForm(request.POST, request.FILES) if form.is_valid(): data = ImageAndUser() data.image = request.FILES['image'] data.save() else: print(form.errors) else: form = UserImageForm() return render(request, 'registration/accounts/photo.html', {'form': form}) index.html is <form action="{% url 'accounts:upload_save' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <h2>SEND PHOTO</h2> <div class="input-group"> <label class="input-group-btn"> <span class="btn btn-primary btn-lg"> SELECT FILE <input type="file" style="display:none" name="files[]" multiple> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <div class="form-group"> <input type="submit" value="SEND" class="form-control"> </div> </form> When I put SEND button, upload_save method is read.And my ideal system is image& user's data put in ImageAndUser model.However,now ImageAndUser model does not have the data.I really cannot understand why.But terminal says <ul class="errorlist"><li>user<ul class="errorlist"><li>This field is required</li></ul></li></ul> so I think i cannot get user data.However,I think user can access upload_save method after he log in the site, so I think the system has user data.I do not know why image&user data is not connected. models.py is class ImageAndUser(models.Model): user = models.ForeignKey("auth.User", verbose_name="imageforegin") image = models.ImageField(upload_to='images/', null=True, blank=True,) How can I fix this?What should I write it? -
Django encoding error when reading from a CSV
When I try to run: import csv with open('data.csv', 'rU') as csvfile: reader = csv.DictReader(csvfile) for row in reader: pgd = Player.objects.get_or_create( player_name=row['Player'], team=row['Team'], position=row['Position'] ) Most of my data gets created in the database, except for one particular row. When my script reaches the row, I receive the error: ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.` The particular row in the CSV that causes this error is: >>> row {'FR\xed\x8aD\xed\x8aRIC.ST-DENIS', 'BOS', 'G'} I've looked at the other similar Stackoverflow threads with the same or similar issues, but most aren't specific to using Sqlite with Django. Any advice? If it matters, I'm running the script by going into the Django shell by calling python manage.py shell, and copy-pasting it in, as opposed to just calling the script from the command line. -
Django messages still shows after page reload
I'm using the following library for notifications: noty Using the following snippet on template: {% if messages %} {% for message in messages %} <script> new Noty({ type: "{{ message.tags }}", layout: "topRight", text: "{{ message }}", timeout: 30000 }).show(); </script> {% endfor %} {% endif %} If I refresh the page the message still appears, as far as I know django messages are deleted after iteration but I don't know how to fix this problem -
Why apache with mod_wsgi timed out?
I was using apache with mod_wsgi to deploy my django project. What I do was: 1. python manage.py startproject mysite as the python tutorial guides, add to apache conf/httpd.conf the following configuration: ServerName www.example.com ServerAlias example.com ServerAdmin webmaster@example.com WSGIDaemonProcess example.com processes=2 threads=15 display-name=%{GROUP} python-path=/root/mysite python-home=/usr WSGIProcessGroup example.com WSGIScriptAlias / /root/mysite/mysite/wsgi.py <Directory /root/mysite/mysite> Require all granted </Directory> type example.com in the address bar, then get time out response: Gateway Timeout The gateway did not receive a timely response from the upstream server or application. How to handle this time-out in case of just a toy django app? I think it's not related to performance issues, but might be some configuration errors. Any one can help? Thanks! -
Django _unaccent and _search in Admin
So I have found a way to use _unaccent and _search together in Django filters, but I'm trying to find a way to properly implement it into the search bar in the admin pages. So far I have the following code, but since I haven't done it properly, admin settings such as search_fields = [] are not applying properly. I would appreciate it if someone could help me merge my solution with the original Django implementation. admin.ModelAdmin function being overwritten: def get_search_results(self, request, queryset, search_term): """ Returns a tuple containing a queryset to implement the search, and a boolean indicating if the results may contain duplicates. """ # Apply keyword searches. def construct_search(field_name): if field_name.startswith('^'): return "%s__istartswith" % field_name[1:] elif field_name.startswith('='): return "%s__iexact" % field_name[1:] elif field_name.startswith('@'): return "%s__search" % field_name[1:] else: return "%s__icontains" % field_name use_distinct = False search_fields = self.get_search_fields(request) if search_fields and search_term: orm_lookups = [construct_search(str(search_field)) for search_field in search_fields] for bit in search_term.split(): or_queries = [models.Q(**{orm_lookup: bit}) for orm_lookup in orm_lookups] queryset = queryset.filter(reduce(operator.or_, or_queries)) if not use_distinct: for search_spec in orm_lookups: if lookup_needs_distinct(self.opts, search_spec): use_distinct = True break return queryset, use_distinct My code: def get_search_results(self, request, queryset, search_term): # TODO: Make this more professionally implemented … -
How do i make my code for form more dynamic
I love the principle of Django, DRY. I am trying to get into the habit of coding following that convention. In my app, the form I am using has the same concept for now which is checking if its a POST method or not and if it is check if its a valid form or not and save it(along with association) but i could not make it more dynamic as it can be used only for the specific app. The main issue in dynamic is the line where i have used the association, there resume is used which i want dynamic and also improve this code for more better and efficient code. Here it is def addForm(request, form, template): if request.method == "POST": if form.is_valid(): resume_instance = Resume.objects.get(applicant=request.user) new_form = form.save(commit=False) new_form.resume=resume_instance new_form.save() messages.success(request, 'Thank you') messages.warning(request, 'Correct the error') context = { 'form': form } return render(request, template, context) def edit_form(request, form, template): if request.method == "POST": if form.is_valid(): form.save() messages.success(request, 'successfully updated') messages.warning(request, 'Correct the error') context={ 'form': form } return render(request, template, context) def resume_form(request): template='userDashboard/user/resume.html' user = request.user try: resume = Resume.objects.get(applicant=request.user) return edit_form(request, ResumeForm(request.POST or None, instance=resume), template) except Resume.DoesNotExist: print ('error') return addForm(request, ResumeForm(request.POST … -
TemplateDoesNotExist at /accounts/upload_save/ error
I got an error,TemplateDoesNotExist at /accounts/upload_save/ {'form': } . I wrote in views.py like def upload(request, p_id): form = UserImageForm(request.POST or None) d = { 'p_id': p_id, 'form':form, } return render(request, 'registration/accounts/photo.html', d) @csrf_exempt def upload_save(request): if request.method == "POST": form = UploadForm(request.POST, request.FILES) if form.is_valid(): data = Post() data.image = request.FILES['image'] data.save() else: form = UploadForm() return render('registration/accounts/photo.html', {'form':form}) class UploadForm(forms.Form): image = forms.FileField() urls.py is urlpatterns = [ url(r'^regist/$', views.regist,name='regist' ), url(r'^regist_save/$', views.regist_save, name='regist_save'), url(r'^profile/$', views.profile, name='profile'), url(r'^photo/$', views.photo, name='photo'), url(r'^upload/(?P<p_id>\d+)/$', views.upload, name='upload'), url(r'^upload_save/$', views.upload_save, name='upload_save'), ] profile.html is <div class="container"> <form action="{% url 'accounts:upload_save' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="input-group"> <label class="input-group-btn"> <span class="btn btn-primary btn-lg"> SELECT FILE <input type="file" style="display:none" name="files[]" multiple> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <div class="form-group"> <input type="submit" value="SEND" class="form-control"> </div> </form> </div> When I put "SEND" button,I wanna show photo.html in the browser.But now the error happens, although I wrote registration/accounts/photo.html in render.I really cannot understand how to fix this.What should I do? -
Django Signals and form is_valid
This question is related to this. I would like to save my form data in relation to the created signal: Model : class PatientInfo(models.Model): lastname = models.CharField('Last Name', max_length=200) ... class MedicalHistory(models.Model): patient = models.OneToOneField(PatientInfo, on_delete=models.CASCADE, primary_key=True) physician_name = models.CharField('Physician', max_length=200, null=True, blank=True) ... @receiver(post_save, sender=PatientInfo) def create_medical_history(sender, **kwargs): if kwargs.get('created', False): MedicalHistory.objects.create(patient=kwargs.get('instance')) View class MedicalCreateView(CreateView): template_name = 'patient/medical_create.html' model = MedicalHistory form_class = MedicalForm success_url = '/' def post(self, request, pk): form = self.form_class(request.POST) if form.is_valid(): patiente = form.save(commit=False) physician_name = form.cleaned_data['physician_name'] # do not delete patiente.save() messages.success(request, "%s is added to patient list" % physician_name ) return redirect('index') else: print(form.errors) My code above saves two entry in my MedicalHistory table, patient field is linked to Patient_info.id while the other is empty yet populated with form data. Any help is greatly appreciated. -
Django Model Formset does not validate yet no errors
Super noob who codes for my own small business. Can't seem to figure this one out. Model formset does not validate but manager form shows no errors screenshot of no errors on form def audit(request, location_id): clear = InvAudit.objects.filter(current_amount__isnull=True).delete() ingredients = Ingredient.objects.filter( location=location_id, ) audit_location = StorageLocation.objects.get(pk=location_id) InvAudit.objects.bulk_create([InvAudit(ingredient=x) for x in ingredients]) tasks = InvAudit.objects.filter(current_amount__isnull=True) CreateFormSet = modelformset_factory(InvAudit, fields=('ingredient', 'current_amount' ), max_num=tasks.count(), extra=0) InitFormSet = CreateFormSet(queryset=tasks) if request.method == 'POST': formset = CreateFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() current_stock = Ingredient.objects.filter(location=location_id,).annotate( system_level = Count(Case( When(item__in_stock=True, then=1,)))) mismatch = [] for f in current_stock: difference = current_stock.system_level - formset.filter(ingredient=f.id) if difference != 0: mismatch.append(f.id) return render(request, 'mismatch.html', {'mismatch': mismatch}) else: errors = formset.errors else: formset = InitFormSet return render(request, 'audit.html', {'formset': formset, 'audit_location': audit_location}) And here is my template. <form method="post" action=""> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {% bootstrap_form form %} {% endfor %} {% buttons %} <button type="submit" class="btn btn-primary"> {% bootstrap_icon "star" %} Submit </button> {% endbuttons %} </form> Any help much appreciated -
"Unable to setup mongodb with Django"
My Settings.py file has DATABASES = { 'default' : { 'ENGINE' : 'django_mongodb_engine', 'NAME' : 'my_database' } } When i try to run the django i get the following error I have attached the screenshot of the error i refered to this document https://django-mongodb-engine.readthedocs.io/en/latest/topics/setup.html MongoDb is up and running in the port 27017 Django Version:1.7 Python :3.4.3 please suggest the solution to setup the mongodb with django. -
Wrapper to help changing api
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 1- If I pull NHL data inside a .csv file, will 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. -
How to sort objects without a static field value?
Let's say I had a bunch of objects, fathers. So each father would have a bunch of kids. An unbounded number of kids. For each 1 father, there are many kids. I want to sort each father by the average age of kids. Since the number of kids can change and their age will increase, I wouldn't necessarily want to hard-code the average age into the father model. I need to have that value dynamically available, cached somehow so it can be quickly sorted by average child age when looking at 100,000 fathers. Any ideas? -
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 …