Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ISODate to JSON date format issue - Django
I am using MongoDB with Django as backend. I am adding timestamp in a column whenever new record is created, as below datetime.datetime.now() It is getting stored as below "created_date" : ISODate("2018-02-21T08:45:38.806Z") Now below is snippet of code sending data to UI row = AttackLog.objects.filter(id='123') rows = row.to_json() return Response({'row':json.loads(rows)}) I tested via postman. Everything is working fine except "created_date": { "$date": 1519208451157 }, I have 2 questions, How can I change it to readable format? How can I apply filter on it? -
Bootstrap tab stay in active after refresh using Django
I created a Bootstrap tab where I want to display different JS charts. I used jQuery to keep active the tabs after refresh, but my problem is that when I click on the submit bottom and the page is reloading the first tab is always appear for 1 second and it is really annoying. Maybe because that that the first tab render fist and just after become active the latest tab page. I thought about this and maybe the solution would that I rid of the JQuery and I use simple Django. My main question is: can I use the tabs as input (like hidden input or something? Because If i can I can send an input (I selected let's say the third tab) to the server (Django) and based on this message I can change the active class after refresh. Furthermore If somebody know better idea to not use JS to keep elected tabs active do not hesitate inform me. Thank you in advance. Currently I use this solution: $(function() { $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) { localStorage.setItem('lastTab', $(this).attr('href')); }); var lastTab = localStorage.getItem('lastTab'); if (lastTab) { $('[href="' + lastTab + '"]').tab('show'); } console.log(lastTab); if (lastTab == "#Section1") { $('.nav-tabs a[href="#Section1"]').tab('show'); } … -
Django Rest Framework: Updating / creating multiple objects dynamically, without giving the pk
I just stumbled upon the hardest problem I ever had with Django Rest Framework. Let me give you my models first, and then explain: class Stampcardformat(models.Model): workunit = models.ForeignKey( Workunit, on_delete=models.CASCADE ) uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) limit = models.PositiveSmallIntegerField( default=10 ) category = models.CharField( max_length=255 ) class Stampcard(models.Model): stampcardformat = models.ForeignKey( Stampcardformat, on_delete=models.CASCADE ) user = models.ForeignKey( User, on_delete=models.CASCADE ) uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) class Stamp(models.Model): stampcardformat = models.ForeignKey( Stampcardformat, on_delete=models.CASCADE ) stampcard = models.ForeignKey( Stampcard, on_delete=models.CASCADE, blank=True, null=True ) uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) These models describe a simple stampcard model. A stampcard is considered full, when it has as many stamps via foreignkey associated to it as it's stampcardformat's limit number dictates. I need to write view that does the following: The view takes in a list of stamps (see below) consisting of their uuid's. It then needs to find the right stampcardformat for each given stamp. Next it needs to check, whether the requests user has a stampcard with the corresponding stampcardformat. a) If it has, it needs to check, if the stampcard is full or not. i) If it is full, it needs to create a new stampcard … -
migration from sqlite to postgresql in django
I want to migrate from sqlite to postgresql db: I was installed postgresql and create db on its shell, then configure my django setting as bellow: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'dbname', 'USER': 'username', 'PASSWORD': 'dbpass', 'HOST': 'localhost', 'PORT': '', } Or: 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dbname', 'USER': 'username', 'PASSWORD': 'dbpass', 'HOST': 'localhost', 'PORT': '', } But when do python manage.py migrate I encountered by this error: ValueError: invalid literal for int() with base 10: '0x000 What's wrong?! -
Django Query values_list getting last value
lets say I have a blog and a class user in a model. Furthermore I have a class comment connected with a foreign key. Now I want to make an csv export in model admin and a I have a queryset with values_list. I am wondering whether there exists a possibility to get each User once and e.g. only the last comment? myList = queryset.values_list('UserName', 'UserCountry', 'comLink__commentText') comLink is the foreign key. Now I just want the last comment. A timestamp is existing and I have not figured out how to filter or reverse etc. -
Error in Django Channels installation
I've followed along this doc to learn how to add a websocket to my already functioning Django app, and after installing Channels, and adding the settings as that tutorial explained, I tried running my server with python3 manage.py runserver to see if it still worked, but I got this error: ImportError: No module named 'websocket.apps.WebsocketConfigmainsite'; 'websocket.apps' is not a package What can I have done wrong? And are all other "normal" django apps supposed to keep working if I add Channels to the project (I only want one app of the project to use websockets)? Note that I didn't use any third-party apps that require an overloaded or replacement runserver command as those the docs warned about. -
NameError: Name view_post is not defined
I apologise for yet another simple Django question but I cannot find what I'm after. Project: Blog I'm trying to URL design to the app using Django 2.0 enter image description here enter image description here enter image description here -
Django Rest Framework: Overwriting validation error keys
When translating my site to another language a problem occurred. I want to handle Validation Errors properly and allow my front-end friends to display them well. Is there a way to overwrite keys in response message of DRF when Validation Error happend? What do I mean by that - I want to change this: { "name": ["This field is required."] } into: { "username": ["This field is required."] } Is there a way to do that without writing each and every one of validators? -
How to filter multiple values for same column
from django.contrib.auth.models import User ... resolvers = User.objects.filter(groups__name = 'resolver') above code is to filter user belongs to group resolver, in this I need to retrieve users those belongs to admin group as well. I tried resolvers = User.objects.filter(groups__name = 'resolver' or 'admin') resolvers = User.objects.filter(groups__name = ('resolver','admin')) both are failing, please help. -
User does not appear under 'authentication and authorization'
I am following this tutorial to create custom model. But when I login to Django admin, the user does not appear under 'groups' in authentication and authorization. How can I make it appear? -
Manage Similar Models in Django
Consider a Blog Project. I have a very similar model named Blog and BlogRequest. BlogRequest has entry of all blogs which has been requested by people. BlogRequest Model looks like the following": class Blog(models.Model): ..... # some usual blog fields .... stage = ... # choicefield .... # some other fields BlogRequest.stage field can take many values like created, edited, formated, reviewed, accepted, rejected etc. A BlogRequest instance goes through a number of stages before being accepted. I now require all the accepted BlogRequest instance as an instance of Blog Model. Blog model should be a subset of BlogRequest and can also contain some extra fields such as liked_by, disliked_byand comments etc. This situation can be handled by creating a Blog instance every time a BlogRequest object achieves accepted status (signals can help here). Extra details required for a Blog Model can be added afterwards, through admin or using forms outside admin. This approach has disadvantages such as (say) changing maximum length of blog content will require me changing fields in both the models. Therefore, I want to know if there are better approaches to handle similar situations. -
How do I import multiple classes in another django app correctly
I am using python 3.5 + django 1.11 and I have two apps hr and payroll in my project called ERP. On payroll app model.py I'm importing classes from hr as below: # Imports from your apps from hr.models import ( # Employee, Job, JobHistory, Department, Section, Region, Country, Location, ) I think this is cumbersome for me considering if in the future I will add more classes to hr I will have to add the same classes as imports above. Is there a simpler way to import them at once without adding them one by one ? -
How can I use a variable in a jinja2 selectattr filter?
I'm trying to filter a list based on an attribute. If I use the attribute as a string everything works fine: {% set ys = xs | selectattr("type", "equalto", "first") | list %} If I tried to use a variable (in my case a property of an enum) instead I get back an empty list {% set ys = xs | selectattr("type", "equalto", MyEnum.FIRST) | list %} The variable MyEnum.FIRST contains the string "first". -
Django / Python - Extract Date from DateTimeField
Take the example model as follows: import datetime class Calendar(models.Model) def now(): return datetime.date.today() def 24hrslater(): return datetime.date.today() + datetime.timedelta(days=1) now = models.DateTimeField(default=now) 24hrslater = models.DateTimeField(default=24hrslater) Is there a way to extract just the date from these date time fields? I have tried the following (as suggested on another thread): todaysdate = now.date() But had no success with it. The error that comes up on the command line when running "python manage.py check" is: AttributeError: 'DateTimeField' object has no attribute 'date' Is there a way to do this? Many thanks! -
Override admin fieldset for model in app
Django admin docs state that you can override templates for specific models in specific apps by putting template in my_app/my_model subdirectory of templates/admin folder in your application. I'm trying to override includes/fieldset.html template for my_model in my_app. Saving it as my_app/admin/my_app/my_model/includes/fieldset.html doesn't seem to work, while my_app/admin/includes/fieldset.html does, but overrides template for all pages in admin site. Is there any way to achieve this behaviour? -
Django management comments not loaded, while settings.INSTALLED_APPS are configured
I was using django 1.7.final.0 for a while, but am now trying to upgrade to 1.8 (..and eventually to the newest version). When running manage.py help, the commands I see are only the base commands. I've added a print statement, to see if INSTALLED_APPS works and it does. import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") from config import settings print(settings.INSTALLED_APPS) # prints apps like django-extensions that have commands. from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) There are no errors, but it simply doesn't list the other commands. If I try to run a command, like ./manage.py shell_plus it returns Unknown Command as can be seen below. Note the print statement, indicating that INSTALLED_APPS can be read. (venv) rootadmin@annotatie01:/data_nfs/opensurfaces2/server$ python manage.py shell_plus ('admin_tools', 'admin_tools.theming', 'admin_tools.menu', 'admin_tools.dashboard', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'django.contrib.humanize', 'gunicorn', 'storages', 'queued_storage', 'django_extensions', 'account', 'django_forms_bootstrap', 'imagekit', 'compressor', 'endless_pagination', 'cacheback', 'captcha', 'mptt', 'debug_toolbar', 'cache_panel', 'memcache_status', 'common', 'home', 'accounts', 'analytics', 'licenses', 'poly', 'mturk', 'categories', 'photos', 'shapes', 'bsdfs', 'normals', 'intrinsic', 'points', 'boxes', 'matclass', 'paintings', 'binaryQuestion') Unknown command: 'shell_plus' Type 'manage.py help' for usage. (venv) rootadmin@annotatie01:/data -
Django refresh data from DB inside an atomic block
I have a complex block of code that handle the creation/update of ORM object relationships. Let's say the models are A and B and the association is a OneToOne A - B (A.b_line points to B). 1) Before creating/updating the associations some A objects needs to be updated and saved into db. During this operation some internal fields of A objects are computed and saved. 2) The updated A object are reloaded from db (because we need the derived computed filed) and the associations with the B objects can proceed. Example: def update_and_associate(a_items): with transaction.atomic(): for item in a_items: item.field_alpha = 1 # updates item.field_beta depending on # item.field_alpha item.update_beta() item.save() # Save to db with transaction.atomic: for item in a_items: item.refresh_from_db() b = item.b_line b.total = a.field_beta b.save() # later... try: update_and_associate(items) except Exception as e: handle_exception(e) I'm enclosing the code in nested atomic transaction block so that if any exception happen the changes should be rolled back (MySql with InnoDB). The problem is that in the second atomic block when I reload item with refresh_from_db they are not in sync, meaning they have old values as if the first transaction block didn't run at all. I though that … -
graphql reason-apollo - recursive parsing of options
I'm using Reason-Apollo to parse a pretty nested GraphQL response from my server. { "data": { "chatGroup": { "id": "Q2hhdEdyb3VwVHlwZTox", "users": { "edges": [ { "node": { "id": "VXNlclR5cGU6MzQ=", "name": "User 1", "isCurrentUser": false } }, { "node": { "id": "VXNlclR5cGU6MQ==", "name": "User 2", "isCurrentUser": true } } ] }, "messages": { "edges": [ { "node": { "id": "Q2hhdE1lc3NhZ2VUeXBlOjE=", "text": "my first message", "author": { "name": "User 1", "abbreviation": "U1", "photoUrl": "", "isCurrentUser": true } } }, ... This ends up producing a hairy tree of options... Js.t({. id : string, messages : option(Js.t({. edges : array(option(Js.t({. node : option( Js.t( {. author : Js.t( {. abbreviation : option( string), isCurrentUser : option( Js.boolean), name : option( string), photoUrl : option( string) }), id : string, text : string })) }))) })), users : option(Js.t({. edges : array(option(Js.t({. node : option( Js.t({. id : string, isCurrentUser : option( Js.boolean), name : option( string) })) }))) })) }) I can make a parser that handles all of these options to render the desired response, but it seems like this would produce pretty muddled code. What is the common paradigm around parsing options in JS when using ReasonML / OCaml? Is there … -
How do I get n items for each of the given list of foreignkey?
I am trying to figure out a way to execute this query in the least possible time. number_of_results = 25 results = [] foreign_keys = [1,2,3,4,5] for key in foreign_keys(): results.append(Model.objects.filter(foreign_key=key)[:number_of_resutlts]) Even if it is a single queryset, it is okay. What I am trying to accomplish is to reduce the count of database queries. My db is postgres 10. How can I make this further simple? -
Django: How to load file not in MEDIA_ROOT correctly | FileField?
In my Django project I have application in which I want to load files NOT in MEDIA_ROOT. I used storage attribute to change the place but it raise error. I used next code but it raise error when I try to load the file. How can I fix this problem? settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root') models.py: from django.core.files.storage import FileSystemStorage from os import environ PRODUCT_STORAGE = FileSystemStorage(location=environ.get('PRODUCT_STORAGE_PATH')) def product_file_upload_path(instance, filename): if instance.category=="1": path = '/category_1/' + '/%s' % filename return path elif instance.category=="2": path = '/category_2/' + '%s' % filename return path else: path = '%s' % filename return path class Product(models.Model): file = models.FileField( max_length=255, blank=True, null=True, validators=[validate_file_extension], storage=PRODUCT_STORAGE, upload_to=product_file_upload_path, ) ERROR: The joined path (/category_1/test.pdf) is located outside of the base path component (/other_folder) -
Django REST Framework - How to return 404 error instead of 403
My API allows access (any request) to certain objects only when a user is authenticated and certain other conditions are satisfied. class SomethingViewSet(viewsets.ModelViewSet): queryset = Something.objects.filter(query_hiding_non_authorized_objects) serializer_class = SomethingSerializer permission_classes = (permissions.IsAuthenticated, SomePermission) If a user attempts to view a non-authorized object DRF returns a 403 error, however, this gives away that an object with the requested id exists. How can I return 404 errors in these cases? Note: I also use a custom queryset to hide non-authorized objects from being listed. -
How can in install Django project requirement.txt with python script
I am creating a single script for setup and running whole Django project. venv_parent_dir = os.path.abspath(os.path.join(os.getcwd(),os.pardir)) venv_dir = os.path.abspath(os.path.join(venv_parent_dir, 'fvenv')) subprocess.run(args=['virtualenv', '-p', 'python3', venv_dir]) os.popen('/bin/bash --rcfile %s'%(venv_dir+'/bin/activate')) With the above code I created a virtual environment then activate this.. now i want to install requirements.txt file in activated virtual environment subprocess.run(args=['pip3', 'install', '-r', 'requirements.txt']) I tried with subprocess, but its not installing in virtual environment, installing os python module Please help... -
Python create a unique hash/encrypted url
I want to create an app where if a person would like to apply working for my company, I'll create an entry in my app and I'll send them a unique URL where it lead to a form page, I wanted the URL to be hashed, but I'm not quite sure how to do this. Below is my code : view.py : def applicant_email_view(request): form = ApplicantEmailForm(request.POST or None) if form.is_valid(): inst = form.save(commit=False) subject = 'Applicant Form' text_content = 'Hola' html_content = """ <h3 style="color: #0b9ac4><a>http://127.0.0.1:8080/hiring/application_form/</a></h3> """ to = [inst.applicant_email] send_email(subject, text_content, html_content, to) inst.save() return render(request, 'hiring/applicant_email.html', {'form': form}) def application_form_view(request): form = JobApplicationForm(request.POST or None, request.FILES or None) if form.is_valid(): inst = form.save(commit=False) inst.save() context = {'form': form} return render(request, 'hiring/application_form.html', context=context) def send_email(subject, text_content, html_content, to): from_email = 'test@testing.studio' footer = """<h5>Do not reply to this email. This is automated email notification from LemonCORE.</h5> </br> """ email_body = html_content + footer msg = EmailMultiAlternatives(subject, text_content, from_email, to) msg.attach_alternative(email_body, "text/html") msg.send() url.py: url(r'^hiring/application_email/$', applicant_email_view, name='application_email_view'), url(r'^hiring/application_form/$', application_form_view, name='application_form_view'), -
Assign task to user in viewflow
I am using django-viewflow in one of my application. I don't want to assign user to a task as soon as it is being created using Assign(). When a user logs in, I want to check if there are any unassigned task if so, fetch one and assign to a user. How can I do this? Thanks in advance -
getting error 'QuerySet' object has no attribute '_meta'
getting this error, 'QuerySet' object has no attribute '_meta' how to solve this problem views.py def profile_update_view(request, username): user = User.objects.filter(username__iexact=username) form = UserProfileForm(instance=user) if request.user.is_authenticated and request.user.id == user.id: if request.method == "POST": form = UserProfileForm(request.POST, request.FILES, instance=user) if form.is_valid(): created_prof = form.save(commit=False) created_prof.user = request.user created_prof.save() return redirect('profiles:profile-detail',username=username) return render(request, "profiles/profile_form.html", { "username": username, "form": form, })