Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create collections inside migrations
i want create migrations for create collections applying one migration. I haven't clear which is the properly workflow for it, can anyone help to me? -
Optimizing Django REST framework load times without .select_related or .prefetch_related
I am experiencing slow load times (~13 seconds) for the Django REST framework due to the amount of data that is being returned (~1000 rows, 116 columns per row, no relationships). ~1000 rows $ curl -w "@curl-format.txt" -o /dev/null -s "http://127.0.0.1:8000/systemstates/3296" time_namelookup: 0.005 time_connect: 0.006 time_appconnect: 0.000 time_pretransfer: 0.006 time_redirect: 0.000 time_starttransfer: 12.968 ---------- time_total: 12.975 Limit to 10 rows $ curl -w "@curl-format.txt" -o /dev/null -s "http://127.0.0.1:8000/systemstates/3296" time_namelookup: 0.005 time_connect: 0.006 time_appconnect: 0.000 time_pretransfer: 0.006 time_redirect: 0.000 time_starttransfer: 1.657 ---------- time_total: 1.657 This is the model class SystemState(models.Model): systemId = models.IntegerField(default=0) from_date = models.DateTimeField(blank=True, null=True) to_date = models.DateTimeField(blank=True, null=True) patch = models.CharField(max_length=255, blank=True, null=True) patch_previous = models.CharField(max_length=255, blank=True, null=True) vv_count = models.IntegerField(default=0) vv_count_previous = models.IntegerField(default=0) vv_total_io = models.DecimalField(default=0, max_digits=15, decimal_places=3) port_total_io = models.DecimalField(default=0, max_digits=15, decimal_places=3) delayed_acks = models.IntegerField(default=0) delayed_acks_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_over_16s = models.IntegerField(default=0) writes_over_32ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_over_64ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_over_128ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_over_256ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_over_512ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_over_1024ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_over_2048ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_over_4096ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_between_0_and_0_62ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_between_0_62_and_0_125ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_between_0_125_and_0_25ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_between_0_25_and_0_5ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_between_0_5_and_1ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_between_1_and_2ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_between_2_and_4ms_pct = models.DecimalField(max_digits=6, decimal_places=3) writes_between_4_and_8ms_pct = models.DecimalField(max_digits=6, decimal_places=3) … -
Django delete database record when HTML button is clicked
I'm trying to create a button located in an HTML table that when clicked will delete a record (article in this case) from the database. I pass the articles pk like I've done with other links, but I can't figure out how make the deletion happen. I've searched online and the help files, but I'm new and really need someone to lay it all out for me. What should the URL and View look? HTML: <a href="{% url 'remove_article', article_pk=articles.pk %}"><span class="glyphicon glyphicon-remove-circle"></span></a> URLS (second url): urlpatterns = [ url(r'^$', views.CompanyList.as_view(), name='company_list'), url(r'^company/(?P<pk>[0-9]+)/$', views.CompanyDetails.as_view(), name='company_details'), url(r'^company/(?P<pk>[0-9]+)/remove$', views.CompanyDetails.delete_article(), name='remove_article'), url(r'^company/transcript/(?P<transcript_id>[0-9]+)/$', views.TranscriptList.as_view(), name='transcript_details'), ] VIEW (for this page): class CompanyDetails(generic.DetailView): model = Company template_name = 'company_details.html' context_object_name = 'articles' def get_queryset(self): return Articles.objects.filter(company_id=self.kwargs.get('company_id')).order_by('-date') def get_context_data(self, **kwargs): pk = self.kwargs.get('pk') context = super(CompanyDetails, self).get_context_data(**kwargs) context['articles'] = Articles.objects.filter(company_id=pk).order_by('-date') context['company'] = Company.objects.filter(id=pk) context['transcripts'] = Transcripts.objects.filter(company_id=pk) return context # Here is where I'm struggling... def delete_article(): article = Articles.objects.get(pk='article_pk') article.delete() -
MySQL encoding from Latin-1 to UTF-8
For a very long time i was suffering form the Latin-1 encoding in My Django web application DB causing this error when trying to select a matching string using LIKE : -- UnicodeEncodeError:'latin-1' codec can't encode character-- i've tried every solution from setting (charset='utf8') in the connection to applying cursor.execute("set names 'utf8'") before my actual query but nothing seams to work. Until i came across this blog post: https://www.whitesmith.co/blog/latin1-to-utf8/ about the encoding problem and it is the same problem that i have because when i looked in phpMyAdmin a saw that by default my DB i Latin-1 encoding: chatbot_brain=>utf8_general_ci information_schema=>utf8_general_ci Total: 2=> latin1_swedish_ci So, the solution is to dump the DB and change the description in the schema file: # Login into your future database host to create a new database with an UTF-8 charset $ mysql -h FUTURE_HOST -u FUTURE_USER -p mysql> CREATE DATABASE `FUTURE_DB` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; # Flush the current database schema on the future host, replacing all CHARSET=latin1 occurrences along the way mysqldump -h CURRENT_HOST -u CURRENT_USER -p CURRENT_DB --no-data --skip-set-charset --default-character-set=latin1 \ | sed 's/CHARSET=latin1/CHARSET=utf8/g' \ | mysql -h FUTURE_HOST -u FUTURE_USER -p FUTURE_DB --default-character-set=utf8 # Flush the current database data on … -
Store boolean variable in url dispatching
The following url definition should pass whether results/ is present in the url: url(r'^(?P<question_id>[0-9]+)/(?P<results>(results/)?)shorten/$', views.shorten, name='shorten') Currently it passes results/ or None which is sufficient for a simple: if results: pass But it would be more elegant to have True and False. How could this be done? -
Connecting seat's status in database to javascript(Django)
I'm using Django to build a bus booking website. I have a javascript code displaying the seating chart and their availability. I have code that passes the id and status of seats of the bus user selects. I want to link them to javascript so they can see on screen whether a seat is available or not. This is my Views def book_seats(request, bus_number,): valid = Bus.objects.filter(bus_number=bus_number,) if valid.exists(): for info in valid: bcapacity = info.capacity bprice = info.price seat_info = Seat.objects.filter(bus__bus_number=bus_number) seats = {} for object in seat_info: seats[object.id]=object.status js_seats = json.dumps(seats) template = 'seats.html' context = {'capacity': bcapacity, 'price': bprice, 'seats':js_seats} return render(request, template, context) else: return HttpResponse("Dude Stop messing with URL") As you can see I pass the bus number in the view which filters the database for seats and seats are then copied in js_seats. Then they are passed to the template using context. This is my seats.html template <div class="cover-container"> <div id="seat-map"> <div class="front-indicator">Front</div> </div> <div class="booking-details"> <h2>Booking Details</h2> <h3> Selected Seats (<span id="counter">0</span>):</h3> <ul id="selected-seats"></ul> Total: <b>Rs <span id="total">0</span></b> <button class="checkout-button" onClick="book()">Checkout &raquo;</button> <div id="legend"></div> </div> </div> {% endblock %} {% block script %} <script> var capacity = {{ capacity }}; var price = … -
Why the contents of the form changes?
I am tring to create dynamic list to choicesof symbol field. I create that list inside view then put it to form constructor. I want to take all data from Dictionary modal put it inside choices and show in my form but in the same time I dont need to show data which is already exist in Requirement modal. At start it shows form correct: Then when I try to click submit button form changes to this: (Whats wrong happenes?) models.py: class Dictionary(models.Model): symbol = models.CharField(_('Symbol'), max_length=250) name = models.CharField(_('Name'), max_length=250) class Requirement(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) symbol = models.CharField(_('Symbol'), max_length=250) name = models.CharField(_('Name'), max_length=250) forms.py: class RequirementForm(forms.ModelForm): symbol = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple) class Meta: model = Requirement fields = ('symbol',) def __init__(self, final_list, *args, **kwargs): super(RequirementForm, self).__init__(*args, **kwargs) self.fields['symbol'].choices = [(x[0], x[1]) for x in final_list)] views.py: def requirement_add(request, project_code): project = get_object_or_404(Project, pk=project_code) if request.method == 'POST': form = RequirementForm(request.POST) if form.is_valid(): requirement_dict = dict([(x.symbol, x.name) for x in Dictionary.objects.all()]) symbols = form.cleaned_data.get('symbol') requirement = form.save(commit=False) for symbol in symbols: requirement.project = project requirement.symbol = symbol requirement.name = requirement_dict[symbol] requirement.pk = None requirement.save() else: requirements = Requirement.objects.filter(project=project_code) current_list = [] for x in requirements: y = (x.symbol, x.name) current_list .append(y) … -
How to prepopulate test database by necessary data?
I need to do some unit tests in my Django project. The problem is that almost every use case depends on prepopulated database objects. For example, I want to create a product and test, if there were all pre_save signals successful. from django.contrib.auth.models import User from django.test import TestCase from .models import Product class ProductTestCase(TestCase): def setUp(self): self.user = User.objects.create(username='test_user') self.product = Product.objects.create(name='Test product',user=self.user) def test_product_exists(self): self.assertIsNotNone(self.product) def product_is_active_by_default(self): ... I can't do that because product has to have User object related. But I can't create a User object because User has to have related plan object. There are multiple plans in my production database from which one is default but there are no plans inside test database. So to be able to do unit tests I need to prepopulate test database with multiple objects from multiple apps. How can I do that? -
Django - display Json or Httpresponse in template
I have something this in views.py: return JsonResponse({'foo': 'bar'}) How would i display "bar" in the template? Something like: <h1 id="demo"></h1> <script> document.getElementById("demo").innerHTML = ?JsonResponse?; </script> or could it be done with http response? return HttpResponse("Bar") and html: <h1 id="demo"></h1> <script> document.getElementById("demo").innerHTML = ?HttpResponse?; </script> -
django api - Mongo DB vs sqlite
I am working on a program that currently using django framework that is interfacing sqlite db. I am considering moving to Mongo DB but I am finding it diffcult to understand if in addition to all the configuration modifications I will have to change the django api. I trying to minimize the work for this transfer. It is important to say that in the future I might interface with SQL/NOSQL database. is working with Mongo DB still recommended? -
(django) Why do I get an error when adding app to INSTALLED_APPS but not when just importing?
I wrote an app with abstract classes, some utils functions, my common template tags and so on. Somewere I saw it's recommended way to do this stuff to a reusable app. (It's all related to each other.) Why not? It seems to be a good idea. So I made the stuff being part of an app. Since that app has no urls, views and not the normal structur, it's more like a python module. (But it needs django.) When I import this app the normal way (with import myapp on top of the files) it works fine. Looking for bestpractice I saw in the official django tutorial part 8 that's recommended to import apps in INSTALLED_APPS in settings.py. Since I made my utils module being an app I thought I could just add a line to INSTALLED_APPS. Just like this: myapp.apps.MyappConfig. My project structure: project |-... [multiple normal apps] |-myapp [which is my utils app] |-project [the inner folder] |-... [some other stuff] As you can see, myapp, the utils app, is still part of the project (and hasn't been made a reusable app yet.) But when I add that line to INSTALLED_APPS I get the following traceback: Unhandled exception … -
Django passing data from one app to another?
I am using django-allauth for my authentication. I have a dashboard which has many links. example: user.html `{% include 'sidebar.html' %} <h1>Profile View</h1> <p>{{ profile.username }}</p>` change_password.html `{% include 'sidebar.html' %} <h2>Change Password</h2> <p>{{ profile.username }}</p>` sidebar.html `<a href="{% url 'profile_view' slug=profile.username %}">Profile View</a> <a href="{% url 'change_password' %}">Change Password</a>` views.py class ProfileView(DetailView): template_name = "user.html" queryset = User.objects.all() context_object_name = 'profile' slug_field = "username" change password view is from django-allauth. How can i pass the the username from the ProfileView to the change password view so that i can display in the change_password.html page. Main Problem Since i have been including sidebar.html to both the views, it works good in ProfileView but when i navigate to change_password view i get the following error Reverse for 'profile_view' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['(?P[-\w.@+-]+)/$'] the error does not show in ProfileView because the profile.username returns a value, but when i navigate to change_password view i get the above error because the profile context object only passes in that particular view. i want to use that context_object through out the project. Is there a simple way to do it? other than build a JSON API? -
Issue with for cycle in django and javascript
please help, because i failed My problem. I used django, and tried to make replay of comments due their id. Everything is working, but i can get only last item from for cycle via javascript. {% for comment in object_comments %} <li> <article> <div class="comment-avatar"> <img src="images/blog/author.png" class="avatar"> <span class="comment-reply"> <a id='reply' class="comment-reply-link" onClick="a_onClick()">Reply</a> </span> </div> <script> function button_onClick() { $('').click(); } function a_onClick() { window.scrollTo(0,document.body.scrollHeight); document.getElementById('text').value = "{{comment.name}}"; } </script> <div class="comment-body"> <div class="meta-data"> <a href="#" class="comment-author">{{ comment.name }}</a> <span class="comment-date"> {{ comment.pub_date }} </span> </div> <div class="comment-content"> {{ comment.text }} </div> </div> </article> </li> {% endfor %} The getting line is "document.getElementById('text').value = "{{comment.name}}";" I know it's not possible, but maybe u can help to find some workaround. -
Django - post multiple files with ajax
How could I post number between 1-6 and multiple image files with ajax? I would like to do this, because I want to upload files and display errors without refreshing, but I can`t set it up. Is it even possible to upload multiple images without using any external modules, etc, just ajax? Form is in modal. Html: <!-- Modal --> <div class="modal fade" id="myModalHorizontal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true">&times;</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title" id="myModalLabel"> Add exam </h4> </div> <!-- Modal Body --> <div class="modal-body"> <form id="form" class="form-horizontal" role="form" method="post" enctype="multipart/form-data" action="{% url 'create_exam' letnik_id=letnik_id classes_id=classes_id subject_id=subject_id %}" id="post-form" onsubmit="myFunction()"> {% csrf_token %} <div class="form-group" csrf="{{ csrf_token }}"> <label class="col-sm-2 control-label" for="inputEmail3">Številka Testa</label> <div class="col-sm-10"> <select class="form-control" id="exam_number" name="exam_number"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> </select> </div> </div> <div class="form-group"> <label class="col-xs-2 control-label" >Pictures</label><br> <div class="col-sm-10"> <input name="exam_file" type="file" accept="*" multiple required> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> </div> </div> </div> <!-- Modal Footer --> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal"> Close </button> <button class="btn btn-primary" id="form-submit" type="submit"> Add </button> </div> </form> </div> </div> </div> -
How to override SearchForm method in Django Haystack
I aim to have my Django Haystack Whoosh search return all results if no results where found. In Haystack documentation I read that I can override the no_query_found method (see below) in my SearchForm to do this. But I have no idea how. Any ideas? class SearchForm(forms.Form): def no_query_found(self): """ Determines the behavior when no query was found. By default, no results are returned (``EmptySearchQuerySet``). Should you want to show all results, override this method in your own ``SearchForm`` subclass and do ``return self.searchqueryset.all()``. """ return EmptySearchQuerySet() Here's my forms.py: from django import forms from .models import Blog, Category from locations.models import Country, County, Municipality, Village from haystack.forms import SearchForm class DateRangeSearchForm(SearchForm): start_date = forms.DateField(required=False) end_date = forms.DateField(required=False) def search(self): # First, store the SearchQuerySet received from other processing. sqs = super(DateRangeSearchForm, self).search() if not self.is_valid(): return self.no_query_found() # Check to see if a start_date was chosen. if self.cleaned_data['start_date']: sqs = sqs.filter(pub_date__gte=self.cleaned_data['start_date']) # Check to see if an end_date was chosen. if self.cleaned_data['end_date']: sqs = sqs.filter(pub_date__lte=self.cleaned_data['end_date']) return sqs -
Enum type django and rest framework
I have a problem with the rest framework and one enum field. I get this error: File "/usr/local/lib/python2.7/dist-packages/coreapi/codecs/corejson.py", line 48, in decode_schema_from_corejson return schema_cls(title=title, description=description) TypeError: __init__() takes exactly 2 arguments (1 given) when the model has this field: class PuddleAtomStatus(ChoiceEnum): INVALID = "INVALID" OK = "OK" class PuddleAtom(Model): name = models.CharField(max_length=255, primary_key=True) ingestion_flow = models.CharField(max_length=256) status = EnumChoiceField(enm_class=PuddleAtomStaus) but anything is fine when status = models.CharField(max_length=100) I'm using Django 1.11 and python 2.7 Is there a way to fix this and leave the model with the enum field ? -
Error was: cannot import name 'GDALRaster' in windows 8.1
(casino_locater) C:\Users\....\Desktop\Geolocation>python manage.py makemigrations ............. .............. .............. django.core.exceptions.ImproperlyConfigured: 'django.contrib.gis.db.backends.postgis' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Error was: cannot import name 'GDALRaster' -
Raven - Sentry and Django: AttributeError: 'function' object has no attribute 'send'
I installed raven-python in my django project, the ./manage.py raven test works, but I get a big traceback when I want to load any page of my app (the development server starts correctly): Traceback (most recent call last): File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 177, in __call__ signals.request_started.send(sender=self.__class__, environ=environ) File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/django/dispatch/dispatcher.py", line 201, in send response = receiver(signal=self, sender=sender, **named) File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/raven/contrib/django/models.py", line 209, in before_request self.client.context.activate() File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/raven/contrib/django/models.py", line 55, in <lambda> __getattr__ = lambda x, o: getattr(get_client(), o) File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/raven/contrib/django/models.py", line 135, in get_client instance = Client(**options) File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/raven/contrib/django/client.py", line 138, in __init__ Client.__init__(self, *args, **kwargs) File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/raven/base.py", line 222, in __init__ self.hook_libraries(hook_libraries) File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/raven/base.py", line 275, in hook_libraries hook_libraries(libraries) File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/raven/breadcrumbs.py", line 364, in hook_libraries func() File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/raven/utils/__init__.py", line 185, in new_func rv = func(*args, **kwargs) File "/home/vince/.virtualenvs/abelujo/lib/python2.7/site-packages/raven/breadcrumbs.py", line 286, in _hook_requests real_send = Session.send AttributeError: 'function' object has no attribute 'send' I don't know where to investigate. Any idea what's going on ? Thanks. raven/django documentation (I don't use the client defined at the end of the setup). I use django-whitenoise to serve static files, setted on wsgi.py but it does not appear to have any influence (I disabled it). … -
Setting intial values in Django Form
I have a Django form: class PlayerForm(forms.Form): OPTIONS = MyUser.objects.all() players = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=OPTIONS) I want the initial values of the players to be checked if MyUser.player = True. How do I set these initial values? -
(django) get query of child class
I have a super class like this: class Superclass(models.Model): number = models.PositiveIntegerField() class Meta: abstract = True def get_next(self): return Superclass.objects.get(number=self.number+1) Now, I have a child class that inherits from the superclass. What's the problem? I can't do this: Superclass.objects because the superclass doesn't refer to any database table. I don't want to query all Superclass childs, only the one of the current child class, like this: When I do instance_of_child1.get_next I don't want to get an instance of Child2. How to solve this? My first idea was to add a static constant to any child class that contains the class (So I could do self.myclass.objects) But this seems to be not a good way. Make the method get_next being part of the child class. Problem: there will be duplicates. -
Why css for admin url in python-django project could not loading?
I am new to python & django. I have learnt basic of both and made a simple project called PythonDjangoDemo. I have visited admin urls during development. But I am unable to load css for admin url in python-django project. At first lets look at project structure. I have - PythonDjangoDemo |--- PythonDjangoDemo | |--- __init__.py | |--- settings.py | |--- urls.py | |--- wggi.py |--- static_cdn | |--- admin | | |--- css | | | |---base.css | | | |---login.css | | |--- fonts | | |--- img | | |--- js |--- media_cdn |--- templates |--- manage.py |--- db.sqlite3 Let's have a look at settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ... ... ... STATIC_URL = '/static/' MEDIA_URL = "/media/" STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn") I have putted all my css for admin urls at "static_cdn/admin/css". While I am trying to access "127.0.0.1:800/admin" then I do not get any error(s). Here is the console output - [30/Apr/2017 16:04:58] "GET /admin/ HTTP/1.1" 302 0 [30/Apr/2017 16:04:59] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1650 [30/Apr/2017 16:04:59] "GET /static/admin/css/base.css HTTP/1.1" 200 16066 [30/Apr/2017 16:04:59] "GET /static/admin/css/login.css HTTP/1.1" 200 1203 Not Found: /favicon.ico [30/Apr/2017 16:04:59] "GET … -
Django autocomplete-light v3 from db
I've already make it directly in HTML page with Jquery but I think isn't a good solution due to the big item list. I think it's better have a huge list stored in the db and than autocompile the field in my case. I want autocompile (with airport name) two field (departure and destination). So in models.py I make two class: class Aero(models.Model): departure = models.CharField(max_length=20) destination = models.CharField(max_length=20) class AirportName(models.Model): air_name= models.CharField(max_length=70) I populate the db with 3000 airport (I use AirportName class to do that). Now I would like that when a user start to digit in departure or destination field (in a form), it will appear the possibile match airport list. I read the documentation but I don't understand how do that, maybe I mistake everything. url.py: url( r'^fly-autocomplete/$', Fly.as_view(), name='fly-autocomplete', ), views.py: class Fly(autocomplete.Select2QuerySetView): def get_queryset(self): form = AeroForm() qs = AirportName.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs forms.py: class AeroForm(forms.ModelForm): class Meta: model = Aero fields = ('__all__') widgets = { 'departure': autocomplete.ModelSelect2(url='fly-autocomplete'), 'destination': autocomplete.ModelSelect2(url='fly-autocomplete'), } -
Django: 'ManyToManyDescriptor' object has no attribute 'create'
I have two classes in models.py class Account(models.Model): ... class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) accounts = models.ManyToManyField(Account, blank=True) Now in my views.py I have: def create_account(request): account = Account(symbol=request.POST['symbol']) account.save() However, when the form that calls the create_function is successfully submitted, my Django debug mode throws the error: 'ManyToManyDescriptor' object has no attribute 'create', and SELECT * FROM the relevant table in my database confirms that no row has been added. After searching this error online, I can confirm that this probably has to do with the fact that the Profile class is many-to-many associated with the Account class and that I should be creating Account objects differently, however I am not sure how to do it correctly. -
Django MEDIA not serving despite configuration
I know this is a prevalent topic, but I still have yet to find a recent answer that helps. I have setup my dev environment to serve MEDIA in what I believe is the correct way, but images are still not resolving. Paths being return propery in template, but I believe the issue is with URLS.PY? This is my settings.py: if DEBUG: #For local STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') if DEV: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' ADMIN_MEDIA_PREFIX = 'http:/127.0.0.1:8000/admin-media/' This is the template itself (attached image is the rendered template itself, which seems correct): <div><img src="{{MEDIA_URL}}products/{{product.filename}}"></div> This is my primary URLS.py (top level, not application specific, but I've added this line in the app specific one as well): urlpatterns = [ url(r'^', include('drivel.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^tinymce/', include('tinymce.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) What am I missing? I am down to the wire and can't seem to get this going. I also am open to recos for the production site as I'm new to Django and best practices in production. Environment is Py 2.7, Django 1.8. enter image description here -
Django - display Json response in template
In views.py i have: return JsonResponse({'foo': 'bar') How can i "capture" that Json response in template and display it inside <h1> </h1>?