Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
celery kombu unresolved dependencies post python upgrade
I upgraded my ubuntu environment to 16.04 which also upgraded python to 2.7.12 My environment is as below: 1) Celery - 3.1.25 2) Django - 1.6.5 3) Kombu - 3.0.24 I was getting below errors while I tried to start my celery worker: File "/usr/local/lib/python2.7/dist-packages/celery/worker/consumer/consumer.py", line 20, in from kombu.utils.compat import _detect_environment ImportError: cannot import name _detect_environment I went through kombu code base and got the relevant function for _detect_environment and that resolved the issue. But, second time I hit below exception: File "/usr/local/lib/python2.7/dist-packages/celery/worker/consumer/consumer.py", line 29, in from celery.five import buffer_t, items, python_2_unicode_compatible, values ImportError: cannot import name buffer_t And could not resolve it. I tried along with latest version of kombu but that also did not help. I know Django is very old but I am scared to upgrade that as it might break other things. It was working fine along with ubuntu 14.04 Any idea? -
Angular -Js $http.post not working in django
I have just started Django and what I was trying to implement $http.post method of angular to post form data to my Django database,and my further plan was to update the view to display the results without page refresh.so what i thought to post data in django db and then my view function will return a jsonresponse,of that posted data which i can use to update the view using $http.get method. But the problem is occuring with me is whenever i post data it is not able to post the data and returning an empty json response. Here is my codes which i am working on:- urls.py from django.conf.urls import url from . import views app_name='demo' urlpatterns=[ url(r'^$',views.index,name="index"), url(r'^add_card/$',views.add_card,name="add_card") ] views.py from django.shortcuts import render from django.http import HttpResponse,JsonResponse from .forms import CardForm from .models import Card # Create your views here. def add_card(request): saved = False if request.method == 'POST': #print('hi') form = CardForm(request.POST) #print('hi') if form.is_valid(): #print('hi') card = Card() #print('hi') card.content = form.cleaned_data['content'] #print('hi') saved = True card.save() #print('hi') return JsonResponse({'body':list(q.content for q in Card.objects.order_by('-id')[:15])}) else: return HttpResponse( json.dumps({"nothing to see": "this isn't happening"}), content_type="application/json" ) def index(request): return render(request,'demo/index.html',{'form':CardForm()}) controller.js var nameSpace = angular.module("ajax", ['ngCookies']); nameSpace.controller("MyFormCtrl", … -
Jmeter authorization where should I put token?
Something wrong with my authorization flow but I can't to figure out what exactly. Response data: {"detail":"Authentication credentials were not provided."} Does it may be related to used technologies: Python/Django + React JS ? View Results Tree HTTP Request по которому отправляется логин/пароль -
Djano bulk_create while populating ImageField
I am trying bulk_create a list of Person objects from some list of raw parsed API data. the data contains: Id Comment Image person = raw_api_data[0] obj = Person( id=person['id'], comment=person['comment'], ) if person['image'] is not None: obj.image.save( '.jpg', ContentFile(person['image'].decode('base-64')), save=False, ) new_persons.append(obj) Person.objects.bulk_create(new_persons) I want to be able to avoid creating local image files on file system in case bulk_create fails. (IntegrityError for example) Is there any way to avoid creating the file itself before the create process itself while also be able to bulk create all objects with their images? I did not find any other ideas besides creating the content file before appending the object itself to the bulk list. Thank you -
django url regex changing on redirect
This is how to the url regex should look like url(r'^(?P<username>\w+)/'...... But on redirect is becomes url(r'^(?P<username>\\w+)/'....... Notice the backslash before the 'w' became double and because of that I keep getting the no reverse match error....what could be the problem -
Jupyter and Django
Here is my folder : /home/bussiere/Workspace/ reetags -- kiwixi -- settings.py retagsTest i'am launching jupyter in reetagsTest but when i try to do this in jupyter : MYPROJECT = '/home/bussiere/Workspace/reetags/' import os, sys sys.path.insert(0, MYPROJECT) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kiwixi.settings") import django django.setup() i have a : ImportError: No module named 'settings' And i would like to acces to django ORM / objects and everything without launching django thanks and regards -
Reactjs REST API call to Django fails
I have hosted an app(ReactJS + Django) on amazon ec2 server. When the client app makes a REST API call, I get connection refused error on the ec2 instance. But when I run the app locally, it works smoothly. I have added the correct inbound rules in security groups for the ports for both client as well as django server. The client makes a call to http://localhost:8000/getImages The django service is also running on the same port. As a matter of fact, the app was working fine on the ec2 server also just a couple of weeks ago with the exact same settings. I'm not sure as to what changed in the mean time and what could possible fix this error. Any suggestions? -
ModuleNotFoundError: No module named 'PyDemo.accounts'
I am trying out Django app for the first time. I have a little experience regarding this. I am trying to host a simple index.html in my app, but I am getting the following error. url.py: from django.conf.urls import url,include from django.contrib import admin from PyDemo.accounts.views import my_view urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^demo/',my_view) ] views.py: from django.shortcuts import render_to_response from django.template import RequestContext # Create your views here. def my_view(request): return render_to_response('index.html',locals(),context_instance=RequestContext(request)) Whenever I am running this I get the following error: return import_module(self.urlconf_name) File "C:\Users\tcssuoy\Desktop\DJANGO\mysite\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "C:\Users\tcssuoy\workspace\PyDemo\PyDemo\PyDemo\urls.py", line 18, in <module> from PyDemo.accounts.views import my_view ModuleNotFoundError: No module named 'PyDemo.accounts' Can you please help me out on this? -
django-ckeditor :data not loading in the Form
I'm Using Django-ckeditor as a model form widget.I have been able to able to save data using the model-form. Now that I want to edit any saved data the form does not load the data onto the CKeditor. Django 1.10 Python 3.5 Windows 7 64bit forms.py class templateform(forms.ModelForm): class Meta: model = presciptiontemplates fields = ['template', 'templateid', ] widgets = { 'template': CKEditorWidget(), } labels = { "templateid": _("Patient ID"), } views.py def get_template(request, tid): template = presciptiontemplates.objects.get(templateid=tid) form = templateform(request.POST, instance=template) if form.is_valid(): form = form.save(commit=False) form.patientid = tid form.save() else: form = templateform(request.POST, instance=template) return render(request, 'presapp/viewtemplate.html',{'form': form}) HTML <div id="preview-content"> <form method="post" style="margin-top:20px;"> {% csrf_token %} {{ form.media }} {{ form|safe }} <div class="" style="margin-top:20px ;"> <button class="btn waves-effect waves-light left" type="submit">Submit <i class="material-icons right">add_circle</i </button> </form> </div> </div> -
Django - Python 3 - "AssertionError: A model can't have more than one AutoField."
I'm getting crazy over this. I created my database with MySQLWorkbench This his my Schema Than I used the terminal command to get the model-code: $python3 manage.py inspectie After passing the code to my models.py I try to use the models in the shell with $python3 manage.py shell But then I'm getting always this error: "AssertionError: A model can't have more than one AutoField." But the error makes no sense, since there are only one AutoField in each Model, see: class Brands(models.Model): bid = models.AutoField(db_column='BID') # Field name made lowercase. name = models.CharField(db_column='Name', max_length=45, blank=True, null=True) # Field name made lowercase. fair = models.IntegerField(db_column='Fair', blank=True, null=True) # Field name made lowercase. eco = models.IntegerField(db_column='Eco', blank=True, null=True) # Field name made lowercase. country = models.CharField(db_column='Country', max_length=45, blank=True, null=True) # Field name made lowercase. companies = models.ForeignKey('Companies', models.DO_NOTHING, db_column='Companies_ID') # Field name made lowercase. class Meta: managed = False db_table = 'Brands' unique_together = (('bid', 'companies'),) class Companies(models.Model): cid = models.AutoField(db_column='CID') # Field name made lowercase. name = models.CharField(db_column='Name', max_length=45, blank=True, null=True) # Field name made lowercase. fair = models.IntegerField(db_column='Fair', blank=True, null=True) # Field name made lowercase. eco = models.IntegerField(db_column='Eco', blank=True, null=True) # Field name made lowercase. country = models.CharField(db_column='Country', max_length=45, blank=True, … -
Error in displaying chart in Django with chartit
I have an application for which I am trying to display a simple chart of number of proposals per country. I am using pivotchart in chartit as explained here I have a model like this class Proposal(models.Model): org = models.CharField(max_length=200) country = models.CharField(max_length=100) recdate = models.DateField(blank=False) subdate = models.DateField(blank=False) status = models.CharField(choices = stat_val, max_length=20) and as explained in the chartit GitHub, I have added this to views from django.db.models import Count from chartit import PivotDataPool, PivotChart from django.shortcuts import render_to_response def proposal_pivot_chart_view(request): # Step 1: Create a PivotDataPool with the data we want to retrieve. proposalpivotdata = PivotDataPool( series=[{ 'options': { 'source': Proposal.objects.all(), 'categories': ['country'], }, 'terms': { 'countprop': Count('id'), } }] ) # Step 2: Create the PivotChart object chart1 = PivotChart( datasource=proposalpivotdata, series_options=[{ 'options': { 'type': 'column', 'stacking': True }, 'terms': ['countprop'] }], chart_options={ 'title': { 'text': 'Proposals by Countries' }, 'xAxis': { 'title': { 'text': 'Country' } } } ) # Step 3: Send the PivotChart object to the template. return render_to_response({'chart1': chart1}) and I have created a template like this <!DOCTYPE html> <html> <head> {% load staticfiles %} {% load static %} <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}" > <link rel="stylesheet" href="{% static 'bootstrap/css/light-bootstrap-dashboard.css' %}" … -
Django project using python 2.7 even though interpretor points to python version 3.5
My project interpretor points to python version 3.5.2: (/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5) However when I go to the python shell in the project terminal (i'm using pycharm btw), it loads python 2.7. Any idea why? -
Get a variable out of a 'Model' -- Django Template
I have a complicated question, so I hope I can write it in a understandable way. I have a template (index.html) and I'm using a custom tag for setting a few variable. I can set this varible with: {% set table_breaker_houses = 4 %} And I use it later many times with, for example: {% if forloop.counter <= table_breaker_houses %} This is how it works now, but I want something like this: {% for settings in Settings %} {% set table_breaker_houses = "{{ settings.table_breaker_houses }}" %} {% endfor %} {% if forloop.counter <= table_breaker_houses %} "Settings" is a model with values, so I can manage my settings with the adminpanel. Could someone please help me out? Thanks for readings so far and sorry for my bad english. :) With best regards, borsTiHD -
Django: how to avoid redirection in a DeleteView
I am using a DeleteView which is redirecting after success, but I am trying to avoid this. I figured the part that redirected the page was in this method in the DeletionMixin (the last line): def delete(self, request, *args, **kwargs): self.object = self.get_object() self.object.delete() return HttpResponseRedirect(self.get_success_url()) So I overrode it: def delete(self, request, *args, **kwargs): self.object = self.get_object() self.object.delete() return HttpResponse(json.dumps({'success': True}), content_type='application/json') Nonetheless, when deleting the entry, the response keeps redirecting the page. This is the relevant part of my client code: $.ajax({ url: '{% url some_delete_route some_model.id %}', type: 'DELETE', success: function () { $this.closest('.item-container').remove(); } }); What am I missing? What should I do to avoid the redirection? I am doing the same thing for other views like FormView and CreateView and I did not experience this issue. -
IndexError at /delta/ - list index out of range - Django
The user selects two aircraft to compare from the list page. However I get the following error: IndexError at /delta/ list index out of range. It's complaining about this line in particular: first_value = getattr(aircraft_to_compare[0], key) Is there an obvious error that I'm making here? View def aircraft_delta(request): ids = [id for id in request.GET.get('ids') if id != ','] aircraft_to_compare = Aircraft.objects.filter(id__in=ids) property_keys = ['name', 'manufacturer', 'aircraft_type', 'body', 'engines', 'image', 'cost','maximum_range','passengers','maximum_altitude','cruising_speed', 'fuel_capacity','description','wing_span','length'] column_descriptions = { 'image': '', 'name': 'Aircraft', 'maximum_range': 'Range (NM)', 'passengers': 'Passengers', 'cruising_speed': 'Max Speed (kts)', 'fuel_capacity': 'Fuel Capacity', 'aircraft_type': 'Type', 'body':'Body', 'engines':'Engines', 'cost':'Cost', 'maximum_altitude':'Maximum Altitude', 'description':'Description', 'manufacturer':'Manufacturer', 'wing_span':'Wing Span (FT)', 'length':'Total Length (FT)' } data = [] for key in property_keys: row = [column_descriptions[key]] first_value = getattr(aircraft_to_compare[0], key) second_value = getattr(aircraft_to_compare[1], key) if key not in ['image', 'name']: delta = abs(first_value - second_value) else: delta = '' row.append(first_value) row.append(delta) row.append(second_value) data.append(row) return render(request, 'aircraft/aircraft_delta.html', { 'data': data }) -
No bin and lib in new django app
I have no bin and lib next to my root directory, which I have in another project but i'm not sure how I got them. So this is my app tree right now: Desktop | project | app > | | | db.sqlite3 | init.py | | manage.py | views.py | | templates | settings.py | | | urls.py And my other app has: Desktop | project | app | app> | | | bin | init.py | init.py | | db.sqlite3 | db.sqlite3 | settings.py | | include | manage.py | urls.py | | lib | templates | views.py So is one of these improperly configured?/which one is the better option? -
django summernote is not displaying
views.py def post_detail(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() return redirect('post_detail') else: form = PostForm() return render(request, 'post_detail.html', {'form': form}) forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('Penname','text',) widgets = { 'text': SummernoteInplaceWidget(), } models.py class Post(models.Model): #user = models.OneToOneField(User) Penname = models.CharField(max_length=200) text = models.TextField() def __str__(self): return self.Penname post_detail.html <!DOCTYPE HTML> <html> <head> </head> <body> <div class="container"> <form method="post"> {{ form.as_p }} <button type="button" class="btn btn-primary">Submit</button> </form> <div> <h1>{{ post.Penname }}</h1> <p>{{ post.text|linebreaksbr }}</p> </div> </div> </body> </html> urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^summernote/', include('django_summernote.urls')), url(r'^post/$', imagec_views.post_detail, name='post_detail') ] I want a summernote editor option for my text field,but it is displaying only 'Text' string and summernote is not displaying ,even it is not displaying a simple textfield -
EmberJS Build Failed with no such file or directory for jquery.js
I have an Ember + Django project that previously worked last week and I have not made a single change since. But now every time I rebuild the project it gives me the following error: Build failed. The Broccoli Plugin: [SourceMapConcat: Concat: Vendor /assets/vendor.js] failed with: Error: ENOENT: no such file or directory, stat '/Users/IFH/Desktop/planner/planner-frontend/frontend/tmp/source_map_concat-input_base_path-V4BWWQCZ.tmp/0/bower_components/jquery/dist/jquery.js' at Error (native) at Object.fs.statSync (fs.js:844:18) at Concat.keyForFile (/Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/broccoli-caching-writer/index.js:87:20) at Array.map (native) at Concat.CachingWriter._conditionalBuild (/Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/broccoli-caching-writer/index.js:109:65) at /Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/broccoli-caching-writer/node_modules/broccoli-plugin/read_compat.js:61:34 at tryCatch (/Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/rsvp/dist/rsvp.js:539:12) at invokeCallback (/Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/rsvp/dist/rsvp.js:554:13) at publish (/Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/rsvp/dist/rsvp.js:522:7) at flush (/Users/IFH/Desktop/planner/planner-frontend/frontend/node_modules/rsvp/dist/rsvp.js:2414:5) Previously it would create those files in that 'tmp' directory, but now nothing is even being created. Once again, I did not change any file before this error occurred. Please let me know what I should change in order to fix this issue. -
how to pass arguments to django views function and return csv on a button click?
I am not able to download the CSV when I click the button. it's working when I directly enter URL i.e localhost:8000/tweets with default values in the view function. but when I'm doing it on button click following output is coming and become idle. url(r'^tweets/', views.scrape_tweets), <div class="modal-footer"> <button id="download_tweets" class="btn btn-success" type="submit">Download</button> </div> $("#download_tweets").click(function() { var input = $('#query_input').val(); fdate = $('#startDate input').datepicker("getDate"); edate = $("#endDate input").datepicker("getDate"); data = {'input': input, 'startDate':convert_date(fdate),'endDate':convert_date(edate)} // console.log(data) $.ajax({ // url : '/tweets', url : '/tweets/?input='+input+'&startDate='+convert_date(fdate)+'&endDate='+convert_date(edate), type : 'get', data : data, success: function(result){ setTimeout(function(){ console.log('Success'); }, 3000); }, error: function (jqXHR, exception) { console.log("Errorrrrrrrrrrrrrrrrrr") console.log(jqXHR) } }); }); def scrape_tweets(request): # Get tweets by query search query = str(request.GET['input']) start_date = str(request.GET['startDate']) end_date = str(request.GET['endDate']) print '\n\n',query, start_date, end_date,'\n\n' response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="tweets.csv"' writer = csv.writer(response) writer.writerow(['Id', 'Tweet', 'Favorites', 'Retweets', 'Date & Time']) tweetCriteria = TweetCriteria().setQuerySearch(query).setSince(start_date).setUntil(end_date).setMaxTweets(200) start_time = timeit.default_timer() tweets = TweetManager.getTweets(tweetCriteria) print timeit.default_timer() - start_time for i in tweets: writer.writerow([unicode(i.id).encode("utf-8"), unicode(i.text).encode("utf-8"), unicode(i.favorites).encode("utf-8"), unicode(i.retweets).encode("utf-8"), unicode(i.date.strftime("%Y-%m-%d %H:%M")).encode("utf-8")]) return response Output in terminal Terminal: Virat Kohli 2017-04-18 2017-04-18 0.789546012878 [18/Apr/2017 10:54:21] "GET /tweets/?input=Virat%20Kohli&startDate=2017-04-18&endDate=2017-04-18&input=Virat%20Kohli&startDate=2017-04-18&endDate=2017-04-18 HTTP/1.1" 200 41 -
Django and postgres migration errors
I have created a new postgressql db in my django app within Heroku. Every time I run a migration, however, I get an error that I don't understand. Error: Applying argent.0043_auto_20170322_1629...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: cannot cast type date to integer LINE 1: ...LTER COLUMN "date_id" TYPE integer USING "date_id"::integer,... I have removed and added the only date field I have, to no avail. I still get the same error whether the date field in my models is there or not. Any insight would be much appreciated. models.py class Entry(models.Model): date = models.DateField(blank=True, null=True,) euros = models.CharField(max_length=500, blank=True, null=True) comments = models.CharField(max_length=900, blank=True, null=True) euros_sum = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) xrate = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) dollars_sum = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) daily_savings_dollars = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) daily_savings_display = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) def get_absolute_url(self): return reverse('argent:detail', kwargs={'pk': self.pk}) def item_date(self): row_title = self.date return row_title class Meta: ordering = ['date'] traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line … -
Django order by
I'm learning django, I am trying to order my objects by field last_name but I think I might be missing something, this is how my function looks: def list(self, *args, **kwargs): data = super().list(*args, **kwargs) data = data.data x = self.queryset.order_by('last_name') print(x) # I'm priting X but I still get list not ordered by last_name return Response(data) -
Why is my django url regex not working
I want my url to accept 0 or more digits(positive or negative integers), I mean it should match '/','/0',...,'/9' as well as '/-9','/-88' etc. This is the regex I am using ^([-]?[0-9]*)/$ . It works for all urls except '/', what is the problem with this regex? -
Django model validation, pass current value to function?
I'm trying to validate an expected IP value in my Django model as per the below: dmvpn_dsl = models.GenericIPAddressField(protocol='IPv4', verbose_name="DMVPN DSL IP", \ validators=[validate_dmvpn_ip('','172.16.100.')], blank=True, null=True) and in my functions i have def validate_dmvpn_ip(value,subnet): from django.core.exceptions import ValidationError if subnet not in value or value != '0.0.0.0': raise ValidationError(u'Invalid IP address, please check corrent octects have been assigned') i just need to pass the current value to the function to check it, but am not sure how to set this? Thanks -
Django: How to filter DB records by 0-3 criteria?
My goal is to have a search form (currently with 3 fields, but later possibly with more) which could be used for filtering products (In my case a product is training that can be filtered by sport, province and city). All those filter fields shall be optional, so I want to ignore when the POST value is either None (sport and province are FKs to related tables) or an empty string (city). I need to chain those three condition into the Training.objects.filter() call, but I need to omit conditions, that are not actually used. And I also need to check for None values as I am getting RelatedObjectDoesNotExist exception. This is what I have so far, but it is not good (only when all 3 conditions are properly filled): trainings = Training.objects.filter(sport = searchQuery.sport.sport_id).filter(province = searchQuery.province.province_id).filter(city = searchQuery.city) I tried to use conditional expression inside filter() to avoid exceptions, but either I am not able to elaborate the syntax correctly, or it is not possible - I was stopped by invalid syntax error... I was even thinking of dumb solution checking inputs in IF clauses and have different query for each case, but even with 3 params it has many … -
SSO Integration with Apache running Django with mod_wsgi
I am using Apache to host my web application running on Django using mod_wsgi. I am trying to integrate SSO with my application. Also, I need to pass on parameters like username to Django session. I am new to this and as far as I have discovered, there are two ways to do the same. Either let Django talk to SSO IdP server using Pysaml or second, use Apache to talk to the IdP server and let it pass on the response parameters to Django. I am not sure which method is better one to use. I need a little clarification on the same. Can someone please help? Thanks!