Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Latest record up to a certain date
Given following model: class MyModel(models.Model): date = models.DateField() date = models.CharField(max_length=16) Containing following records: 1/May/2016: a 20/May/2016: b 3/Nov/2016: c 15/Nov/2016: d I would like to get the latest record up to a certain date, e.g. latest_up_to_date(18/August/2016) should return b. -
How does django work with websocket server and webserver simultaneously?
I think I have some confusion in the understanding of websocket server and webserver. So I followed the tutorial of django channels, where I created a little app that listens on a channel and returns some response. At the same time, I can still serve webpages with normal view functions, so how does django do this magic so that it works without me modifying anything in the nginx server config? -
Django Cookie is not set properly
I am trying to set a cookie in a Django view. Something like this: def my_view(request): response = HttpResponse('Setting a cookie') if 'my_cookie' in request.COOKIES: return HttpResponse('Cookie found.') else: response.set_cookie('my_cookie', 'value') return HttpResponse('Cookie set.') In my mind, how it should work is this: on the first load, the cookie is not found, so its set and 'Cookie set.' is returned. If I reload the page, the cookie should be found, since it has been set already, so 'Cookie found.' is returned. However, every time I reload, I get 'Cookie set.' for some reason. Any help? Thanks. -
Confusing error while deploying Django on Heroku: No module named site
I've got two Heroku apps, running on the same codebase. The 1st is used as staging env and it works as expected (it auto deploys the devel branch) and the 2nd is used as the production app (auto deploying the master branch). Today I did a minor code-level change and submitted a PR from devel to master and merged it. From that moment, heroku cannot deploy my master branch in production. Full logs for this as given by heroku build log: -----> Python app detected -----> Uninstalling stale dependencies Uninstalling django-elasticsearch-0.5: Successfully uninstalled django-elasticsearch-0.5 Uninstalling pymongo-3.3.0: Successfully uninstalled pymongo-3.3.0 $ pip install -r requirements.txt Collecting git+https://github.com/liberation/django_elasticsearch.git (from -r requirements.txt (line 69)) Cloning https://github.com/liberation/django_elasticsearch.git to /tmp/pip-ZPaLWp-build Collecting Delorean==0.6.0 (from -r requirements.txt (line 10)) Downloading Delorean-0.6.0.tar.gz Collecting humanize==0.5.1 (from -r requirements.txt (line 37)) Downloading humanize-0.5.1.tar.gz Collecting pynamodb==2.0.2 (from -r requirements.txt (line 46)) Downloading pynamodb-2.0.2-py2.py3-none-any.whl (73kB) Collecting tzlocal==1.3 (from -r requirements.txt (line 63)) Downloading tzlocal-1.3.tar.gz Installing collected packages: humanize, tzlocal, Delorean, django-traffic, pynamodb, django-elasticsearch Running setup.py install for humanize: started Running setup.py install for humanize: finished with status 'done' Running setup.py install for tzlocal: started Running setup.py install for tzlocal: finished with status 'done' Running setup.py install for Delorean: started Running setup.py install … -
Override field to allow NULL in django model
Django user model works for me, but I want to make username nullable. What is a clean way to do it? -
Exception handling and atomic requests in Django
I've previously a similar question, but I put it incorrectly, that's why need to clarify it in a new post. Consider the following Django settings and a view: settings.py DATABASES = { 'default': { # ... 'ATOMIC_REQUESTS': True, }, view: def my_view(request): foo = Foo.objects.get(id = 1) foo.some_field = 'new value' foo.save() if some_condition(): # ... else: return JsonResponse(json.dumps('Cusom message', ensure_ascii=False), status = 500, safe = False) The problem with this code is that foo object is updated if some_condition is not true, whereas I would expect the transaction to roll back, since I am sending status 500. Could anyone give me a hint on what I am doing wrong here ? -
How to customise user profile fields in allauth after signup
I used allauth to signup function in my web application. In the socialaccount signup is collected from users e-mail, password, first and last name. In the sign in form I just collect e-mail and password from users. Once logged, my app redirects the user to a profile page where is supposed to him/her update her profile (including new and customised fields, as the "institution" I added), if him/she wants to do so. The question as a beginner in django-allauth, I'd like to know how to add these new customised fields to my user profile, and how to update those data once the user signed up. what I did till now: In settings.py AUTH_USER_MODEL = 'auth.User' In my_project/models.py from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): institution = models.TextField(max_length=254) In profile_page.html {% extends 'base.html' %} {% block title %}Profile Page{%endblock title%} {% if user.is_authenticated %} {%block body%} <div class="col-md-6" > <div class="panel panel-default"> <div class="panel-body"> <h1 class="text-center"><b>MY ONTOLOGIES</b></h1><br> </div> </div> </div> <div class="col-md-6" > <div class="panel panel-default"> <div class="panel-body"> <h1 class="text-center"><b>MY PROFILE</b></h1><br> <div class="form-group"> {% csrf_token %} <label for="id_login" class="col-sm-2 control-label">E-mail:</label> <div class="col-sm-10"> <input type="email" id="asd" value="{{user.email}}" name="login" class="form-control" required /> </div><br><br> <label for="first_name" class="col-sm-2 control-label">First Name:</label> <div class="col-sm-10"> … -
Django 1.10 / AttributeError: 'list' object has no attribute '_meta'
I got this error: Internal Server Error: /QOP/1/editar/ Traceback (most recent call last): ... opts = instance._meta AttributeError: 'list' object has no attribute '_meta' [25/Nov/2016 19:17:00] "GET /QOP/1/editar/ HTTP/1.1" 500 77572 models.py from django.db import models from smart_selects.db_fields import ChainedForeignKey from django.core.urlresolvers import reverse from modulos.modPessoas.models import Postos # Quadro Orgânico Pessoal class Qop(models.Model): class Meta: ordering = ['qop_ref'] verbose_name = 'Quadro Orgânico Pessoal' verbose_name_plural = 'Quadro Orgânico Pessoal' qop_ref = models.CharField(max_length=255, null=True, blank=True, verbose_name='Referência') qop_nome = models.CharField(max_length=255, null=True, blank=True, verbose_name='QOP Nome') qop_dt_arov = models.DateField(null=True, blank=True, verbose_name='Data de Aprovação') qop_atv = models.BooleanField(default=True, verbose_name='Ativo?') def __str__(self): return '{} {}'.format(self.qop_ref, self.qop_nome) def get_absulute_url(self): return reverse("QOP:detalhe", kwargs={"pk": self.id}) views.py def qop_editar(request, pk=None): instance = get_list_or_404(Qop, id=pk) form = QopForm(request.POST or None, request.FILES or None, instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.save() contexto = { "titulo": "QOP Editar", "instance": instance, "form": form } return render(request, "modQOP/editar.html", contexto) urls.py from django.conf.urls import url from .views import (index, qop_lista, qop_detalhe, qop_criar, qop_editar) urlpatterns = [ url(r'^$', index), url(r'^criar/$', qop_criar), url(r'^lista/$', qop_lista), url(r'^(?P<pk>\d+)/detalhe/$', qop_detalhe, name='detalhe'), url(r'^(?P<pk>\d+)/editar/$', qop_editar, name='editar'), ] template <form method="post" action="" enctype="multipart/form-data"> {% csrf_token %} Nome: {{ form.qop_nome }}<br> Nº de Referência: {{ form.qop_ref }}<br> Data de Aprovação: {{ form.qop_dt_arov }}<br> Ativo? {{ form.qop_atv }}<br> … -
Is there any admin ajax url in Django like Wordpress?
Basically, I am a Wordpress developer. When i make an ajax request in Wordpress, hook up wp-admin ajax with the request. I am pretty new in Django. Does Django has any helper library for back-end implementation through which it hooks up ajax request. Wordpress uses following code to generate url for $.ajax- admin_url( 'admin-ajax.php' ) If i explain bit further, then it may be - In Wordpress, if i use the URL in AJAX then admin ajax url is loaded which hooks up an action to catch the request. I am wondering is there something already implemented as a helper library for handling admin ajax call in Django This is just my curiosity that Django has something like that? Thanks! -
Django CBV Detailview
Hello Everybody excuse my english.... I am facing a problem with django. I need to restrict object so only their owners can print it. Model.py class Post(models.Model): title = models.CharField(max_length=50, blank=False) prenom = models.CharField(max_length=255, blank=False) user = models.ForeignKey(User, null=False) View.py class detailpost(DetailView): model = Post template_name = 'detail-post.html' context_object_name = 'post' url.py url(r'detail-post/(?P<pk>[-\d]+)$', views.detailpost.as_view(), name='detailpost'), This works properly but the problem is that every users can access to the post of another user (http://localhost:8000/detail-post/1). So my question is how can i do some stuff befor rendering the page and see if the post belongs to the current user if yes we print it else we redirect the user to another page. -
Django related_name naming best practice in case of multiple relations
After a year of Django experience I found out that I am not quite sure that I use Django related_names correctly. Imagine I have three models classA(models.Model): pass classB(models.Model): pass classC(models.Model): modelA = models.ForeignKey(classA) modelB = models.ForeignKey(classB) Fine. Now I am thinking of adding related_name to classC's modelA and modelB, but the frustrating think is that I cannot use the same name for two fields. In other words, this code is apparently wrong classC(models.Model): modelA = models.ForeignKey(classA, related_name = 'classC') # wrong modelB = models.ForeignKey(classB, related_name = 'classC') # wrong On the other hand, coming up with an approach like this: classC(models.Model): modelA = models.ForeignKey(classA, related_name = 'classA') # wrong modelB = models.ForeignKey(classB, related_name = 'classB') # wrong would result in a very misleading (at least for me) code. Consider this: obj = classC.filter(classA = classC_instance) So such naming results in a very disruptive code classA = classC_instance. What is the best practice in terms of naming related_names. And is there something I am missing about ManyToManyFields ? Actually, I have a large project, but I've never used ManyToManyFields, always going for a third table like classC in the example. Is there something I am missing ? -
Django object ownership restrictions
What kind of patterns are there for restricting access to logged-in user's own object instances and ensuring that objects are only related to other objects owned by the same user? Every object has a user field FK to the Django User model. There's two things going on: Models need to ensure they're only related to objects with the same user. Views need to ensure they're only presenting models with the logged in user (and this includes the queryset for related models). For (1) I've done a couple of things in the past: A custom clean() that each model instance's user field matches the user field on each item related via FK/M2M/OTO. An abstract base class model with a generic clean() something like: class UserHaver(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) RELATED_OBJECTS_DIFFERENT_USERS_ERR = 'RELATED_OBJECTS_DIFFERENT_USERS_ERR' def clean(self): super(UserHaver, self).clean() try: check = self.user except User.DoesNotExist: check = False if check: err = ValidationError( 'Cannot have different users for related objects.', code=self.RELATED_OBJECTS_DIFFERENT_USERS_ERR ) for field in self._meta.get_fields(): if field.name == 'user': continue if field.many_to_many: for related_obj in getattr(self, field.name).all(): if not related_obj.user == self.user: raise err elif field.many_to_one and field.related_model: try: related_obj = getattr(self, field.name) except field.related_model.DoesNotExist: continue if not related_obj.user == self.user: raise err elif … -
Retrieve Class of ManyToManyField
Given the following simplified models, I need to return an empty QuerySet of a ManyToManyField, but I receive an "AttributeError: 'ReverseManyRelatedObjectsDescriptor' object has no attribute 'none'" class AnimalFamily(models.Model): objects = GetOrNoneManager() siblings = objects.none() class Countable(models.Model): @classmethod def get_peers(cls_obj,target_animal): animals = cls_obj.objects.get_or_none(siblings=target_animal) if animals: return animals.siblings.exclude(id=target_animal.id) else return cls_obj.siblings.none() # <--- this fails <---- class Meta: abstract = True class BearFamily(AnimalFamily,Countable) siblings = models.ManyToManyField(Bear) class GiraffeFamily(AnimalFamily,Countable) siblings = models.ManyToManyField(Giraffe) How can I get access to the "Bear"-Class or the respective "Giraffe"-Class in the generic classmethod to return an empty query of the correct QuerySet? -
How to supply choices to a formset, if choices come from queryset or other view logic?
How to supply choices to a formset, if choices come from queryset or other view logic? I have formset setup in forms.py as following: class MCQuestionAnswerForm(forms.Form): question = forms.CharField() mcq_answer_choice = forms.ChoiceField(widget=forms.RadioSelect) MCQuestionAnswerFormSet = formset_factory(MCQuestionAnswerForm, extra=0) I need to supply in views.py different set of choices to the formset instance, where choices will be a result of a queryset or other view logic. Can I use for that matter form_kwargs? If so, how can I do that? -
How to filter data in Django admin without returning a queryset?
I need to filter data using python and then return the result (a list of filtered objects) to the admin page like this. class MyFilter(admin.SimpleListFilter): def queryset(self, request, queryset): if self.value() == 'delayed_orders': filtered_objects = filter(queryset) return filtered_objects Is this possible using the admin.SimpleListFilter or we always need to return a queryset ? -
Passing initial data from django to angular 2
I'm working on my first angular 2 app in an existing Django/Angular1 setup. We used to pass initial data in a django template to be consumed by angular in a tag like so: <script type="text/javascript"> var id = '{{ id }}'; </script> Then the angular app could utilize it by: $scope.id = id; How can I accomplish this same functionality with Angular2? -
Django context processors and URL arguments
I have some code that is repeated at the start of my Django views. It basically just adds some variables to the context, but based on the URL argument, e.g. def someView(request, id): target = Target.objects.get(id=id) # name will be added to ctx name = target.name (there are more attributes added and other attributes from related models, but this gives the general idea --- There are quite a few lines of repeat code at the start of each view) I thought I could make my code more DRY by taking advantage of Django's context processors, but it would seem these don't access to the URL arguments? Is there another way to avoid these repeat lines? Maybe middleware or something else? -
No module named 'psycopg2
I Installed psycopg2 using pip C:\Users\username>python -m pip install psycopg2 Adjusted my settings to: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # also tried: django.db.backends.postgresql 'NAME': 'name', 'USER': 'user', 'PASSWORD': 'my_password', 'HOST': 'localhost', 'PORT': '5432', } } When I attempt to run the server: import psycopg2 as Database ImportError: No module named 'psycopg2' So I ran this again and got: python -m pip install psycopg2 Requirement already satisfied (use --upgrade to upgrade): psycopg2 in ... So what have I done wrong? I am new to Django -
Django Streaming sent events response
I want to push data from server to client if it is ready. So here is my JS: var eventSource = new EventSource("/project/api/v1/listener/"); eventSource.addEventListener('message', function(e) { console.log('Here is the message: ' + e.data); }, false) eventSource.addEventListener('open', function(e) { console.log('Connection was opened') }, false) views.py in Django: class handler(): data = {} def listener(request): return StreamingHttpResponse('data:' + handler.data, content_type="text/event-stream") urls.py: urlpatterns = [ url(r'^api/v1/listener/$', views.listener), ] I want to push data to handler.data and recieve it with JS. The above mentioned code is not working and returns: "GET /project/api/v1/listener/ HTTP/1.0" 500 If I try: return StreamingHttpResponse('data: just a string', content_type="text/event-stream") I recieve lots of 'Connection was opened' messages in console. Can you support me with the easiest solution, how can I pass data from Django to my client with SSE? -
Restrict User to Views their own calendar in django-schedule?
I am making an appointment system using django-schedule. The documentation is not very good for this package and I am not able to get my head around restricting the user to views only their own calendars. Please suggest some other package that I can use for implementing this functionality which has a better documentation. -
Django Rebuild all migrations
I am building an app in Django and it uses a live/in-use database. Basically since the apps development the SQL Database has undergone some structure changes and it is causing issues with Django, Django will try to apply migrations to the database that already exist. For example: In the Django app I marked the email column as unique which was fine based on the development database. However the main database now always has a table change that marks the email column as unique. Django is fighting this unique key with the one that already exists. So is it possible to clear all Django migrations and have it make migrations again compared to the more up to date SQL database structure? -
Call variables in two different functions
I'm asking How I can call a variable with Python 2.7 and Django 1.10 which is defined in the function1 into the function2. I defined a function1 like that : def Test(request) : form = TestForm(request.POST or None) if form.is_valid() : instance = form.save(commit=False) return HttpResponseRedirect('toto') context = { "form" : form, } return render(request, 'form_Test.html', context) And I would like to call the variable instance inside my function2 : def Test2(request) : identity = instance.lastname context = { "identity" : identity, } return render(request, 'test2_identity.html',context) I would like to know How it's possible to do this handle ? -
Cannot customise django-ckeditor toolbar
I'm trying to customise a django-ckeditor toolbar. My model field is: answer = RichTextField( verbose_name = "Answer presented to user", config_name = 'answer_ckeditor', ) Within settings.py I have CKEDITOR_CONFIGS = { 'answer_ckeditor': { 'skin': 'moono', #'skin': 'office2013', 'toolbar': [ {'name': 'basicstyles', 'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']}, {'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language']}, {'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']}, {'name': 'colors', 'items': ['TextColor', 'BGColor']}, ], } } My HTML is: <textarea id="answer_1" name="answer_1" required class="form-control quiz-search-box" placeholder="Option 1"></textarea> <script> CKEDITOR.replace( 'answer_1' ); </script> I just get the standard ckeditor menu. I've tried using default and removing the config_name from the field definition but no difference. Is there something different I need to do in the JavaScript CKEDITOR.replace( 'answer_1' ); to get it to pick up my toolbar? -
Cannot properly modify list of dictioaries
I am trying to supply initial (es_initial) data to my formset, where initial is a list of dictionaries. My view.py have following code: # get all answers by current student es_answers_by_student = models.Answer.objects.filter( student__user=request.user ).filter( question__quiz=step ).filter( eq_answer_text__icontains='' ) # supply question prompt to the initial data for es_question in eqs: es_dict_for_initial.update({'question': es_question.prompt},) es_initial.append(es_dict_for_initial.copy()) # supply saved answers for answer in es_answers_by_student: for _dict in es_initial: _dict["eq_answer"] = answer.eq_answer_text print(es_initial) Cannot understand, why my last for loop always returns same value which is the last value in es_answers_by_student queryset -
Django-Rest-Framework: Paginate nested object
I have two models: class Book(models.Model): title = models.CharField(max_length=250) author = models.CharField(max_length=250) class WordInBook(models.Model): book = models.ForeignKey("Book") word = models.ForeignKey("Word") And corresponding serializers: class BookSerializer(ModelSerializer): wordinbook_set = WordInBookSerializer(many=True) class Meta: model = Book fields = ('id', 'title', 'author', 'wordinbook_set') class WordInBookSerializer(ModelSerializer): class Meta: model = WordInBook fields = ('word') Now I want to paginate the wordinbook_set. Outside of serialiser it is easy: book = Book.objects.get(pk=book_id) paginator = Paginator(book.wordinbook_set.all(), 10) words = paginator.page(page).object_list But that leaves me with two separate serialised objects. Question: how do I paginate wordinbook_set inside the serialiser, so that the resulting json looks like this: {id: '...', title: '...', author: '...', wordinbook_set: [ 10 WordInBook objects here ]}