Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django creating a "sentinel" user on delete
I do want to keep some info about removed users (like username) to show in forum posts. How can I achieve that? So far I have this: class Post(models.Model): (...) creator = models.ForeignKey(User, blank=True, null=True,on_delete=models.SET(get_sentinel_user)) @receiver(pre_delete, sender=User, dispatch_uid='user_delete_signal') def create_sentinel_user(sender, instance, using, **kwargs): SentinelUsers.objects.get_or_create( \ username=instance.username+" (left)")[0] def get_sentinel_user(): return SentinelUser.objects.latest('id') However if I use that in Admin, it doesn't work because for some reason get_sentinel_user is run sooner than pre_delete and therefor the sentinel user doesn't exist yet. -
Creating multiple select checkboxes with Django
I'm getting a little problem with multiple checkboxes according to Django models & forms. I'm creating a template which let to select a theme which will apply on my project. I already scripted a list of theme with identicals css files but with different background-colors. Objective : Users check the box, Django picks up the variable and the css path is modified according to this variable. Then one of theme is applied. I created a models.py file : #-*- coding: utf-8 -*- from django.db import models from django.utils.encoding import force_text # 2 themes : Datasystems & Cameroun FAVORITE_THEME = ( ('Datasystems', 'Datasystems'), ('Cameroun', 'Cameroun'), ) class Theme(models.Model): favorite_theme = models.CharField(max_length=20, choices=FAVORITE_THEME) Then my forms.py file : #-*- coding: utf-8 -*- from django import forms from .models import Theme class ThemeForm(forms.ModelForm): favorite_theme = forms.MultipleChoiceField( label = "Choisissez le thème à appliquer", widget=forms.CheckboxSelectMultiple, ) class Meta: model = Theme fields = '__all__' The views.py file is very simple : #-*- coding: utf-8 -*- import os from django.shortcuts import render, reverse from django.http import HttpResponseRedirect, HttpResponse from .forms import ThemeForm from .models import Theme def Theme(request) : if request.method == 'POST': form = ThemeForm(request.POST or None) if 'save' in request.POST : post = … -
ValueError while migration in django
I have created 2 app in django named "user_profile" and "corrector". At first, I had a model in user_profile Writing which one of its fields had foreign key to a model in corrector Corrector. the migration was like: migrations.CreateModel( name='Writing', fields=[ ... ('corrector', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='corrector.Corrector')), ], ), After a while, I removed this field: operations = [ migrations.RemoveField( model_name='writing', name='corrector', ), ] A long time after that, I cleared the Corrector model in corrector app. Now, I made some modifications in my model, and when I want to migrate it after makemigrations it raises an error that: ValueError: Unhandled pending operations for models: corrector.corrector (referred to by fields: user_profile.Writing.corrector) How can I get rid of this error? Thanks -
Django DateTime field received a naive datetime
I've seen this question asked a few times and I have followed the answers suggested, however im still getting the error: /usr/lib64/python2.7/site-packages/django/db/models/fields/__init__.py:1430: RuntimeWarning: DateTimeField CircuitMaintenance.end_time received a naive datetime (2017-02-24 23:59:59) while time zone support is active. RuntimeWarning) From what ive read using django utils timezone instead of datetime.now() should of solved the issue, but it has not. I have also got the following settings in my settings.py LANGUAGE_CODE = 'en-gb' TIME_ZONE = 'Europe/London' USE_I18N = True USE_L10N = True USE_TZ = True code from django.utils import timezone dt_now = timezone.now() days_away = datetime(dt_now.year, dt_now.month, dt_now.day) + timedelta(days) days_away_end = days_away + timedelta(hours=23,minutes=59,seconds=59) maintenance = CircuitMaintenance.objects.filter(start_time__gte=days_away, end_time__lte=days_away_end,circuit__site_data__site_type="Major Site") -
Django: Object level permissions DRY
Object level permissions Example from http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/#object-level-permissions class IsOwnerOrReadOnly(permissions.BasePermission): """ Custom permission to only allow owners of an object to edit it. """ def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: return True # Write permissions are only allowed to the owner of the snippet. return obj.owner == request.user My need: Queryset of all objects a user can edit I want to have a django-orm queryset which contains all objects which a given user can edit. I guess I could solve this by creating a complex django-orm filter (with OR and distinct) Not DRY But that's not DRY. That's not DRY because I need to code the stuff twice. One time in has_object_permission() and one time in the django-orm filter. Question How to solve my need (queryset of all objects a user can edit) without duplication the permission checking? -
How to calculate the dfference between two variables in Django?
I'm creating an aircraft comparison site. Say for example we have this table: Aircraft | A350 | 777-330 | |-----------------| Range| 8,943 | 7,354 | ------------------- What I essential want to do is calculate the difference, but the user may select B777 first which has a lower range than the A350, resulting in a negative number (-1589). I want to write a function where the computer realises that the bigger number should come first and calculate the difference, but where will this piece of code go - in the view or jquery? -
How to re-run a view based off information on the current page
I'm using the django web framework to create a calendar webpage. I have a couple of buttons on the page a 'Next' and 'Previous' button that I want to change the values of some things on a view. The change in values is dependant on what is currently on the page, so I have used ajax to get some information from the page and send it to the view. Here's the view: def holiday(request): if request.is_ajax(): # find out if next or previous has been clicked request_type = request.GET['type'] if request_type == "next": response_data = {} # calculate new month and year based off current month and year from view year = a_new_year month = a_new_month if request_type == "previous": #same again else: # page loaded for first time use current date date_today = datetime.now() year = date_today.year month = date_today.month my_holidays = Holiday.objects.order_by('start_date').filter( Q(start_date__year=year, start_date__month=month) | Q(end_date__year=year, end_date__month=month) ) cal = HolidayCalendar(my_holidays, request.user).formatmonth(year, month) context = { "calendar": mark_safe(cal), } return render(request, "tande/calendar.html", context) So basically, when I run the ajax I want to change what year and month are set as, and then run the view as normal and re-render the page. But at the moment it's not … -
Django: Saving multiple models from ChoiceFiled
In the Django ModelAdmin Change page I have one InlineModelAdmin (TabularInline) to edit models on the same page as a parent model. There is a ChoiceField in the table for selecting one model in each row. Each model is identified by unique string in this field (e.g. primary key). There are a lot of items in the ChoiceField (more than thousand) and I want to add many of them at the same time and I don't want to do this manualy for each item. So I defined groups containing preselected items and displayed them in the ChoiceField at the end of list. Now, I want to save all items from group which I choose in ChoiceField at the end of list and also keep possibility to save one of them. Is there way, how can I do this? -
Connect mongodb as primary database for django
I'm new to Django and i need to know how to connect mongodb as primary database.i'm using python3.6,please guide me to connect the database -
Video thumbnails on the fly
I am programming a small video site with Django. Video player is the native HTML5 one. I am managing a video playlist aside of it that modify on the fly the src attribute of the tag with the onclick javascript method. I works perfectly so far even if this is DIY code without any "security" consideration (don't really know if it is worth btw). I would like to add some thumbnail picture close to my video title. I don't know what is the best choice but initially I would prefer those thumbnails to be generated on the fly while page is loaded. Is it possible to do this or too much ressources/response time would be demanded on the server side? I precise that for the moment, videos are copied in a static folder of my server, I don't want to upload them via a form on the website. And if possible I would like to avoid a cron task running and generating thumbnail every XXXminutes. What are your ideas? Thanks, best regards -
django_markdown editor is not showing up in Django 1.10?
I am using Django 1.10 with python 3.4. Here are the settings as recommended by django_markdown github page settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_markdown', 'blog', ] urls.py urlpatterns = [ url(r'^blog/', include('blog.urls')), url(r'^admin/', admin.site.urls), url('^markdown/', include( 'django_markdown.urls')), ] models.py from django_markdown.models import MarkdownField class Post(models.Model): title = models.CharField(max_length=50) #.. content = MarkdownField() Inside the admin text editor looks like this: -
Is it possible to forge HttpRequest attributes for a Django server
I am writing a web app using Django. I am trying to allow a user to see its profile and only his own. if(not request.user.id == request.GET.get('user_id', '')): raise PermissionDenied My question is: is it safe to check this way or is it possible for a smart kid to somehow alter the value in request.user.id to match the user_id of anyone? The user must be logged in before accessing this page using this: user = LDAPBackend().authenticate(username=username, password=password) if(user is not None): login(request, user) -
Django download not working with browser, but works fine in machines where Internet Download Manager(IDM) is installed
My django project uses the following code to download the file. It works all good if the client machine has IDM installed but fails to work if IDM is not installed. I couldn't find any reason for this weirdness. views.py def download(request): if not request.user.is_authenticated(): return render(request, 'login/login/login.html') else: filename = request.POST.get('pdf_file_location') if request.method == 'POST': while os.path.exists(filename) is False: time.sleep(2) chunk_size = 8192 response = StreamingHttpResponse(FileWrapper(open(filename, 'rb'), chunk_size), content_type=mimetypes.guess_type(filename)[0]) response['Content-Length'] = os.path.getsize(filename) response['Content-Disposition'] = "attachment; filename=%s" % filename[filename.find("UserSessionDetails-")+19:] return response return render(request, 'something/something/index.html') download.html <canvas id="c-timer" width="300" height="300"> <input id="pdf_file_location" type="hidden" value={{ pdf_file_location }} name="pdf_file_location"/> </canvas> js for the download.html var val = document.getElementById('pdf_file_location').value data ={"pdf_file_location": val}; something something and then finishTime is called var finishTime = function () { $.post( "/book_publish/download/",data); }; -
How to show push notification to admin user based on the actions of another user in Django?
I am trying to generate a web push notification for an admin user based on the actions of a group of specific users. So basically a user tries to generate a report by clicking a button but it asks for a code. On the background it sends an email or a message to the admin with a specific six digit code. He then calls up the user who wants the report and tells him the code. The user submits the code in the form in front of him and can now access the report. However, the admin user wants to see the code in the notification box that should pop up on the corner of the screen. How can I achieve this? Do I need to learn Django Channels for this? -
Cannot able to display data from database in Django 1.10?
I am new to django and i cannot able to display data from postgres database, i have following data in my database, Data in products Table 1 "test" "images.jpg" 1 3 "sample" "images.jpg" 2 and my code is , views.py from django.shortcuts import render from products.forms import productsform from django.http import HttpResponseRedirect from django.http import HttpResponse from products.models import products def productsview(request): if request.method == 'POST': form = productsform(request.POST) if form.is_valid: name = request.POST.get('name') image = request.POST.get('image') code = request.POST.get('code') products_obj = products(name=name,image=image,code=code) products_obj.save() return HttpResponse("Register Successfull") else: form = productsform() return render(request,'products/products_view.html',{'form':form,}) def display(request): query_results = products.objects.all() return render(request, 'products/myview.html') urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.productsview, name='products'), url(r'^myview', views.myview, name='myview'), ] models.py from __future__ import unicode_literals from django.db import models class products(models.Model): name = models.CharField(max_length=15,unique=True) image = models.ImageField(upload_to = 'pictures') code = models.IntegerField() myview.html <table> <tr> <th>Field 1</th> <th>Field N</th> </tr> {% for item in query_results %} <tr> <td>{{ item.name }}</td> <td>{{ item.code }}</td> </tr> {% endfor %} </table> -
getting 302 error code in Django?
I'm using the Django friendship app. Tweaked the view a little to suit my app. views.py: @api_view(['POST']) @login_required def friendship_add_friend(request, to_username): """ Create a FriendshipRequest """ ctx = {'to_username': to_username} if request.method == 'POST': print('HELLO!!!') to_user = user_model.objects.get(username=to_username) from_user = request.user try: Friend.objects.add_friend(from_user, to_user) except AlreadyExistsError as e: ctx['errors'] = ["%s" % e] return Response(status=status.HTTP_200_OK) friendship/urls.py: url( regex=r'^friend/add/(?P<to_username>[\w-]+)/$', view=friendship_add_friend, ), the root urls in projectname/urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('regis.urls')), url(r'^', include('home.urls')), url(r'^', include('UserProfile.urls')), url(r'', include('friendship.urls')), ] In iOS swift, here's my url: let url = "http://127.0.0.1:8000/friend/add/" + toUsername + "/" Using alamofire: request(url, method: .post, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate() .responseJSON(queue: nil, options: .mutableLeaves) { (response) in success = response.result.isSuccess ? true : false # variable already declared above the completion block. } completion(success) } Where am I going wrong with this? The user is clearly logged in. -
Is it a good idea to log all sql queries in django production?
I am thinking of logging all the sql queries made to our postgresql database for every request by using a middleware like Snippet 1 or Snippet 2 Will it affect the performance of application ? Postgres normal logging doesn't work for me, because along with the sql query I also have to store some additional information. I tried logging all the sql queries by using database logging, but sadly that doesn't seem to work when DEBUG=False in settings file. -
Heroku not found static files Django
I know there are similar questions, but believe me I've gone through every each of them, but still not getting my static files going through. Any help is greatly appreciated. I have all my setting and other codes below. The capture below shows when I run $ heroku run python manage.py collectstatic and the erorr I get when I deploy my app. Capture setting.py: import os import dj_database_url # this is because I have my setting.py under setting folder BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) SECRET_KEY = os.environ['secret_key'] DEBUG = False ADMINS = [] ALLOWED_HOSTS = ['*'] EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '...@gmail.com' EMAIL_HOST_PASSWORD = os.environ['EMAIL_HOST_PASSWORD'] EMAIL_PORT = 587 EMAIL_USE_TLS = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.sites', 'registration', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third party apps 'crispy_forms', # my apps 'home', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'site2.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'site2.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', … -
Why does the js function need to be inside the html file and cannot be separates in this case?
I currently have something like this filename : notes.html {% load staticfiles %} <script src="{% static "bootstrap/js/Notes.js"%}"></script> <div class="pure-container" data-effect="pure-effect-slide" style="height: 10px"> <label class="pure-toggle-label" for="pure-toggle-left" data-toggle-label="left" style="margin-top:50px"> <span class="pure-toggle-icon"></span> </label> </div> Now I have a file called Notes.js which is like this (This file is being referenced in Notes.html file.) Filename : Notes.js $(".pure-toggle-label").click(function () { console.log("Hello World"); }) Now from the above code when I click on pure-toggle-label I expect the console to get "Hello World". However seems like the click function never gets called. Now if I move the content of Notes.js to Notes.html surrounded by the tag <script> </script> then the function gets called. My question is why this is happening ? Why cant I separately place that function in a separate file and reference that file.Why does the function not get called when the function is moved to a separate js file -
Django Admin - Cannot delete certain users
When I use django admin to delete some users, it returns this error: ERROR base handle_uncaught_exception Internal Server Error: /admin/auth/user/ Traceback (most recent call last): File "/home/yuanyin/.virtualenvs/transcats/lib/python3.5/site-packages/django/core/handlers/base.py", line 235, in get_response response = middleware_method(request, response) File "/home/yuanyin/.virtualenvs/transcats/lib/python3.5/site-packages/htmlmin/middleware.py", line 44, in process_response parser=parser) File "/home/yuanyin/.virtualenvs/transcats/lib/python3.5/site-packages/htmlmin/minify.py", line 46, in html_minify mini_soup = space_minify(soup, ignore_comments) File "/home/yuanyin/.virtualenvs/transcats/lib/python3.5/site-packages/htmlmin/minify.py", line 69, in space_minify space_minify(child, ignore_comments) File "/home/yuanyin/.virtualenvs/transcats/lib/python3.5/site-packages/htmlmin/minify.py", line 69, in space_minify space_minify(child, ignore_comments) File "/home/yuanyin/.virtualenvs/transcats/lib/python3.5/site-packages/htmlmin/minify.py", line 69, in space_minify space_minify(child, ignore_comments) File "/home/yuanyin/.virtualenvs/transcats/lib/python3.5/site-packages/htmlmin/minify.py", line 69, in space_minify space_minify(child, ignore_comments) File "/home/yuanyin/.virtualenvs/transcats/lib/python3.5/site-packages/htmlmin/minify.py", line 69, in space_minify space_minify(child, ignore_comments) File "/home/yuanyin/.virtualenvs/transcats/lib/python3.5/site-packages/htmlmin/minify.py", line 69, in space_minify space_minify(child, ignore_comments) File "/home/yuanyin/.virtualenvs/transcats/lib/python3.5/site-packages/htmlmin/minify.py", line 69, in space_minify space_minify(child, ignore_comments) File "/home/yuanyin/.virtualenvs/transcats/lib/python3.5/site-packages/htmlmin/minify.py", line 69, in space_minify space_minify(child, ignore_comments) File "/home/yuanyin/.virtualenvs/transcats/lib/python3.5/site-packages/htmlmin/minify.py", line 101, in space_minify soup.string.replace_with(new_string) File "/home/yuanyin/.virtualenvs/transcats/lib/python3.5/site-packages/bs4/element.py", line 231, in replace_with self.extract() File "/home/yuanyin/.virtualenvs/transcats/lib/python3.5/site-packages/bs4/element.py", line 258, in extract del self.parent.contents[self.parent.index(self)] File "/home/yuanyin/.virtualenvs/transcats/lib/python3.5/site-packages/bs4/element.py", line 938, in index for i, child in enumerate(self.contents): File "/home/yuanyin/.virtualenvs/transcats/lib/python3.5/site-packages/gunicorn/workers/base.py", line 192, in handle_abort sys.exit(1) SystemExit: 1 But get this: it doesn't appear all the time. When I try to delete some users, it doesn't show up; it appears when I try to delete others. What's going on? -
what's the best regex for validating comment in python?
I want to validate user's comments in my django project. in comments, these characters not allowed: [ * % & ! = ' ; ` ] what's the best regex for it? tanx -
Issues with the addition of duplicate items by django_rest_framework ListSerializer
I am using a combination of a PhoneGap app and a Django-based backend to record location data points for a research project. The PhoneGap app will bundle up multiple data points and pushes them to a django-rest-framework API endpoint, for example: [{ "speed": -1, "time": 1487292133229.221, "longitude": 172.123456, "bearing": -1, "location_type": "current", "latitude": -43.123456, "accuracy": 65, "heading": -1, "altitude": 3.585018873214722, "altitudeAccuracy": 10 }, ... ] However because of how the PhoneGap app manages location, many of the points are duplicated in the JSON that is pushed. In order to try and resolve this, I've overridden the ListSerializer to go through the incoming data and compare it to what's already in the database by computing an (unencrypted) unique hash based on timestamp and user id (who uploaded it), and then seeing if something with the same hash already exists. This approach was taken because the actual location data is encrypted before being added to the database. class DatumListSerializer(serializers.ListSerializer): def create(self, validated_data): """ Only append objects if the count of existing objects is 0 (i.e. it is unique), and it does not appear elsewhere in the list to be committed. """ objects = [] for obj in validated_data: hashed_value = generate_hash(obj['timestamp'], obj['user'].id) … -
How to get the values fro a query set in django
I am trying to get the values of all entities connected to specific user I made a loop and appended all of the results in an array but the problem is that it is generated in a query set and I don't know how only to get the value from it this is the code user_entities = Entity.objects.filter(event_id=current_event.id) user_ent=[] for u_e in user_entities: try: user_ent.append(UserEntity.objects.filter(entity=u_e,user=userphase.user)) except: pass try: first_pref=user_ent[0] second_pref=user_ent[1] and that's the result [< QuerySet < UserEntity: first-entity r>]>, < QuerySet []>, < QuerySet []>, < QuerySet [< UserEntity: Second- entity >]>] I need to get only [first-entity,second-entity] -
'DisabledBackend' object has no attribute '_get_task_meta_for'
I get the error "'DisabledBackend' object has no attribute '_get_task_meta_for'"../ Here is the django settings.py # celery settings CELERY_RESULT_BACKEND = 'amqp' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' And, this is the celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', proj.settings) app = Celery('proj', backend='amqp', broker='amqp://guest:guest@localhost:5672//') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) I installed rabbitmq on ubuntu linux with $>sudo apt-get install rabbitmq-server But, this codes work very well in mac OSX!! Not work on linux-ubuntu.. Do I have to install "elang"?? I think I didn't mistake at 'settings.py' and 'celery.py'. I never know that what is wrong. -
django render html tags passed from views.py
-- Thanks for reading -- You guys are awesome. I'm struggling with Django at the moment. I want my user to be able to write, for example image1 and use a regex to recognize and replace that with an tag. I have it all working -- but when I pass the data to template for display I do so like this: <div class="container"> <p> {% articleTxt %} </p> </div> ArticleTxt contains: This is a test Article img src="/media/articleImages/django-allauth.png" and that was a picture and this is another one then some more text ---- original: This is a test Article image1 and that was a picture and this is another one image2 then some more text OK-- to post this I had to remove the < from img tag to have it display correctly. But you get my meaning -- the img tag is formatted correctly with<> HOWEVER it renders as text and not an IMAGE! Thats my frustration I've tried changing the template to: {% autoescape off %} {{articleTXT}} {{% autoescape %}} I also tried {{% articleTXT|safe %}} Nada -- it always prints the tags instead of rendering them. Is there anyway to render tags embedded in text passed from …