Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, }) -
how to update django 2.0.1 I unable to upgrade from 1.8 version?
How to update django version 2.0.2 from 1.8 I am unable to doing this please help me out i am using python 3.5 enter image description here -
Django crispy-forms / xadmin - IndexError: list index out of range
Could someone help me understand what's going wrong here? I started a new Django project, logged into admin and created a "test" user. When I click on the user url, I could see all the editable fields (name, email, etc.) / user detail page. Then I installed xadmin, ran migrations, etc. All seems to work, except when I click on the user to see the detail page, it throws this error. IndexError at /xadmin/auth/user/2/update/ list index out of range Request Method: GET Request URL: http://127.0.0.1:8000/xadmin/auth/user/2/update/ Django Version: 1.11.10 Exception Type: IndexError Exception Value: list index out of range Exception Location: C:\Users\...\Documents\CSA\portal\portal\apps\xadmin\widgets.py in render, line 81 Python Executable: C:\Python27\python.exe Python Version: 2.7.14 Python Path: ['C:\\Users\\...\\Documents\\CSA\\portal\\portal\\apps', 'C:\\Users\\...\\Documents\\CSA\\portal', 'C:\\WINDOWS\\SYSTEM32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages', 'C:\\Python27\\lib\\site-packages\\xadmin-0.6.1-py2.7.egg', 'C:\\Python27\\lib\\site-packages\\six-1.11.0-py2.7.egg', 'c:\\python27\\lib\\site-packages', 'C:\\Python27\\lib\\site-packages\\odf', 'C:\\Python27\\lib\\site-packages\\odf', 'C:\\Python27\\lib\\site-packages\\odf', 'C:\\Python27\\lib\\site-packages\\odf', 'C:\\Python27\\lib\\site-packages\\odf', 'C:\\Python27\\lib\\site-packages\\odf', 'C:\\Python27\\lib\\site-packages\\odf'] Error during template rendering In template C:\Python27\lib\site-packages\crispy_forms\templates\bootstrap3\field.html, error at line 28 list index out of range 18 19 {% if field|is_checkboxselectmultiple %} 20 {% include 'bootstrap3/layout/checkboxselectmultiple.html' %} 21 {% endif %} 22 23 {% if field|is_radioselect %} 24 {% include 'bootstrap3/layout/radioselect.html' %} 25 {% endif %} 26 27 {% if not field|is_checkboxselectmultiple and not field|is_radioselect %} 28 {% if field|is_checkbox and form_show_labels %} 29 <label for="{{ field.id_for_label }}" … -
Django Rest Framework: Call serializer.save using double underscore
When making querysets in Django, you can use the double underscore method, to filter on specific criteria of a model: E.g. instead of filtering restaurant by their pk like this: restaurants = Restaurant.objects.filter(restaurant=<some_pk>) You can filter them by some attribute of the model like this: restaurants = Restaurant.objects.filter(restaurant__uuid=<some_uuid>) Or restaurants = Restaurant.objects.filter(restaurant__name=<some_name>) Now in function in the api views you (e.g. in get_queryset) you can use this to filter by kwargs of the request: def get_queryset(self): restaurants = Restaurant.objects.filter(restaurant__uuid=self.kwargs['uuid']) return restaurants Now I want to do the same using serializer.save(). In my perform create I want to call: def perform_create(self, serializer): serializer.save(restaurant__uuid=self.request.data['uuid']) This unfortunately throws an error. My workaround is this: def perform_create(self, serializer): restaurant = Restaurant.objects.get(restaurant__uuid=self.kwargs['uuid']) serializer.save(restaurant=restaurant) but this obviously has bad performance, because it needs to do an additional queryset. Is there any way to get it work in one step within serializer.save()? Any help would be much appreciated! -
Images from my AWS Bucket not showing on my website
I've implemented AWS S3 storage to my Django project. So I just uploaded all my static images to my bucket. However it is not showing up on my site. My HTML for the images are the standard Django syntax for template: <img src="{% static 'images/settingsIcon.png' %}"> The img src appears to point to the correct URL (the image in my bucket): however the image still doesn't work. Any idea why? -
Django API REST : Issue with function in CreateAPIView
I'm working on my Django API Rest but it's pretty new for me and I have one more question about my code. I'm reading all the time Django Rest Doc ------------------------------------------------------------------------------------------------------------------------------------ FIRST PART - My code : ------------------------------------------------------------------------------------------------------------------------------------ I have a serializer.py file which describe my ModelSerializer like this : class IndividuCreateSerializer(serializers.ModelSerializer) : class Meta : model = Individu fields = [ 'Etat', 'Civilite', 'Nom', 'Prenom', 'Sexe', 'Statut', 'DateNaissance', 'VilleNaissance', 'PaysNaissance', 'Nationalite1', 'Nationalite2', 'Profession', 'Adresse', 'Ville', 'Zip', 'Pays', 'Mail', 'Telephone', 'Image', 'CarteIdentite', ] def create(self, validated_data): print('toto') obj = Individu.objects.create(**validated_data) Identity_Individu_Resume(self.context.get('request'), obj.id) return obj This create function calls another function which is not in my API module, but in my main module : Identity_Individu_Resume As you can see here, this function takes the last created object and applies multiple processes : @login_required def Identity_Individu_Resume(request, id) : personne = get_object_or_404(Individu, pk=id) NIU = lib.Individu_Recherche.NIUGeneratorIndividu(personne) personne.NumeroIdentification = NIU if personne.Image != " " : NewImageName = 'pictures/' + personne.Nom +'_'+ personne.Prenom +'_'+ NIU + '.jpg' FilePath = settings.MEDIA_ROOT FilePathOLD = settings.MEDIA_ROOT + str(personne.Image) FilePathNEW = settings.MEDIA_ROOT + NewImageName file = os.path.exists(FilePath) if file : os.rename(FilePathOLD, FilePathNEW) personne.Image = NewImageName if personne.CarteIdentite != " " : NewCarteName = 'Carte_Identite/' + 'Carte_Identite_' + personne.Nom … -
Post request handling in Django Rest framework
I am using Django Rest Framework, currently to pull some data from the backend we are using Get request, but due to URL limit going high we are planning to implement a Post request. To do this firstly the backend Django Rest API has to be made available to serve a post request. I am new to Django and I don't find a post or get method in the code, all i can say is we are using viewsets, I tried using "@detail_route(methods=['post'])" but this didn't work, what am I doing wrong here? -
How to redirect url other than login_url when using user_passes_test in django decorators?
Here is my code: url(r'^permission_not_granted/',views.permission_not_granted, name='permission_not_granted'), this is inside decorators.py: def is_admin_or_senior_surveyor(user): return user.userrole.id == 1 this is the view method : def permission_not_granted(request): return HttpResponse("Permission Not Granted") Here is my permission: @user_passes_test(is_admin_or_senior_surveyor,login_url=None,redirect_field_name='/permission_not_granted/') -
Delete function in Django not working
I am trying to create a delete function for my Workout model. This is the model: class Workout(models.Model): workoutID = models.AutoField(primary_key=True) name = models.CharField(max_length=40) created_by = models.ForeignKey(User) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def delete(self): return reverse("delete_workout", kwargs = {'workout_id': self.workoutID}) Next I have the view: def delete_workout(request, workout_id): workout = get_object_or_404(Workout, workoutID = workout_id) print(workout) if request.user != workout.created_by: return HttpResponse('Not ur workout') else: workout.delete() return HttpResponseRedirect('/') This is the url: url(r'^(?P<workout_id>\d+)/delete/$', views.delete_workout, name='delete_workout'), And finally the html: <a href='{{ instance.delete }}'> <button>Delete Workout</button> </a> Im not getting any errors in the console, which is why I dont know what is going wrong. Thanks