Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Twitter typeahead not showing text only a blank drop down
I am having a problem with my typeahead, the suggestion dropdown box comes up while typing however no text are shown. What I did to see if it was just a random dropdown was to type words that I know are in my json file and words that are not. Once I type words that are not in my database the dropdown box is removed, so it is actually working without the actual text from the json file. Also while typing in the search box, I see within the python console that a query is being made. Here you can see me typing 'Number theory' that is in my json, as you can see the dropdown appears without any text. I made sure that my json format is correct by using http://jsonlint.com/. Why isn't the text showing in the drop down box? This is my view: def search_subclasss(request): q = request.GET.get('subclass', '') sub_classs = SubClasss.objects.filter(subclasss__icontains=q) results = [] for subclasss in sub_classs: results.append([subclasss.subclasss, subclasss.subject_id]) data = json.dumps(results) return HttpResponse(data, content_type='application/json') This is my html: <script type="text/javascript"> var bestPictures = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('subclasss'), queryTokenizer: Bloodhound.tokenizers.whitespace, remote: { url: "{% url 'search_subclasss' %}?subclass=%QUERY", //url: '/search_subclasss/?subclass=%QUERY', wildcard: '%QUERY' } }); $('#remote .typeahead').typeahead(null, … -
displaying group permissions causing duplicate queries in django
TLDR : I wanted to serialize a Group along with its permissions name. But lot of duplicate queries of content_type from Permission Model occurred. I tried to solve it through prefetch, but didn't work. What am i doing wrong? so my serializer for retreive method is given below class RetrieveGroupSerializer(serializers.ModelSerializer): user_set = UserSerializer(many=True, read_only=True) permissions = PermissionsSerializer(many=True, read_only=True) class Meta: model = Group fields = ('name', 'user_set', 'permissions') The serializer for list method is given below class GroupSerializer(serializers.ModelSerializer): user_set = UserSerializer(many=True) permissions = PermissionsSerializer(many=True) class Meta: model = Group fields = ('url', 'user_set', 'permissions') the views is given below class GroupViewSet( mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): """ Creates, Updates, and retrives User Groups """ queryset = Group.objects.all().prefetch_related('user_set').prefetch_related('permissions__content_type') serializer_class = GroupSerializer permission_classes = ( IsAuthenticated, ) action_serializer_classes = { "create": CreateGroupSerializer, "retrieve": RetrieveGroupSerializer, "update": UpdateGroupSerializer } def get_serializer_class(self): try: return self.action_serializer_classes[self.action] except (KeyError, AttributeError): return super(GroupViewSet, self).get_serializer_class() When I use the list method I am not facing any duplicate queries, but when I use the retrieve method on any single group instance I am getting lot of duplicate queries. As you can see the content_type from Permission Model is getting queried 62 times. So I used prefetch_related on the Foreign Key … -
Passing jQuery slider value onto Django form
I'm having a difficult time extracting a jQuery slider value in a Django form when it is submitted. I can pass a value to it from the URL on through the outer and inner urls.py and views.py when the page is accessed or refreshed, but I can't include the slider value in the form upon submission. Needless to say I have tried numerous methods to extract the value, including jQuery post methods and AJAX, but nothing I've tried works. First, I created a simple form (forms.Form), and then later tried using a model form, expecting more control, but returned to a forms.Form. My form.py is: class ChoiceForm(forms.Form): '''Checkboxes.''' GeoJunk = forms.BooleanField(required=False, initial=True) Little_Free_Library = forms.BooleanField(required=False, initial=True) Garage_Sale = forms.BooleanField(required=False, initial=True) '''Field for jQuery slider widget value. I initially don’t care if it is hidden, especially during troubleshooting.''' slider_field = forms.CharField(max_length=4, required=False) My views.py is complex, but the essence is: def profile_list(request, sort_arg='default', latlonzoom='39.991622,-105.250098,15', choice='7', rangefactor='0'): request_user = request.user [lat, lon, zoom] = latlonzoom.split(',') lat = float(lat) lon = float(lon) zoom = int(zoom) ''' Range of view. ''' if rangefactor == 0: range = 0.1 else: range = 1.0 ''' Initialize. ''' slider_value = 0 if request.method == 'POST': choice_form = … -
Django-tinymce : apps aren't loaded yet
recently i have follow the docs from django-tinymce I have added to installed-apps, added to urls.py, and import tinymce to model, but when i migrate or runserver i got "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet." Any one can help please? appreciated ! -
how to add intelligence to search using simple context based AI?
hi i am working on a scenario,how to add intelligence to the search engine and already implemented the search engine using django-rest framework ,so i am trying to add the intelligence to my search . I am researching on contextual searching and i am confused whether to use NLTK (WordNet) or aip.ai :https://api.ai/ So is this statement: Molecular dynamics (MD) is a computer simulation method for studying the physical movements of atoms and molecules, and is thus a type of N-body simulation. The atoms and molecules are allowed to interact for a fixed period of time, giving a view of the dynamical evolution of the system. so these are my contexts and able to search these context/questions: What are allowed to interact over a period of time What is MD What is Molecular Dynamics What do we study in MD What do we study in MD/Molecular Dynamics What type of simulation is MD Any suggestions would be appreciated.... -
Django storing image in static assets but not saving the file path in DB
I am following this answer to fetch an image and store it in my model: Programmatically saving image to Django ImageField I would like to store the image in static assets and also store the path to that image on the model attribute product_photo.large_image_file. When I manually execute this code in shell_plus the image is successfully downloaded and stored and the path to the file is successfully saved in the DB. When the code is executed with Django runserver, the image is downloaded and added to the static files but the path is not stored in the DB. The exact same code works in shell_plus but does not work with runserver. I used ipdb to step into the runserver environment and when I checked product_photo.large_image_file it gives me the correct path but that path is not saved into the DB, even if I call product_photo.save() manually. Any ideas would be much appreciated! product_photo = Product.objects.get(id=product_object.id) if product_photo.large_image_url is not None: try: product_photo.large_image_file.url except: result = urllib.request.urlretrieve(product_photo.large_image_url) product_photo.large_image_file.save(os.path.basename( product_photo.large_image_url), File(open(result[0], 'rb')) ) product_photo.save() -
Django css not working unless add 'whitenoise.middleware.WhiteNoiseMiddleware' in Middleware
My static file settings are: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) My base html's static are as follows: <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> {% block title_tag %}<title>{% block title %}{% if page.title %}{{ page.title }}{% endif %}{% endblock %}</title>{% endblock %} <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/> <link href="{% static 'site/css/jquery-ui.css' %}" rel="stylesheet"> <link href="{% static 'site/css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'site/css/bootstrap-theme.min.css' %}" rel="stylesheet"> <link href='https://fonts.googleapis.com/css?family=Satisfy' rel='stylesheet' type='text/css'> <link href="{% static 'site/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet"> <link href="{% static 'site/css/mystyle.css' %}" rel="stylesheet"> {% block head_extra %} {% endblock head_extra %} </head> This settings not work until I use 'whitenoise.middleware.WhiteNoiseMiddleware', in Middleware as: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', ................... ] Could anyone suggest me how css work without whitenoise in local server. For your information my static folder in my project root. -
Django Admin: Can we cascade more than one custom filters?
So, In my project for a Model, I have written 2 custom filters, that help filter according to columns present in a different model. Now if I apply one of the custom filters, then it gives me a filtered result set. Now I want to apply the next custom filter on the result of the last filter, rather than querying the complete model. Can I do that? -
AJAX data being sent to the wrong Django view
I'm new to django and ajax so I've been working on a project to learn it. I have two buttons, one that adds a marker and one that deletes a marker. Here is the views.py @csrf_exempt def save(request): searchVar = request.POST.getlist('search[]') waypoint = Waypoint() waypoint.name = searchVar[0] waypoint.geometry = ('POINT(' + searchVar[2] + " " + searchVar[1] + ')') waypoint.save() return HttpResponse(json.dumps(dict(isOk=1)), content_type='application/json') @csrf_exempt def remove(request): objectID = request.POST.get('id') point = get_object_or_404(Point, pk = objectID) point.delete() Here is the urls.py from django.conf.urls import patterns, url, include urlpatterns = patterns('googlemaps.waypoints.views', url(r'^$', 'index', name='waypoints-index'), url(r'', 'save', name='waypoints-save'), url(r'', 'remove', name='waypoints-remove'), ) and here is the ajax from the js file $('#saveWaypoints').click(function () { var searchList = [search.name, search.geometry.location.lat(), search.geometry.location.lng()] $.ajax({ url : "waypoints-save", type : "POST", data : { search : searchList } }, function (data) { if (data.isOk) { $('#saveWaypoints'); } else { alert(data.message); } }); }); $('#removeWaypoints').click(function () { console.log(markerID); $.ajax({ url : "waypoints-remove", type : "POST", data : { id : markerID } }, function (data) { if (data.isOk) { $('#removeWaypoints'); } else { alert(data.message); } }); }); The save button works fine, but when I click on the remove button I get this error in my console log … -
Related name query while using multi-table inheritance in Django
Currently working on Django 1.6, MySQL and South: I recently starting working with inheritance and Django models. If I use a foreign key with a related name to make a query, the query doesn't seem complete, and objects are missing. I want to emphasize that the model we are inheriting is not an abstract model. Using the code below as a sample: from django.shortcuts import get_object_or_404 Car(models.Model): name = models.CharField(null=True, blank=True, default=None,) trunk_size = models.IntegerField(default=0) fleet_leader = models.ForeignKey("Car", related_name='car_fleet', null=True, default=None) class Meta: verbose_name = "Car" verbose_name_plural = "Cars" Bigcar(Car): extra_storage_size = models.IntegerField(default=0) class Meta: verbose_name = "Car" verbose_name_plural = "Cars" If I make the query xcar = Car.objects.get(pk=123) Car.objects.get(fleet_leader=xcar) would provide expected results, with every object where their fleet leader pointing to xcar (pk=123). However, xcar.car_fleet.all() would not yield all the entries that are present in the database. So I'm wondering if anyone knows what's going on with these queries? Am I missing some setting or code that I should implement following the inheritance being used? I've looked into the Django documentation and most of the emphasis is on abstract model inheritance usage. -
How does Django decide where to put the output of makemessages?
I have a Django app with several local locale folders, stored in the translations folder of the base directory: translations/public/locale/{en,fr} translations/portal/locale/{en,fr} translations/terminology/locale/{en,fr} with corresponding entries in LOCALE_PATHS: LOCALE_PATHS = ( os.path.abspath(os.path.join(BASE_DIR, 'translations', 'public', 'locale')), os.path.abspath(os.path.join(BASE_DIR, 'translations', 'portal', 'locale')), os.path.abspath(os.path.join(BASE_DIR, 'translations', 'terminology', 'locale')), ) It all works fine, but I'm confused on to tell makemessages where to put its output. I don't see any relevant parameters in the source code. My preference would be to put the file somewhere else, like: % bin/dev/manage.py makemessages -o .../derived_translations How do I control, or at least determine where the output files are put? -
Python objects lose state after every request in nginx
This is really troublesome for me. I have a telegram bot that runs in django and python 2.7. During development I used django sslserver and everything worked fine. Today I deployed it using gunicorn in nginx and the code works very different than it did on my localhost. I tried everything I could since I already started getting users, but all to no avail. It seems to me that most python objects lose their state after each request and this is what might be causing the problems. The library I use has a class that handles conversation with a telegram user and the state of the conversation is stored in a class instance. Sometimes when new requests come, those values would already be lost. Please has anyone faced this? and is there a way to solve the problem quick? I am in a critical situation and need a quick solution -
can't set radio button to required in django
I have the following radio button html using django widget tweaks (i do not have to use this library and open to using whatever method works): {% for choice in seeking_form2.disaster_recovery %} <div class="radio radio-primary radio-inline"> {{ choice.tag|attr:"required" }} <label for='{{ seeking_form2.disaster_recovery.auto_id }}_{{ forloop.counter0 }}'>{{ choice.choice_label }}</label> </div> {% endfor %} My model looks like: BOOL_CHOICES = ((True, 'Yes'), (False, 'No')) disaster_recovery = models.BooleanField(choices=BOOL_CHOICES, default=False, ) I get the error: 'SafeText' object has no attribute 'as_widget' -
django+uwsgi logging with TimedRotatingFileHandler "overwrites rotated log file"
I recently switched my django production web app from apache+mod_wsgi to nginx+uwsgi in emperor mode. All it's ok except Time Rotated log files. My web app uses a log file named appname.log to log all requests, and with apache it rotates at midnight without problems. With uwsgi the file rotates at midnight but some uwsgi process/worker writes into this rotated file (example rotated file: appname.log.2017-01-08) instead of write into appname.log , this cause that the rotated file is overwritten. A solution seems to be touching the uwsgi .ini file (I'm not completely sure...), but I don't want to restart/reload uwsgi if a user is still connected to my app. There is a possibility or a configuration that I can use to notify to all uwsgi process that the logfile is changed without restarting the web app? If possible I would have the same behaviour that I have in apache+mod_wsgi. ConcurrentLogHandler, is too old and I don't want use syslog or logrotate :) Someone have same problems? someone have suggestions? thanx This is my setting: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '[%(asctime)s];[%(levelname)s];[Proc:%(process)d];[Thread:%(thread)d];%(module)s-%(funcName)s:%(lineno)d;Msg:%(message)s;' }, 'simple': { 'format': '[%(asctime)s] [%(levelname)s] %(message)s' }, }, 'filters': { 'require_debug_false': { … -
Why do I get Invalid literal for int() exception error when running basic django query?
A simple django query is not working and I am wondering why models.py class Entry(models.Model): headline= models.CharField(max_length=200,) body_text = models.TextField() author=models.ForeignKey(settings.AUTH_USER_MODEL, related_name='entryauthors') pub_date=models.DateTimeField(auto_now_add=True) def __str__(self): return u'%s %s %s %s %s %s %s' % (self.headline, self.body_text, self.author, self.pub_date) In the django shell or in my views I have tried itemstosell = Entry.objects.get(author=username)[:4] which results in: Exception Type: ValueError Exception Value: invalid literal for int() with base 10: 'john' -
Can't downwload Django
So I have Python on my new Macbook Air and now I'm trying to download Django and having no luck. I've tried "wget" and the link from the Django site, then I downloaded it and tried "python setup.py install". In both cases I get invalid syntax. I have Python 2.712. I'd really appreciate any help!! Thanks, Tom -
(Post polls tutorial) Django admin: After adding new related model type (free response, true/false, etc.), how to add to Django admin
I just finished the Django polls tutorial. In the tutorial, you essentially build a multiple choice question (a question with related choices). You then configure the admin such that you get this really nice "ADD CHOICE" button. (I love Django so far) I want to build a quiz app that has other question types too, such as free-response, true/false, etc, and collect the series of different question under a new model called Quiz. I eventually want to get a button "SELECT QUESTION TYPE" in Django admin, but how would I do this? Here's my attempt at my models: (models.py) class Quiz(models.Model): quiz_name = models.CharField class Multiple_choice_question(models.Model): quiz = models.ForeignKey(Quiz) question_text = models.CharField class Free_response_question(models.Model): quiz = models.ForeignKey(Quiz) question_text = models.CharField class Choice(models.Model): question = models.ForeignKey(Multiple_choice_question) choice_text = models.CharField In my models above, Multiple_choice_question and Free_response_question are identical except for the fact that Multiple_choice_question has children (choices) and Free_response_question does not, but I will be creating many different problem types, with many different attributes other than question_text: for example I'll have questions with/without images, others with attributes such as "x-component" and "y-component" for drawing vectors as the question, etc., so I don't just want to use the same model for all … -
django tests setUp and --keepdb
I have many, many migrations I can't delete. So when I run the tests it takes too much time unless I run them with --keepdb which is perfect. The only question is how does --keepdb and the setUp method work together. In the setUp method of the test I do something like this: class APITests(APITestCase): fixtures = ['tests/testdata.json'] def setUp(self): username = "test" password = "1234" user_created = User.objects.create_user(username=username, password=password) body = { "username": username, "password": password } cart = Cart.objects.create() Client.objects.create(user=user_created, cart=cart) APITestCase is just a django rest framework wrapper for the django test class. I create a user, a client and a cart for that user. If I re-run the tests with --keepdb, will the setUp method create a duplicated user or cart? how does it work in this case? -
django models timefield o min:sec format
How can I set TimeField format in django models to be [min:sec] like for an audio track? class Song(models.Model): title = models.CharField(max_length=128) duration = models.TimeField(null=True) -
Should I add Django admin static files to my git repo?
I ran manage.py collectstatic on my webapp and now I have a new static folder with only Django admin files (so far I've been using just CDNs for my project CSS and JS files). Should I track these admin static files on my git repo? What's the best practise? -
Django mlbgame object list of lists
I am new to Python, and I know a little big of Java, so I kind of know objects.Now, in python I am using mlbgame to get the schedule of one team. I am using games(years, months=None, days=None, home=None, away=None). Here is my view def baseball(request): angels_game = mlbgame.games(2017, home='Angels', away='Angels') return render(request, 'home/baseball.html', {'games1': games1, 'angels_game': angels_game}) Now here is my template <h1>Anaheim Angels Games</h1> {% for anaheim in angels_game %} <p>{{ anaheim }}</p> {% endfor %} This is what I get in my page Anaheim Angels Games [<mlbgame.game.GameScoreboard object at 0x7f04f2f0ac50>] [<mlbgame.game.GameScoreboard object at 0x7f04f31f5978>] [<mlbgame.game.GameScoreboard object at 0x7f04f2ef22e8>] [<mlbgame.game.GameScoreboard object at 0x7f04f1e9b048>] I understand, I am getting the object there, but I do know how to use that object, like I would do in Java using the toString() method. Can anybody direct me on the right path here? Thanks, -
Django Rest Framework serializers as forms and nested relationships
I am trying to use the django rest framework to generate html forms for model creation. Suppose I have a serializer that belongs to a model with a ManyToMany relation. class SerializerExample(serializers.ModelSerializer): mtm = ManyToManySerializer(many=True) I then, in a django rest view, class AddModelView(StandardView): serializer_class = ModelSerializer renderer_classes = [TemplateHTMLRenderer] template_name = 'details.html' def get(self, request): model = Model.objects.get.all() serializer = ModelSerializer(model) return Response({'serializer': serializer, 'model': model}) And then suppose details.html looks like: {% load rest_framework %} <html><body> <form method="POST"> {% csrf_token %} {% render_form serializer %} <input type="submit" value="Save"> </form> </body></html> Lists are not currently supported in HTML input. instead of a multiselect or the abiliity to add new instances. What am I doing wrong? -
Django postgreSQL schema
Stupid question (again - referring to this question) but all I really want to do is to change the default schema from public to whatever. Is this really as complex as described above question? The question and corresponding answers are up to serveral years so maybe its worth dropping this again. Maybe I haven't read the above carefully enough yet but I've tried some of it without success. What exactly do I have to? Do I need to add the schema to the postgre DB manually or does the manage.py migrate-stuff take care of this? This 'options': '-c search_path=your_schema' doesn't work at all. If so than it must be 'options': '-c search_path=your_schema,public'. This doesn't throw an error but after migrating nothing appears in that specific db-schema. Anyone who successfully runs an Django-App in a none-public schema? -
dj-stripe: multiple subscriptions, single invoice
I have a rather complex subscription model in my project that is subject to change. I considered making a subscription for every possible combination of elements but that would quickly become unmanageably complex, especially with the future addition of elements. Anyways, what I want to be able to do is add multiple subscriptions to a single invoice, so that each subscription isn't treated as a separate invoice leading to messy billing. I am unsure how to do this. Right now when I call .subscribe it instantly creates an invoice and charges the customer. Looking at the Invoice creation methods, especially .add_item it looks like a subscription can be added as an argument, but if it is already invoiced, what is the point in adding it to another invoice, wouldn't this just be double charging? Anyway, from the available methods, it is difficult to see how this is possible, does anyone have a clear example? -
my program dont recognize beetwen modules & core i am on python2
i got a program, running on python inImportError: No module named coreenter code here the import i put; from core import wcolors, the file wcolors.py is inside a dir named core, there is another dir called modules, so when i run my program it give this error output: output: Traceback (most recent call last): File "anubis.py", line 7, in <module> from core import wcolors ImportError: No module named core dir structure the dir structure follows like that anubis>anubis.py (the script that i run) anubis>core>wcolors.py (the file i import from core) anubis>modules>[the modules i suposed to load during the execution.] as another detail all files in core are compiled with .pyc extention.