Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django annotate specific keys in json fields
I'm using Django 1.9 and Postgres 9.5. I have a model (MyModel) with a JSONField (django.contrib.postgres.fields). The JSON value has the same structure in all the objects in the model. { "key1": int_val_1, "key2": int_val_2 } I want to order my queryset by a value of a specified key in my JSONField. Something like MyModel.objects.annotate(val=F('jsonfield__key1')).order_by('val') This does not work - i get the following error Cannot resolve keyword 'key1' into field. Join on 'jsonfield' not permitted. Is there anyway i can achieve this? -
Multiple Database in Django
I am trying to create a Q/A website using Django and I want to use mutiple databases for all the apps Two secure database like admin, auth, forum A less secure (like sqlite3) database for the rest But I don't want to re-configure my models and apps. How can I do that?? -
Dynamic HTML page content
Let's say I want to show different items each time the user changes the search options. I get the new items by AJAX (This is mandatory so I can't use the POST, so I can't use the {% for %} loop of django template). Currently, I take the returned list of items, and pass it to a javascript function that generates HTML code. This function is not more than concatenating strings together and forming the new HTML content. A simple example: function build_items_list(items_list, container){ container.innerHTML = ''; for(var i=0; i<items_list.length; i+=1){ var item = items_list[i]; container.innerHTML += '<div>' + '<input type="checkbox" id="' + item.id.toString() + '">' + '<a href="' + item.url+'"><b>' + item.name + '</b></a>'+ '</div>' } } Obviously, it is not the best way to generate the content, and I have many similar contents to generate. What is the right way to generate such contents? Thank you very much. -
django python create a follow project function
I'm currently working on a site with django, python 3.The site allows you to follow projects that you like, and you can follow as many as you can as long as the that project exist. Here are my models of the site. This is my Team model, which is the model for all the projects you can follow class Team(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='team') created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) title = models.CharField(max_length=255) description = models.TextField() image = models.ImageField(upload_to='images/team_images', blank=True) roster = models.TextField(blank=True, default='') current_raise = models.IntegerField(blank=True, default=0) # current_backers = models.IntegerField(blank=True, default=0) time_left = models.DateTimeField(blank=True, default=timezone.now) raising_minimum = models.PositiveIntegerField(blank=False) raising_maximum = models.PositiveIntegerField(blank=False) duration = models.DateTimeField(blank=False) def __str__(self): return self.title This is the user profile mode, I have a Many to Many field in this model. class UserProfile(models.Model): user = models.OneToOneField('accounts.User') following = models.ManyToManyField(Team, related_name='user_following', blank=True) The problem is when I check the database, all the teams I've created for testing are in the 'following' field WITHOUT asking the user following them yet. What do you guys think is the best approach to this problem? -
Django admin date range filter
I'm trying to write a customer date range field for Django admin. This is my filter, which is very similar to the decade example provided in the docs but is not working for me. What am I doing wrong? It just shows all records for every selection. class DaysSinceAdvertFilter(admin.SimpleListFilter): # Human-readable title which will be displayed in the # right admin sidebar just above the filter options. title = _('Days Since Advert') # Parameter for the filter that will be used in the URL query. parameter_name = 'last_advert' def lookups(self, request, model_admin): """ Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar. """ return ( ('0', _('Less than 7 days')), ('7', _('7-13 days')), ('14', _('14-20 days')), ('21', _('21-27 days')), ('28', _('28-34 days')), ('35', _('35+ days')), ) def queryset(self, request, queryset): """ Returns the filtered queryset based on the value provided in the query string and retrievable via `self.value()`. """ # Compare the requested value to decide how to filter the queryset. today = datetime.date.today() if self.value() == … -
Django Celery MultipleObjectsReturned
I started getting the following error, not sure why. i am using celery==3.1.18, django-celery==3.1.16 with a Redis Backend, but i am using my database to store my results. The traceback is: [2017-02-08 12:49:47,389: ERROR/MainProcess] Error in timer: MultipleObjectsReturned('get() returned more than one WorkerState -- it returned 2!',) Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/kombu/async/timer.py", line 171, in apply_entry entry() File "/usr/local/lib/python2.7/dist-packages/kombu/async/timer.py", line 64, in __call__ return self.fun(*self.args, **self.kwargs) File "/usr/local/lib/python2.7/dist-packages/kombu/async/timer.py", line 132, in _reschedules return fun(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/celery/events/snapshot.py", line 73, in capture self.state.freeze_while(self.shutter, clear_after=self.clear_after) File "/usr/local/lib/python2.7/dist-packages/celery/events/state.py", line 428, in freeze_while return fun(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/celery/events/snapshot.py", line 70, in shutter self.on_shutter(self.state) File "/usr/local/lib/python2.7/dist-packages/djcelery/snapshot.py", line 127, in on_shutter self.handle_worker(worker) File "/usr/local/lib/python2.7/dist-packages/djcelery/snapshot.py", line 64, in handle_worker defaults={'last_heartbeat': self.get_heartbeat(worker)}, File "/usr/local/lib/python2.7/dist-packages/djcelery/managers.py", line 87, in update_or_create return get_queryset(self).update_or_create(**kwargs) File "/usr/local/lib/python2.7/dist-packages/djcelery/managers.py", line 70, in update_or_create obj, created = self.get_or_create(**kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 405, in get_or_create return self.get(**lookup), False File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 338, in get (self.model._meta.object_name, num) MultipleObjectsReturned: get() returned more than one WorkerState -- it returned 2! -
Django display multiple models in single template
How to do the same for detail view? views.py class ViewProfile(generic.DetailView): model = User slug_field = 'username' template_name = 'profile/profile_view.html' def get_context_data(self, **kwargs): ctx = super(ViewProfile, self).get_context_data(**kwargs) ctx['profile'] = Profile.objects.all() return ctx profile_view.html <h1>{{ user.username }}</h1> {% for profile in profile %} <p>{{ profile.full_name }}</p> {% endfor %} I need to display only the first in the list as detail view. any methods? -
self hosted Amazon S3 alternative - Django supported
I'm using Amazon S3 bucket to host media files of my Django application. I have used: https://github.com/jschneier/django-storages for it. The problem is that Amazon S3 is costing too much (about 36$ - 10$ for S3 and 26$ for "data transfer") I am looking for an opensource alternative for it which I can self-host on a VPS. It should be easy to integrate with Django as well. Thanks in advance. -
copying django admin in my project
i want to edit django admin. i need somethings more than that but i only want to manipulate django admin so if i copy admin folder from this path C:\Python35\Lib\site-packages\django\contrib in my project and change this line in setting.py 'django.contrib.admin', to this : 'admin' now i can make any changes that i want. i can change templates and views and ... but if i do this have i done a right thing? is that clear programing way or i should find a better way for doing that? why i don't have to do this? what's wrong with this solution? -
How can I sort a table column with ChoiceField in django with a specific order pattern?
I have a table with these columns in my template: <th><a href="?order_by=id&sort_type={{sort_type}}">Id</a></th> <th><a href="?order_by=status&sort_type={{sort_type}}">Status</a></th> In the views.py: sort_type = request.GET.get('sort_type', 'descending') field_order_by = request.GET.get('order_by', 'id') field_order_by = "-%s" % field_order_by if sort_type == "descending" else field_to_order sort_type = "descending" if sort_type == "ascending" else "ascending" my_rows = MyModel.objects.all().order_by(field_order_by) return render(request, 'my_app/my_template.html', {'rows': my_rows, 'sort_type': sort_type}) That works fine. When I click once in , the column is ordered ascending and if I click another time, the column is ordered descending. But 'Status' is a ChoiceField... NOT_REVIEWED = 0 BAD = 1 REGULAR = 2 GOOD = 3 STATUS_TEST = ( (NOT_REVIEWED, 'Not reviewed'), (BAD, 'Bad'), (REGULAR, 'Regular'), (GOOD, 'Good'), ) ...and that is the behaviour when I click on the status column: First, the default order for the status field is this pattern: [3,2,1,0] (descending) If I click another time, I have this pattern: [0,1,2,3] (ascending) If I click another time, I return to the descending pattern. But I dont want the ascending/descending pattern. I want that every time I click on the status column, the order pattern increases by 1: First, the default order for the status field is this pattern: [3,2,1,0] If I click another time, I want … -
Django rest framework api end points not accessble after implementing ouath 2 toolkit
My django rest api endpoints were working with the JWT authentication. Later I changed that to Oauth 2 toolkit. All are working fine from postman rest app. But the api doc test endpoints are not working. It shows the following screen. This page still shows even if I am logged in as administrator. Is there any change I need to do in the settings file? Current settings in settings.py is OAUTH2_PROVIDER = { 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'} } REST_FRAMEWORK = { 'DATETIME_FORMAT': "%m/%d/%Y %H:%M:%S", 'DATE_FORMAT' : "%m/%d/%Y", 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.ext.rest_framework.OAuth2Authentication', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 50, 'EXCEPTION_HANDLER': 'app_utils.views.exception_handler' } -
Django rest framework extra serializer field with get and post
I want to serialize a model and include extra field. I want use this serializer for list, detail and create views. class ExampleSerializer(serializers.ModelSerializer): field = serializers.CharField() class Meta: model = Example fields = ("field", ...) When I add new object everything is correct (I can validation custom field data), but when I get object, 'field' don't exists in response. Why is it like that? Is exist better solution for this? -
django inspect containerised mysql database
I have an odd one here. Im trying to inspectdb a MYSQL database that is inside docker container. I'd reason is I have to connect to the live version of this database bt need to see what django makes of it model wise. The containerised db is a dev vesrion so for me to play with. Any help would be appreciated. -
Django AuthenticationForm - user does not get logged in
I have a login form like so: login_form.html {% extends "base.html" %} {% block title %}Login{% endblock %} {% block content %} <h2>Login</h2> <form action="/accounts/login/" method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Login" /> </form> {% endblock %} A login complete page like so: login_complete.html {% extends "base.html" %} {% block title %}You are logged in{% endblock %} {% block content %} <h2>Thank you for logging in</h2> {% if user.is_authenticated %} <p>foo</p> {% endif %} {% endblock %} Login view: def login(request): if request.method == "POST": form = AuthenticationForm(data=request.POST) if form.is_valid(): auth.login(request, form.get_user()) return HttpResponseRedirect("/accounts/login/complete") else: form = AuthenticationForm() token = {} token.update(csrf(request)) token["form"] = form return render_to_response("registration/login_form.html", token) However the user does not get logged in. Username and password are correct (I tried with invalid combinations and I stay on the login page in that case and it displays an error) and I am using the correct login() method (auth.login and not my login() by accident). Edit: My login() method is being called, it also shows me the login complete page correctly, but the {% if user.is_authenticated %} <p>foo</p> {% endif %} does not show. What am I doing wrong? -
Bash Script for Completely remove django web app, supervisor, gunicorn, virtualenv
i have ubuntu instance on which multiple django web apps are running on virtual environment, im looking for a good bash script which completely remove any selected web app. like Stopping the supervisor process, gunicorn and removing the related Nginx and Supervisor Conf files. -
Django + Celery tasks on multiple worker nodes
I've deployed a django(1.10) + celery(4.x) on the same VM, with rabbitmq being the broker(on the same machine). I want to develop the same application on a multi-node architecture like I can just replicate a number of worker nodes, and scale the tasks to run quickly. Here, How to configure celery with rabbitmq for this architecture? On the other worker nodes, what should be the setup? -
Bokeh map not respecting div size
I want to embed a map using my Django application. Next to Bokeh, I'm only using Bootstrap. This related post doesn't have an answer that helped me: Bokeh plot not displaying correctly Annoyingly, the map does not respect the size of the bokeh div. When inspecting the elements, I can see that the figure exceeds the div. Removing css templates from Bootstrap does not seem to solve the problem. The surrounding HTML looks like this: <div class="container"> <table class="table"> Here's a table... </table> <div class="bk-root"> <div class="plotdiv" id="6b1ee173 etc..."></div> </div> </div> Any idea's about what's wrong? Let me know if I need to supply more information. Thanks in advance! -
Django url - matching value from list/tuple
Currently in my urls.py I have something like: url(r'^(?P<my_var>:|var1|var2|var3|other_string)/rest_of_url' it matches /var1/rest_of_url var2/rest_of_url var3/rest_of_url other_string/rest_of_url I would like to have a list/tuple of variables: VARIABLES = ('var1', 'var2', 'var3') That could store variables that can be matched in my url. However I do not know any django regex that could do that. To be precise, my goal is to have something like: url(r'^(?P<my_var>:regex_matching_any_of_VARIABLES|other_string)/rest_of_url' -
Global variable for gogoleMap key in django project
I need to open my gmap in a few pages: {% block extra_js %} <script src="{%static 'js/map.js' %}" type="text/javascript"></script> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAZY5nutUGjjf4D...endOFKEY&callback=initMap"async defer></script> {% endblock %} and sometimes keys get expired. It's really annoying to change the key in every html file I have. Maybe I can make some sort of a global varialbe and store the key there? Any suggestions? -
Serialize DynamicField
I have some model: class Settings(mongoengine.Document): name = mongoengine.StringField() range = mongoengine.DynamicField() And serializer for it: class SettingsSerializer(serializers.DocumentSerializer): class Meta: model = Settings fields = [ 'name', 'range' ] Field 'range' can be a dict or list. But, when I do serialize I got only string to this field: { "name": "hello world", "range": "{'max': 100, 'min': 0}", } How can I get list or dict after serialize? -
Stripe subscription data array index
I am trying to implement a webhook for stripe . Lets say i do event_json = json.loads(request.body) then i get the data i need at event_json['data']['object']['subscriptions']['data'][0]['id'] the thing is i am new to subscription does the array index "0" here change on every subscription? part of the response is shown below { u'object': u'event', u'pending_webhooks': 1, u'created': 1486550453, u'type': u'customer.created', u'livemode': False, u'request': u'req_A52yftxLoyXcW6', u'data': { u'object': { u'subscriptions': { u'has_more': False, u'total_count': 1, u'object': u'list', u'data': [ {... }, 'id':'val',... -
forms or formsets or none of them in django
I have 5 models , and I want to have three form from these models. I should set a form for registering course , in the form should be display the course name , the course unit and the professor name and lastname for each professor should show all courses and the manager user with checkboxs can select course for professor.one idea is using table in template file but I couldn't do it. the other idea is using forms ,formsets in django. using ModelFrom and the other one using Form. because I have the model in database the right way is using modelForm, of course I think! If I want to use modelforms , the operation formmodel should use. but in this form there are foriegnkeys and only user could choose one data. but I want user can choose many options and the result of this form sent to selecting course def! here the student could select course from courses that registered. is there any idea/code for helping me?? here is my code: model: from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType class Course(models.Model): course_name = models.CharField(max_length=30) course_unit = models.IntegerField() def __str__(self): return self.course_name + ' … -
Pass Django variables between view functions
I'm asking a question about variables handling in my Django application view. I have 2 functions : The first one lets me to display query result in an array with GET filter parameter (in my case, user writes year and Django returns all objects according to this year. We will call query_naissance this variable). The second one lets me to create a PDF. I have lots of variables but I want to take one more time query_naissance in my PDF. This is my first function : @login_required def Table_annuelle_BirthCertificate(request) : query_naissance = request.GET.get('q1') ... return render(request, 'annuel.html', context) And my second function looks like : @login_required def Table_Naissance_PDF(request) : data = {"BirthCertificate" : BirthCertificate} template = get_template('Table_raw.html') html = template.render(Context(data)) filename = str('Table annuelle Naissance.pdf') path = '/Users/valentinjungbluth/Desktop/Django/Individus/' + filename file = open(path, "w+b") pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8') file.close() context = { "BirthCertificate":BirthCertificate, "query_naissance":query_naissance, } return render(request, 'Table.html', context) # Template page générée après PDF So How I can add query_naissance given by user in my first function to my second one without write one more time a field ? Then, I have to call this variable like {{ query_naissance }} in my HTML template. Thank you -
Use field label as placeholder with django-widget-tweaks
I am using django-widget-tweaks and spent some time searching through SO posts to figure out how to add a field variable as placeholder: The field label above does not evaluate and puts the string "field.label" as the placeholder on the page. Some SO posts suggest registering a custom tag/filter which seems complicated for something as simple as this. -
Showing relationships inside the model
This is a model for my MCQ app. Is there a way to show relationship inside this particular model that answer belongs to one of the options and there should be only one right option class Question(models.Model): quiz_question=models.CharField(max_length=1000) option1=models.CharField(max_length=500) option2=models.CharField(max_length=500) option3=models.CharField(max_length=500) option4=models.CharField(max_length=500) option5=models.CharField(max_length=500) answer=models.CharField(max_length=500) Thank You.