Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
App Engine Flexible: Timed out waiting for the app infrastructure to become healthy
I'm trying several times to deploy a new version of a service on my app engine flexible instance using the sdk and the command "gcloud app deploy", but all i get is this error "ERROR: (gcloud.app.deploy) Error Response: [4] Timed out waiting for the app infrastructure to become healthy.". I Couldn't found any answer about it on the issue tracker of gcp. On this question, he got the same problem, but no one could answered it. Any guidance will be very helpfull. -
how to get value of a model instance at specified time in Django?
I have a point awarding method in my website and I want to create a "top users in last 10 days" list. right now I store and update user scores in Profile model which is: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) points = models.IntegerField(default=0) but I want to get the value of this "point" instance at for example 10 days ago for comparing it to latest value. how can I achieve this? -
Ordering Filter using 2 ordering values(django_filters)
Hello every one is there a way to use OrderingFilter like in django order_by with 2 ordering values queryset.ordery_by('value1', value_2') I have tried order_by = django_filters.OrderingFilter( fields=( ('item_name', 'Items), ('time_from', 'Time'), (('value1', 'value2'), 'Value'), ) ) But received expected string or bytes-like object -
Django permissions analysis
Is anyone aware of a programmatic way of analysing a codebase to see which permissions each view is protected by? I'd like to be able to run a regular report on a site to inform us which views are available and who can see them etc. rather than having to maintain a list by hand. I'm aware of the show_urls command from django-extensions but that doesn't help with the permissions side of things. -
django date filter doesn't update
I made a listview in a django project. But when day go away, filter stay on starting data (start or refresh of web-server). Why it doesn't update every day? this is my code: (table booking for restaurant) models.py: class Table_book(models.Model): name = models.CharField(max_length=50) date = models.DateField() time = models.CharField(max_length=50, choices=TIMES) people = models.PositiveIntegerField(choices=TABLES) telephone = models.CharField(max_length=50) views.py class List_book(ListView): model = Table_book template_name = 'list_today.html' queryset = Table_book.objects.all().filter(date=timezone.now()).order_by('date', 'time') urls.py url(r'^$', login_required(List_book.as_view(), login_url='/login/'), name='home'), in template.html the list objects populate a table. -
django - How to make a custom is_authenticated to verify if a user is connected?
I have a custom user model using AbstractBaseUser, called Users, so I also have a custom authentication backend: https://pastebin.com/waky5AW3 My issue is that I don't know how to check if a user is connected while using this custom user model, because users.is_authenticated will always return true as logged in and user.is_authenticated will always return false and I mean not logged in, ONLY if the user is logging into the CONTROL PANEL, THEN, user.is_authenticated will return TRUE and which means that the user is LOGGED in. This is how I log in the user once form is submitted: email = form.cleaned_data['email_field'] password = form.cleaned_data['password'] temp = OwnAuthBackend() user = temp.authenticate(email=email, password=password) if user is not None: messages.success(request, 'You logged in successfully!') return redirect('index', users = user) The if is not None returns true and the user is redirected to the index with variable users = user and with that success message, and I know it is not a good way because if user comes from another redirect, still logged in but without the variable 'users', it should give him an error. The thing is, How to check if user is authenticated using a custom user model... -
serving media files with dj-static in heroku
I'm trying to serve media files that are registered in django-admin. When accessing an image by api error 404 Not found. I made a configuration as the recommended documentation, but in heroku does not work. settings.py import os from decouple import config, Csv from dj_database_url import parse as dburl BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', default=False, cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS', default=[], cast=Csv()) default_dburl = 'sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3') DATABASES = { 'default': config('DATABASE_URL', default=default_dburl, cast=dburl), } (...) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') wsgi.py import os from dj_static import Cling, MediaCling from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "integrafundaj.settings") application = Cling(MediaCling(get_wsgi_application())) requirements.txt dj-database-url==0.4.2 dj-static==0.0.6 Django==1.11.3 djangorestframework==3.7.7 easy-thumbnails==2.4.2 olefile==0.44 Pillow==4.3.0 python-decouple==3.1 pytz==2017.3 static3==0.7.0 Unidecode==0.4.21 gunicorn==19.4.1 psycopg2==2.7.1 -
is that important to clean data when use self.kwargs.get()?
is that important to clean data when use self.kwargs.get()? for example when we get pk from url in view classes by self.kwargs.get(pk). if answer is yes, how can I clean data? -
Django rest password throws 500 error
I have implemented the Reset password by using django ResetPassword. But It throws the 500 error. I don't know how to find the flow & fix it. 1.I have created the urls.py from __future__ import unicode_literals from django.conf.urls.static import static from django.conf import settings from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import include, path from . import views app_patterns = [ path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('signup/', views.Signup.as_view(), name='signup'), path( 'password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset' ),][enter image description here][1] Also I have created the HTML files (Refer Screenshot) password_reset_form password_reset_done password_reset_confirm password_reset_complete I don't know what I'm missing here. Can anybody help me out? Thanks in advance. -
does not appear to have any patterns in it error
I got an error, Traceback (most recent call last): File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/checks/urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/checks/urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/urls/resolvers.py", line 545, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'django.urls' from '/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/urls/__init__.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. I recently updated Django 1.8 into 2.0,so I think the error happens.I think the way of urls.py causes this error, so I rewrote like from django.urls import include, path app_name = 'App' urlpatterns = [ path('admin/', admin.site.urls), path('app/', include('app.urls')), ] +static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) but same error happens.I really cannot understand why this error happens.How should I fix this?What is wrong in my code? -
I think I'm installing Django, but it doesn't seem to be there
Mysterious. I may not understand virtualenv sufficiently to use it. I created what I thought was a virtual environment: pip3 -m venv myenv pip3 install --ignore-installed django~=2.0.0 Collecting django~=2.0.0 Using cached Django-2.0.1-py3-none-any.whl Collecting pytz (from django~=2.0.0) Using cached pytz-2017.3-py2.py3-none-any.whl Installing collected packages: pytz, django Successfully installed django-2.0.1 pytz-2017.3 001b639f6f87:myenv admin$ ls bin include lib pyvenv.cfg So, where is Django? Actually, this may not be a virtualenv question. Run the same command in a non-venv directory with the same result: no Django. So, I think, maybe there is an issue with Django 2.0 of which I am unaware. Let's try 1.11: 001b639f6f87:django-test admin$ pip3 install --ignore-installed django~=1.11.0 Collecting django~=1.11.0 Downloading Django-1.11.9-py2.py3-none-any.whl (6.9MB) 100% |&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;& #9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&# 9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;| 7.0MB 108kB/s Collecting pytz (from django~=1.11.0) Using cached pytz-2017.3-py2.py3-none-any.whl Installing collected packages: pytz, django Successfully installed django-2.0.1 pytz-2017.3 001b639f6f87:django-test admin$ ls 001b639f6f87:django-test admin$ ls -l 001b639f6f87:django-test admin$ Obviously, unclear on something, but not sure where the problem lies. -
djangocms integration filer_image with apphook objects
I want to add filer_image field to my Gift class instance object. It works as apphook in django-cms. The main problem is that after making migrations and open the view where the form is i don't have loaded js. I already added all tags: {% load staticfiles i18n cms_tags sekizai_tags menu_tags thumbnail filer_tags filer_image_tags %} The model is: class Gift(models.Model): filer_image = FilerImageField(related_name="book_covers") The form: class GiftForm(ModelForm): class Meta: model = Gift fields = '__all__' widgets = { 'name': forms.TextInput(attrs={'class': 'basic-input full-width'}), } The rendered output: Please tell me what am I doing wrong with these. It seems to me like some js files are not loaded. After click it opens FileImageFiler gallery, but I also cannot select any image. -
Restructuring json response from Django REST Framework
My current response which lists all fields in my serialiser is as follows: GET /conversations/<id>/messages returns: { "count": 2, "next": null, "previous": null, "results": [ { "task_id": 21, "conversation_id": 1, "sender": 2, "body": "Hello There" }, { "task_id": 21, "conversation_id": 1, "sender": 2, "body": "Can you do the task" } ] } Instead, since conversation_id , task_id and user_id are repeated, I would like to take them outside the main response. I want to return: { "count": 2, "next": null, "previous": null, "task_id": 21, "conversation_id": 1, "user_id": 1, "results": [ { "sender": 2, "body": "Hello There" }, { "sender": 2, "body": "Second Message" }, ] } serializers.py class MessageSerializer(serializers.ModelSerializer): sender = serializers.ReadOnlyField(source='sender.id') task_id = serializers.SerializerMethodField() conversation_id = serializers.SerializerMethodField() def get_task_id(self, obj): task = Task.objects.filter(task_worker__conversation__message=obj)[0] return task.id def get_conversation_id(self, obj): conversation = Conversation.objects.filter(message=obj)[0] return conversation.id class Meta: model = Message fields = ['task_id','conversation_id','sender','body'] -
How to set interrelated Django model Fields
I have the following simplified problem. Say that I have two Django models, namely a (P)roject and (H)ourly which stores hourly values for the project. Now lets assume that there is a simple relation between these entities, e.g.: H.y = 2*H.x + P.par. Is there an elegant way to implement this? Where to put the help function: def calc_y(x, par): return 2*x+par class P(models.Model): par = FloatField() class H(models.Model): p = models.ForeignKey(P, on_delete.CASCADE) x = FloatField() y = FloatField() -
Sending audio AND text using django to android app
So I have an android app that uses MediaPlayer to load audio from a Django view/URL (by setting the content type to audio/mpeg). However, now I need to get both audio and a json from the view. Is there any way I can achieve this? I tried using multipart but turns out that wasn't the way to go. -
Django rest api expected string or buffer on PATCH
I'm making a Django application, where I am sending requests through rest API. I am using POST and GET and all works pretty well, but when I am trying to use PATCH (as I must firstly upload field "start_time", and then add field "time"), I'm getting following error: match = time_re.match(value) TypeError: expected string or buffer Surely it is about views.py, but I cannot find clear recipe how to do that, thus I don't know where I am wrong. Thank you. Views.py ... elif request.method = 'PATCH': serializer = TABLESerializer(data=request.data, partial=True) if serializer.is_valid(): obj = TABLE.objects.get(start_time=request.data['start_time']) obj.time = serializer['time'] obj.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializers.py class TABLESerilizer(serializers.serializer): start_time = serializers.DateTimeField(format = None, allow_null=True) time = serializers.TimeField(format=None, required=False) models.py class TABLE(models.Model): start_time=models.DateTimeField(primary_key=True) time = models.TimeField(null= True, blank= True, default = '00:00:00') -
Debug Django app on Heroku
How can I debug django app deployed on Heroku. I can not reproduce the issue on local setup and want to drop to pdb in handling request code. Is there a way to connect to the web dyno and step thru the code handling request. Please suggest if there is any alternate way was well. Thanks!! -
'User' object has no attribute 'is_valid'
def register(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] email = request.POST['email'] user = User(email=email, username=username, password=password) if user.is_valid: user.save() context = {'message_good': "god" } else: context = {'message_bad': "bad." } else: context = {'message_bad': "bad" } return render(request, 'register.html', context) please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help please help -
Django admin add model page. Display objects with only foreign key
I have a Django admin page that displays a list of my model, Event, and allows me add an Event. My Event model has a field with a one to many relationship with a field from another model, Church. My problem is that when I go to add an Event, it allows me to add any church I want. Instead I would like to only return churches filtered by id. This is what I have so far: class EventAdmin(admin.ModelAdmin): exclude = () list_display = ('title', 'start_time', 'end_time') def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "church": kwargs["queryset"] = models.Event.objects.filter(church__parish=request.user.userprofile.associated_parish) return super(EventAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) request.user.userprofile.associated_parish is the id I'm searching on. This returns me an empty list of churches so I am affecting the field, but I'm not sure where it's failing. -
Django - multiple static file directories javascript not loading
I have a Django project consisting of 3 apps - Survey, Django-admin and Chartsjs (installed through nodejs). The directory structure is: Project survey/ (urls, admin...) views/ analytics_view.py models/ static/ templates/ survey analytics.html ...etc/ Bootstrap_admin/ static/ admin/ css/ boostrap_admin img/ js/ templates/ ...etc node_modules chart.js/ dist/ Chart.js chartjs-color/ ....etc/ When I built Boostrap-Admin, I was left with the following in my settings.py file: MEDIA_URL = '/media/' STATIC_URL = '/bootstrap_admin/static/' MEDIA_ROOT = os.path.join(ROOT, 'media') STATIC_ROOT = os.path.join(ROOT, 'static') STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) STATICFILES_DIRS = [ os.path.normpath(os.path.join(ROOT, '..', "survey", "static")), In analytics_view.py I have a class: class AnalyticsView(TemplateView): template_name = "survey/analytics.html" And in analytics.html I have the code example provided by chartsjs: {% block extrahead %} <script src="../../../node_modules/chart.js/dist/Chart.js" type="text/javascript"></script> <script> var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, … -
How to fix problems with querystring in show_more tag?
I use pagination on scroll of django-el-pagination application in my own project. django==django==1.11.5 django-el-pagination==3.1.0 When user scroll to the last page in terminal I notice next Traceback. It seems to me that something wrong with querystring which in show_more tag. Do you have any ideas how to fix it?! P.S. As I said this Traceback happens only when user scroll to the last page. Lets say I have 5 page, so this Traceback happens only when user at last page: http://127.0.0.1:8000/documents/?page=5&querystring_key=page ERROR: Time: [25/Jan/2018 08:37:38] | LevelName: DEBUG | Module: base | Process: 1148 | Thread: 123145435922432 | Message: Exception while resolving variable 'querystring' in template 'documents/documents.html'. Traceback (most recent call last): File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/template/base.py", line 903, in _resolve_lookup (bit, current)) # missing attribute VariableDoesNotExist: Failed lookup for key [querystring] in u"[{'False': False, 'None': None, 'True': True}, {'csrf_token': <SimpleLazyObject: <function _get_val at 0x109034ed8>>}] views.py: from el_pagination.views import AjaxListView class DocumentListView(AjaxListView): context_object_name = 'documents' template_name = "documents/main.html" page_template = 'documents/documents.html' def get_queryset(self): documents = Document.objects.all() return documents documents/main.html: <div class="list-group"> {% include page_template %} </div> documents/documents.html: {% load el_pagination_tags %} {% paginate 20 documents %} {% for document in documents %} {% include "documents/list_template.html" %} {% endfor %} {% show_more %} documents/list_template.html: … -
Djanog Override Default ModelForm Input Wrapper
There are many questions and answers out there for override the widgets and other field properties on a Django Form. My answer is slightly different from what I have been able to find by searching. Inside my form template, I load the form UI elements like this: <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <a class="button icon fa-cancel" href="{% url 'advertising:my-ads' %}">Cancel</a> <button type="submit" class="button icon fa-save">Save</button> </form> All form elements are rendered wrapped in a <p> element. Like this: <p><label for="id_title">Title:</label> <input id="id_title" maxlength="100" name="title" type="text" value="Flamingo T-Shirt Corporation"></p> So my question is: how to change that <p> element to something else? For example i'd like to change it to <div class='some-class'>. Instead of just hard-coding my own HTML template, I would rather override some aspect of the form class. Here is my current form class defnintion: class AdForm(forms.ModelForm): class Meta: model = Ad fields = "__all__" exclude = ['created','modified'] I'm been reading through the docs and still haven't quite found what I am looking for. Any help is greatly appreciated. -
can not remove field from serializer with .pop('field') in create() method - DRF
I'm using Django rest framework. I want to create admin endpoint where the user can add the member with project permission. following is the data coming from the user. { "email" : "name@yopmail.com", "first_name" : "asd", "last_name" : "asd", "projects":[{ "project_id" : 1, "project_role" : 1 }, { "project_id" : 1, "project_role" : 1 }], "position" : "something something" } following is serializer I created to validate and save the data. class ProjectPermissionSerializer(serializers.Serializer): """ Serialiser to hold permissions pair of project_id and role """ project_id = serializers.IntegerField(allow_null=False) project_role = serializers.ChoiceField(PROJECT_ROLES) def create(self, validated_data): print(validated_data) def update(self, instance, validated_data): pass class ProjectMemberSerializer(serializers.ModelSerializer): """ serializer to add new member with projects """ projects = ProjectPermissionSerializer(many=True) email = serializers.EmailField() class Meta: model = User fields = ('first_name', 'last_name', 'email', 'position', 'projects') def create(self, validated_data): permission_data = validated_data.pop('projects') emailstatus = {"email_id": validated_data.pop('email')} emailobj, created = EmailStatus.objects.get_or_create(**emailstatus) validated_data['email'] = emailobj project_member = User.objects.create(**validated_data) return project_member still, after popping the projects from validated_data, I'm getting following error. AttributeError: Got AttributeError when attempting to get a value for field `projects` on serializer `ProjectMemberSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object … -
Django test - models.DoesNotExist: matching query does not exist
I have two test files, test1.py and test2.py. Individually they run fine, but when I try to run them using 'django manage.py test' I get the following error: post.models.DoesNotExist: Post matching query does not exist. One more thing I notice is that, whichever file runs first will work well while the other throws this error (tested this by renaming files). I am using django.test.TestCase. This is the relevant code - test1.py: def setUpTestData(cls): Post.objects.create(...) Post.objects.get(id=1) #Works fine since this file runs first test2.py: def setUpTestData(cls): Post.objects.create(...) Post.objects.get(id=1) #Throws above error I am new to testing in django so I think I'm missing something basic here. -
How to close a site for django?
I want to restrict access to a django site, how to restrict it to an IP adress or make it to open by login and password should I use htaccess or code it inside django itself?