Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Search string in database column django query
I have a field in db which contains string like "Food,Financial,Health" . I need to search string which is startswith "Fi" in that field. I can search string using contains but i need to search startswith in django query. Anyone suggest me to do that. -
ConnectionTimeout caused by - ReadTimeoutError(HTTPConnectionPool(host=u'localhost', port=9200): Read timed out. (read timeout=10))
In local system elastic search works perfectly but when i'm trying to search in server system it shows in console : "ConnectionTimeout caused by - ReadTimeoutError(HTTPConnectionPool(host=u'localhost', port=9200): Read timed out. (read timeout=10))" -
django prefetch_related reverse relationship with nested serializer
I wanted to know that, how can I optimize my sql query with django's prefetch_related() method on a reverse foreignkey relationship and nested serializer models.py class Dataset(models.Model): name = models.CharField(max_length=30) run = models.ForeignKey('Run') class Spider(models.Model): name = models.CharField(max_length=20) status = models.BooleanField() class Run(models.Model): name = models.CharField(max_length=10) spider = models.ForeignKey(Spider) serializers.py class SpiderDetailSerializer(serializers.ModelSerializer): latest_run = serializers.SerializerMethodField(read_only=True) def get_latest_run(self, model): latest_run = model.run_set.first() if latest_run: return RunDetailSerializer(latest_run).data return None @staticmethod def setup_eager_loading(queryset): # stuff to make optimize # code return queryset class RunDetailSerializer(serializers.ModelSerializer): spider = SpiderAllSerializer(read_only=True) datasets = DatasetSerializer(many=True, read_only=True, source='dataset_set') class SpiderAllSerializer(serializers.ModelSerializer): class Meta: model = Spider fields = ('id', 'name', 'status') class DatasetSerializer(serializers.ModelSerializer): class Meta: model = Spider fields = ('id', 'name', 'run') I want to implement setup_eager_loading() on SpiderDetailSerialize ( I don't know whether it's good method or not ). While calling SpiderDetailSerialize many Dataset will be retrived. If it's not a good way to implement prefetch_related() on SpiderDetailSerialize , kindly suggest better way to optimize the process -
Django performance with render_to_response
I have Django app, which have following statements: response = render_to_response('template.html', {'s':s, 'r':r}, context_instance=RequestContext(request)) The typical statement at template.html is: <tbody>{%for m in r.m_set.all %}<tr> <td>{{m.id}}</td> <td>{{m.Name}}</td> <td>{{m.MaterialLot.id}}</td> <td>{{m.MaterialSublot.id}}</td> <td>{{m.Description|truncatechars:20}}</td> <td>{{m.StorageLocation.id}} - {{m.StorageLocation.Name}}</td> <td>{{m.Quantity|floatformat:"-3"}}</td> <td>{{m.QuantityUnitOfMeasure.id}}</td> <td>{{m.Status.id}}</td></tr> {%endfor%}</tbody> There are about 10 thousands records. the page response time take about 3 minutes(ThinkServer, Linux, Apache, mod_wsgi, Python3.4, Django 1.9.4, MySQL), is this normal? Thanks! -
FormView updating context after redirecting same template
index.html <form class="form-horizontal" method="POST" action=""> {% csrf_token %} {{ form.as_p }} <div class="control-group"> <div class="controls"> <button type="submit" class="btn btn-primary">Go</button> </div> </div> </form> {% if my_list %} {% for a, b in my_list %} {{ a }} {{ b }} {% endfor %} {% endif %} views.py class MyView(FormView): template_name = 'index.html' form_class = MyForm success_url = reverse_lazy('myapp:index') def form_valid(self, form): # get URL value from form field url = form.cleaned_data['url'] # do some stuf to populate my_list ... self.my_list = [('test','a'), ('test2','b')] return super(ScraperFormView, self).form_valid(form) forms.py class MyForm(forms.Form): url = forms.URLField(label='URL', required=True) There's only one page (index.html) with a form so the user can submit an URL. Then the URL is processed in MyView and my_list var is created in the form_valid method. After returning from this method, the context data should be updated adding my_list var, so the template (index.html, same success_url) is populated. I've tried to solve this overriding get_context_data, but cannot figure out how to redirect to success_url updating the context with my_list. -
Mezzanine 4.2.2 / 4.2.3: Search breaks when USE_MODELTRANSLATION = True
I've been having quite the time trying to get my search functionality to work correctly on my mezzanine project using django-modeltranslation. I am fairly new to Django, Mezzanine, and Python as well so no surprise as to why I'm having difficulty figuring this issue out. My translations work fine. No issues there. However, each time I set USE_MODELTRANSLATION = True in my settings.py and perform a search query I just get re-directed to my homepage each time rather than the expected search results page and in my console output I'll see "POST /i18n/ HTTP/1.1" 302 0. For the latter, if I set USE_MODELTRANSLATION = False and perform a search query I get the expected search result and in my output "GET /search/?q=test HTTP/1.1" 200 12972. I also noticed that each POST is also passing the language parameter in the headers which I suspect to be part of the problem. I also suspected some issues with my urls.py and attempted many combinations specific to the search url but didn't have any luck with that either. I am almost certain the issue may be with modeltranslation set_language. So far I've tested my scenario with the following combinations but no resolve: Mezzanine 4.2.3 … -
AttributeError: 'DeferredAttribute' object has no attribute 'objects'
I got an error,AttributeError: 'DeferredAttribute' object has no attribute 'objects'. I wanna parse excel and put it to the model(City&Prefecture&Area&User) . I wrote user3 = User.objects.filter(corporation_id=val3).first() if user3: area = Area.objects.filter(name="America").first() pref = Prefecture.objects.create(name="prefecture", area=user3.area) city = City.objects.create(name="city", prefecture=pref) price_u1000 = Price.upper1000.objects.get(city=city) price_500_1000 = Price.from500to1000.objects.get(city=city) price_u500 = Price.under500.objects.get(city=city) pref.name = "NY" pref.save() for i in range(2,len(fourrows_transpose)): city.name = fourrows_transpose[i][1] city.save() print(fourrows_transpose[i][1]) price_u1000.name = fourrows_transpose[i][2] price_u1000.save() print(fourrows_transpose[i][2]) price_500_1000.name = fourrows_transpose[i][3] price_500_1000.save() print(fourrows_transpose[i][3]) price_u500.name = fourrows_transpose[i][4] price_u500.save() print(fourrows_transpose[i][4]) Traceback says this code price_u1000 = Price.upper700.objects.get(city=city) is wrong. models.py is class Area(models.Model): name = models.CharField(max_length=20, verbose_name='area', null=True) class User(models.Model): user_id = models.CharField(max_length=200,null=True) area = models.ForeignKey('Area',null=True, blank=True) class Prefecture(models.Model): name = models.CharField(max_length=20, verbose_name='prefecture') area = models.ForeignKey('Area', null=True, blank=True) class City(models.Model): name = models.CharField(max_length=20, verbose_name='city') prefecture = models.ForeignKey('Prefecture', null=True, blank=True) class Price(models.Model): upper1000 = models.CharField(max_length=20, verbose_name='u1000', null=True) from500to1000 = models.CharField(max_length=20, verbose_name='500~1000', null=True) under500 = models.CharField(max_length=20, verbose_name='d500', null=True) city = models.ForeignKey('City', null=True, blank=True) What should I do to fix this?How should I write it? -
Increment integer field dynamically - Django
So I have the following model: from django.db import models class Person(models.Model): name = models.CharField(max_length=254) image_url = models.CharField(max_length=254) title = models.CharField(max_length=254) bio = models.CharField(max_length=20000) vote = models.IntegerField(default=0) def __str__(self): return self.name Where Vote is the attribute that I want to increment by one on every click. The following Views: import json from rest_framework.views import APIView from rest_framework.response import Response from urllib.request import urlopen from .models import Person from .serializers import PersonSerializer from django.views.generic import ListView class PersonApiView(APIView): def get(self, request): persons = Person.objects.all() serializer = PersonSerializer(persons, many=True) return Response(serializer.data) class PersonView(ListView): data = urlopen("https://api.myjson.com/bins/16roa3").read() json_persons = json.loads(data) persons = Person.objects.all() for person in json_persons: if person['id'] not in [i.id for i in persons]: Person.objects.create(id=person['id'], name=person['name'], image_url=person['image_url'], title=person['title'], bio=person['bio']) model = Person context_object_name = 'persons' In the views, I'm doing 2 things: Show in my /api/ URL all my objects after being serialized. Create objects using an external JSON URL This what I have in my html: {% for person in persons %} <div class="container"> <div ng-controller="mainController"> <div class="row"> <div class="col-xs-12 col-sm-5 col-md-4 col-lg-3"> <img ng-src="{{person.image_url}}"/> </div> <div class="col-xs-12 col-sm-7 col-md-8 col-lg-9"> <h2>{{ person.name }}</h2> <h3>{{ person.title }}</h3> <p>{{ person.bio }}</p> <form method="POST"> <h4>Want to work with {{ person.name }}? <img … -
connect to database on web hosting and my django applicattion
hello everyone i'm knew in develloping i'm creating a web application for car tracking where i use a gprs card that must send data to my hosting web database so i want to know how to connect between my web site and django app thank you :D -
how can I create a project with django?
i install python and Django on mac with pip , but when i want start project with Django by this command i have message error : macs-MacBook:desktop mac$ django-admin.py startproject blog pkg_resources.DistributionNotFound: The 'pytz' distribution was not found and is required by Django i try solve that with this command but i have same error : sudo pip install -U djangorestframework how can i solve that and create project ? -
Unexpected keyword 'import' in WebPack Django and Vue.js project
I have a simple project where I am using Django, Webpack and Vue.js. When I build a static bundle upon load it seems like my bundle is not compiled correctly. I get an error in JavaScript console: [Error] SyntaxError: Unexpected keyword 'import' (anonymous function) (main-dd2bbbf09bf9a252a3c7.js:47) I tried to keep my webpack.config.js really simple: var path = require("path"); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); module.exports = { context: __dirname, entry: './frontend/js/main', output: { path: path.resolve('./frontend/bundles/'), filename: "[name]-[hash].js", }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), ], resolve: { extensions: ['', '.js', '.vue', '.json'], }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { } // other vue-loader options go here } }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } } ], }, } .babelrc looks like this: { "presets": [ ["env", { "modules": false }] ] } main.js (which ultimately blows up) is simple: import Vue from 'vue' import App from './App.vue' new Vue({ el: '#app', render: h => h(App) }) -
Django: I want a Queryset as a list. How?
I need to get a Queryset in Django and make a copy of it as a variable in the form of a list of dictionaries. I thought this is what Querysets were, I guess I'm wrong. listA = User_Item.objects.filter(user=User.objects.get(id=1)) Gives me an error when I try to perform a simple algorithm with it. I don't want to interact with the database- I need to copy that Queryset as a list of dictionaries. How do I do this? (Trying to get a list of entries in this join table, which should be a list of dictionaries with dictionaries for some of the key values) -
Django: Cannot insert user profile data from model into the template
I am using Django's default auth for users and I have created a separate model to extend the user profile a bit. When I try to access the user profile info its not showing up on the page. In my view, I pass the Profile objects to the view's context but it still not working. When I try it in the shell, I get AttributeError: 'QuerySet' object has no attribute 'country' error when I do: profile = Profile.get.objects.all() country = profile.coutry country Below is my models.py: from pytz import common_timezones from django.db import models from django.contrib.auth.models import User from django_countries.fields import CountryField from django.db.models.signals import post_save from django.dispatch import receiver TIMEZONES = tuple(zip(common_timezones, common_timezones)) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) country = CountryField() timeZone = models.CharField(max_length=50, choices=TIMEZONES, default='US/Eastern') def __str__(self): return "{0} - {1} ({2})".format(self.user.username, self.country, self.timeZone) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Here is my views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from user.models import Profile @login_required() def home(request): profile = Profile.objects.all() return render(request, "user/home.html", {'profile': profile}) And finally the home.html file: {% extends "base.html" %} {% block title %} Account Home for {{ user.username }} … -
How can I repeatedly call a function from a views.py in Django?
How can I repeatedly call a function from a views.py in Django? urls.py urlpatterns = [ url(r'^$', views.index), url(r'^report/(?P<extension>\d+)/$', views.report), ] views.py def report(request, extension): """ I will do some logic here. I need the extension variable for database purposes. EX: my_array = Report.objects.fetching_reports(extension='3') """ return render(request, 'report.html’) If you notice in extension, I passed in 3. The idea is that each extension will have their own data. However, I want them to render on the same html template. I will begin rendering from extension 1, up to 12 then goes back to 1. Let’s say extension 4 is missing, it will be redirected to extension 5.These extension will come from my database. Example: …/report/1/ …/report/2/ …/report/3/ ## will skip 4 if not available …/report/5/ …/report/6/ ## and so on.. Each extension will render the same HMTL template. Right now, I can successfully render these reports if I type the URL patter directly to the browser. Is there a way to call report( ) continuously, let’s say every 15 seconds? Or should I have a different approach to this? Thank you very much for reading. -
Django DateInput default set by browser
In my Django project I have a regular looking forms.py which, for one form, specifies a certain field to use the DateInput widget. This works fine - when I browse to the page, I see an empty date field on which I can click and select a date from a calendar view. Now I'd like to auto-populate that for the user using the current date on their computer. So not a server-side default value, but probably browser-side set by Javascript or something. How can I do this? Essentially this is the template for my form: <form action="/new_case/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> -
django SelectDateWidget and bootstrap
I'm trying to render a SelectDateWidget with bootstrap, however when I add the class "form-control" it just appears vertically. If I don't add it it appears horizontal but unstyled. Is there a way to break down the widget so that I can customise it as needed? (Note I've used django widget tweaks to add the css class) <div class="form-group"> <label for="{{ form.move_in_date.id_for_label }}"> {{ form.move_in_date.label }} </label> {% render_field form.move_in_date.errors class="form-control" %} {% render_field form.move_in_date class="form-control" placeholder=form.move_in_date.label %} </div> -
Django Wagtail Jinja2 include_block tag not passing variables
I have the following very simple statement to render blocks in wagtail. {% for block in blocks %} {% include_block block %} {% endfor %} The for loop works and iterates over the blocks as does the template tag include_block. The variable 'block' however is not accessible in the template executed by include_block. {% set background_image = block.background_image.image %} The above statement called in the template called by include_block throws the following error. 'block' is undefined This does not really make sense since the documentation for Wagtail's include_block states that variables get passed down into the called template. http://docs.wagtail.io/en/v1.9/advanced_topics/jinja2.html#include-block I have the following statement in order to explicitly pass in variables but it still does not work, {% include_block block with context %} -
Django REST Framework - unittest client failing to resolve hyperlinks relation for POST
I have this test: class AttributeTest(APITestCase): def setUp(self): user1 = User.objects.create(pk=1, username='pepa', email='ads@asasd.cz', is_active=True, is_staff=True) user1.set_password('mypass') user1.save() self.c1 = Campaign.objects.create(pk=1, owner=user1, project_name='c1') def test(self): campaign_url = 'http://testserver/api/campaigns/{}/'.format(self.c1.pk) self.client.login(username='pepa', password='mypass') data = { "label": "something_here", "parent_campaign": campaign_url, } # campaign clearly exists (created in setUp) and GET retrieve it: assert self.client.get(campaign_url).json()['project_name'] == 'c1' # I can even try it myself using pdb # but this doesn't work - response return 400 Bad Request # complaining about the very same hyperlink I can GET above response = self.client.post('/api/keys', data, format="json") self.assertEqual(response.status_code, status.HTTP_201_CREATED) but when run, it fails with {'parent_campaign': ['Invalid hyperlink - No URL match.']}. When I try using curl or browsable API (outside the test environment), everything works as expected. Anyone knows what's going on? -
Django "apps" folder still relevant?
There was somewhere I read couple of years ago (Two scoops of Django 1.4?) suggested having an "apps" folder inside the Django project which hosts all the apps. Repo folder -- Project root folder -- apps -- app 1 -- app 2 -- settings etc But just had a quick read of "Two scoops of Django 1.8" there is no mention of the "apps" folder in the preferred project structure. Repo folder -- Project root folder -- app 1 -- app 2 -- settings etc What have I missed? And why did they remove this folder? -
Django & SET CONSTRAINTS ALL DEFERRED
What is the most repeatable way to update my db with unique constraints suspended during the update? Do I have to write the SQL query out every time I do a new one, or? -
Why Are my Nav-Pills and Carousel Slides Suddenly Not Working?
So I created my website for my company and when I had launched the site the functionality of various elements were working perfectly. On various pages of the website are carousel slides with slide timers and on one of the pages, https://ordinanceservices.com/services , I have nav nav-pills so that prospective customers could view the two elements of our services, one at a time; without needing to reload the page or visit a different page altogether. You guys get it. Upon revisiting my website after a while, I noticed that the carousel slides now no longer change and the nav nav-pills no longer change between "Identity Protection" and "Financial Planning". If I attempt to click on "Financial Planning" tab, it will reload the page but remain on the tab "Identity Protection". Since the markup is very lengthy and it is multiple elements that are no longer working, I will simply provide you all the URL to the page in question so that you all can view the source and play around on the webpage. If anyone has a solution or thinks they have found why this is happening please do let me know. As I have sank many hours into the … -
Preventing a file upload completely if file already exists in Django
I'm trying to make it so that when someone tries to upload a file that has already been uploaded before with a model form, the form will prevent it from submitting. Here is the relevant code: models.py class File(models.Model): file = models.FileField(upload_to='documents/') forms.py class FileForm(forms.ModelForm): file = forms.FileField() class Meta: model = File fields = ('file',) views.py def file_upload(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('list_files') else: logger.error(form.errors) else: form = FileForm() return render(request, 'files/file_upload.html', {'form': form}) Let's say someone uploaded a file called document_1.xlsx. The way this code is now, if someone tries to upload another file called document_1.xlsx, it will upload it and add some weird suffix to it before the dot. I don't want that. I want the form to not allow anyone upload a file that already exists period, without breaking the code. Apparently adding 'unique=True' to the file field in the model doesn't work. I've seen so many questions that ask how to rename a file if it already exists, but I don't want that. I want to stop it completely if that file name already exists. Thanks. -
Generate SQL query string from Django ORM
I need to use SET CONSTRAINTS ALL DEFERRED in order to persist new order values on a series of rows, where they have a unique constraint. Django does not have support for deferring constraints natively, and I don't want to have to rewrite the query every time I want to do something like this. Is there a way to have Django write some SQL for me, and then I can toss the SET CONSTRAINTS ALL DEFERRED into it before running raw_sql? -
How to reverse_lazy to a view/url with variable?
I've got a DeleteView I use for removing objects from a model. It is launched via a button in a table. It works fine. class DeleteAssignment(DeleteView): model = Assignment success_url = reverse_lazy('company') I just want to have it return to it's parent view on success. I currently have it redirecting to the parent's parent (company), as this view doesn't require a variable. This would be simple, but the parent view requires a variable farm_id to render, this is captured from the url like "/farm/18" url(r'^farm/(?P<farm_id>.+)', views.farm, name='farm'), I've solved this with forms on the page by having them redirect to the view farm with the variable farm_id. return redirect(farm, farm_id=farm_id) How could I do this with the success_url for my DeleteView? -
the view didn't return an HttpResponse object. It returned None instead.,nothing work
i am now working with Django in python. this is views.py class AddTeamView(View): def get(self, request): form = TeamForm() context={ 'form':form } def post(self, request): if request.method == "POST": form = TeamForm(request.post) if form.is_valid(): team = Mem() team.Your_Name = form.cleaned_data['Your_Name'] team.Your_Age = form.cleaned_data['Your_Age'] team.Your_Country = form.cleaned_data['Your_Country'] team.Your_Memories = form.cleaned_data['Your_Memories'] team.save() return redirect('/') return render(request, 'newmem.html', context) and this is the full error from terminal Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: /new/ Traceback (most recent call last): File "C:\smile-env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\smile-env\lib\site-packages\django\core\handlers\base.py", line 198, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view web.views.AddTeamView didn't return an HttpResponse object. It returned None instead. [12/Sep/2017 21:32:39] "GET /new/ HTTP/1.1" 500 57308 i did search but nothing i don't know what's wrong i also added else in the end but same error