Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Python mod_wsgi: ImportError: No module named 'django'
I'm trying to set up a Django-Python environment in Ubunt16.04u server but I get the Apache error: "ImportError: No module named 'django'" I've installed Python 3.7, virtualenv (sudo pip install virtualenv), Django (pip install Django), mod_wsgi (sudo make install). Which could be the reason of the issue? //Apache Error Log File [Wed Nov 21 17:45:07.572605 2018] [wsgi:error] [pid 60818] [remote 192.168.224.1:56398] mod_wsgi (pid=60818): Target WSGI script '/var/www/django_virtualenv/progetti_django/curriculum/curriculum/wsgi.py' cannot be loaded as Python module. [Wed Nov 21 17:45:07.572638 2018] [wsgi:error] [pid 60818] [remote 192.168.224.1:56398] mod_wsgi (pid=60818): Exception occurred processing WSGI script '/var/www/django_virtualenv/progetti_django/curriculum/curriculum/wsgi.py'. [Wed Nov 21 17:45:07.572758 2018] [wsgi:error] [pid 60818] [remote 192.168.224.1:56398] Traceback (most recent call last): [Wed Nov 21 17:45:07.572805 2018] [wsgi:error] [pid 60818] [remote 192.168.224.1:56398] File "/var/www/django_virtualenv/progetti_django/curriculum/curriculum/wsgi.py", line 17, in <module> [Wed Nov 21 17:45:07.572812 2018] [wsgi:error] [pid 60818] [remote 192.168.224.1:56398] from django.core.wsgi import get_wsgi_application [Wed Nov 21 17:45:07.572824 2018] [wsgi:error] [pid 60818] [remote 192.168.224.1:56398] ImportError: No module named 'django' //Apache Config File <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's … -
How to force/warn the way other developers treat some class/django model
We have a Django project and I came across this problem multiple times this year. I will simplify the example: class MyModel(Model): my_attr = .... ... def get_my_attr_safe(): if not self.my_attr: return somecalculation() return self.my_attr I want to force developers to use get_my_attr_safe() instead of my_attr. It's a huge and complicated model. My idea was to somehow override __getattribute__ and raise Exception if it's called directly but I don't think this would work. Moreover, Django, of course needs to call sometimes ModelFields directly so I can't just do it this way. I want to either raise Exception or make sure they will get the information that they have to use the method if possible. For example I need them to use the method everywhere in templates: {{ obj.get_my_attr_safe }} instead of {{ obj.my_attr }} The solution doesn't have to be Pythonic, maybe there is a way to do this using PyCharm only. It would be enough. -
How to check if Django ValidationError subclass was raised?
Let's assume I have a Django model: class MyDjangoModel(models.Model): name = models.CharField(max_length=200) attribute = models.IntegerField() class CustomValidationError(ValidationError): pass def clean(self): if self.attribute < 1: raise CustomValidationError("Attribute should be > 1!") if len(self.name) > 20: raise ValidationError("Name too long!") I would like to create model instance and validate it: inst = MyDjangoModel(name="Foo", attribute=0) try: inst.full_clean() except CustomValidationError as e: print("Hello!") But the code above will never print "Hello!" because full_clean method is raising only ValidationError. Can anyone suggest, how to call full_clean and check if ValidationError subclass exception was raised? -
djChoices download issue in CMD
I can't download djChoices from https://pypi.org/project/djChoices/ unsing pip install djChoices. I getting error in cmd ERROR -
Having a dynamic rest view duplicates the user-list url
(I have a custom user model) I do not understand why this is happening. These are my expected urls: python manage.py show_urls /api/v1/ rest_framework.routers.APIRootView api-root /api/v1/\.<format>/ rest_framework.routers.APIRootView api-root /api/v1/users/ users.views.UserCreateViewSet user-list /api/v1/users/<pk>/ users.views.UserViewSet user-detail /api/v1/users/<pk>\.<format>/ users.views.UserViewSet user-detail /api/v1/users\.<format>/ users.views.UserCreateViewSet user-list As soon as I include in my urls.py a view based on DynamicModelViewSet: from dynamic_rest.viewsets import DynamicModelViewSet class AggregateViewSet(DynamicModelViewSet): pass My user-list urls are duplicated: » python manage.py show_urls /api/v1/ rest_framework.routers.APIRootView api-root /api/v1/\.<format>/ rest_framework.routers.APIRootView api-root /api/v1/users/ users.views.UserCreateViewSet user-list /api/v1/users/ users.views.UserViewSet user-list /api/v1/users/<pk>/ users.views.UserViewSet user-detail /api/v1/users/<pk>\.<format>/ users.views.UserViewSet user-detail /api/v1/users\.<format>/ users.views.UserCreateViewSet user-list /api/v1/users\.<format>/ users.views.UserViewSet user-list This is my (simplified) urls.py: from django.urls include from rest_framework.routers import DefaultRouter # from consumption.views import AggregateViewSet router = DefaultRouter() router.register(r'users', UserViewSet) router.register(r'users', UserCreateViewSet) urlpatterns = [ path('api/v1/', include(router.urls)), ] Activating that from consumption.views import AggregateViewSet statement makes the problem appear. It does not even need to be registered to the router: just importing the view is breaking the urls. Why is dynamic-rest mangling the urls just by being imported? -
Django 1.11 - Use Model to query a clone table
I have a table core_people and a backup table: core_people_01 Is it possibile to use People Django model to make a query on the "clone" table? Something like this: People.objects.get(pk = 123).table("people_01") Im searching online without success. -
Django view rendered with formset errors causes a ton of queries
Is there a way to minimize the number of queries when a view is rendered with inlineformset_factory errors? class CustomerProductForm(forms.ModelForm): class Meta: model = CustomerProduct # m2m through fields = ('product', 'unit', 'price') CustomerTemplateFormSet = inlineformset_factory( Customer, CustomerProduct, fk_name='customer', form=CustomerProductForm) If product and unit are foreign keys (plus customer) a formset consisting of 50 forms rendered with errors will cause 50 duplicate queries for each field. Is there some way to optimize? -
Python - Django - Pass serializer and attribute as argument
currently i am dealing with this snippet: def to_representation(self, instance): representation = super().to_representation(instance) representation['categories'] = CategorySerializer(instance.categories, many=True).data return representation Now i would like to make the snippet representation['categories'] = CategorySerializer(instance.categories, many=True).data more generic, so i can pass any field and its corresponding serializer here, like: representation[config['field']] = config['serializer'](instance[getattr(instance, config['field'])]).data but it crashed totally, anybody ever dealed with this kind of generic setup? thanks and greetings! -
understanding QuerySet of Django Permissions
Am new to Django, have been working on linking some permissions to groups and then adding users to those groups. Have managed some of that so far, but am stuck on understanding exactly what is going on with the permissions. Here is my attempt so far: (Django-1.11.4-env) $ python manage.py shell Python 3.6.7 (default, Oct 25 2018, 13:09:20) [GCC 6.3.0 20170516] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.contrib.auth.models import Permission >>> p = Permission.objects.all() then >>> p.values <bound method QuerySet.values of <QuerySet [<Permission: MyApp | user | Can add user>, <Permission: MyApp | user | Can write stuff.>, <Permission: MyApp | user | Can change user>, <Permission: MyApp | user | Can delete user>, <Permission: admin | log entry | Can add log entry>, <Permission: admin | log entry | Can change log entry>, <Permission: admin | log entry | Can delete log entry>, <Permission: auth | group | Can add group>, <Permission: auth | group | Can change group>, <Permission: auth | group | Can delete group>, <Permission: auth | permission | Can add permission>, <Permission: auth | permission | Can change permission>, <Permission: auth | permission | Can delete permission>, … -
Django-storages does not see the GOOGLE_APPLICATION_CREDENTIALS environment variable.
I am using Django Storages to work with Google Cloud Storage to service static and media files. I have set the required GOOGLE_APPLICATION_CREDENTIALS, but django fails to see it, and returns an Attribute Error. you need a private key to sign credentials.the credentials you are currently using <class 'google.auth.compute_engine.credentials.Credentials'> just contains a token. I also added the environment variable to /etc/environment/, tried export GOOGLE..., set the environment in my Gunicorn run command with a -e param, and specified it in a .env file alongside my manage.py, with my other secrets. I am using ubuntu 18. -
Populating a Postgresql database with an API from url
I am tasked with populating an existing database with info from a Jira API within a web app made with django/python. I am not asking for a full answer but just want to know where i should start. I have started thinking of retrieving data from the url serving JSON and putting that into a .csv file and then populate the table that way, but was wondering if there is a more efficient way of doing this. If there is any reference or advice you could give me on where to start that would also be great. -
Display Age from date of birth
I need help with displaying an age when I enter a date of birth. I have tried this JS method but I cannot get it to display. <div class="kidsFormCenter"> {% for kid in kids %} <table class="kidsTable kidForm"> <form action="{% url 'update_profile_kid' kid.id %}" method="post"> {% csrf_token %} <tr> <td>First name:</td> <td><input type="text" value="{{ kid.name }}" name="name"></td> </tr> <tr> <td>Date of Birth:</td> <td><input type="text" maxlength="10" value="{{ kid.dob }}" name="dob"></td> <td><input type="text" id="age" class="form-control" required readonly></td> </tr> <tr> <td>Gender:</td> <td><input type="text" maxlength="1" value="{{ kid.gender }}" name="gender"></td> </tr> <tr> <td><button class="btn btn-primary" formaction="{% url 'update_profile_kid' kid.id %}" type="submit">Edit</button> <form action="{% url 'delete_profile_kid' kid.id %}" method="POST"> {% csrf_token %}<button class="btn btn-info" formaction="{% url 'delete_profile_kid' kid.id %}" type="submit">Delete</button></td> </form> </tr> </form> </table> <br> {% endfor %} </div> And my age.js is $(function() { $('input[name="dob"]').daterangepicker({ singleDatePicker: true, showDropdowns: true }, function(start, end, label) { var years = moment().diff(start, 'years'); $("#age").val("You are " + years + " years old."); }); }); I want the age of the child to be displayed. -
Filter models with created date less than today's date
So i have a model, And i want to filter all models with created date less than today's date . For example Class Post(models.Model): created=model.DateField() view.py get_objects_with_date_lessthan_today_date=Post.objects.filter(created=) In my view i need to filter all models with created date less than today's date .Please i need help . In going about this logic -
Why django rest framework's serializer won't systematically validate model before save
When we compare code in django form and django rest framework's serializer, the last only validates fresh data from request, then launches immediately Model.save() instead of full_clean() used by django form. Sometimes we need to check data in actual model instance before save, but in this case, an override of serializer's run_validation/create/update should be used in order to call model instance's validation by self.instance.clean/full_clean/..., like class MySerializer(serializers.ModelSerializer): field = serializers.ReadOnlyField(source='xxx') class Meta: model = MyModel fields = (...) read_only_fields = (...) def run_validation(self, data=empty): self.instance.clean() return super(MySerializer, self).run_validation(data=data) Such that I feel discouraged to call model's validation in serializer. Maybe I'm using it wrongly, so what's the philosophy here ? Thanks. -
django deployment on GCP with kubernetes
I finally got my first django project and i need help in deploying it in GCP with kubernetes. i've never deployed any project before so it's a bit frustrating for me with the client nagging on my head. it's an E-learning platform so i want to use GCP with kubernetes (for CI/DI since there will be a lot of updates for the project) and Google cloud storage for storing media files. ps: this is my first question so be easy on me -
Django: Access form_kwargs in init
I defined form_kwargsand I am able to access them directly in my __init__ in forms.py. I expected to do organizer = kwargs.pop('organizer') etc. Can anyone explain me why it's possible that I access these kwargs directly even so they should be stored inside form_kwargs? I'm currently trying to replicate this behaviour to my class BaseReserveFormSet(BaseFormSet): but there I can't access them without kwargs.pop @cached_property def formset(self): ReserveFormSet = formset_factory( ReserveForm, formset=BaseReserveFormSet, extra=0 ) return ReserveFormSet( data=( self.request.POST if self.request.method == 'POST' else None ), initial=self.tickets, form_kwargs={ 'organizer': self.request.organizer, 'event': self.request.event, 'user_order_reference': self.request.session.get('order_reference'), 'discount_code_session': self.discount_code, } ) forms.py class ReserveForm(forms.ModelForm): class Meta: model = ReservedItem fields = ['ticket', 'quantity'] def __init__(self, organizer, event, user_order_reference, discount_code_session, *args, **kwargs): self.organizer = organizer self.event = event [...] -
Standard for application-specific template directories in Django?
I guess this is a question related to best practises in Django development. I'm trying to build a web service with a main page (base.html) that contains multiple apps. I would like to make the apps self-contained, so I've made a templates directory in each app, and would also like to take advantage of the template inheritance feature of Django to make this whole thing as fluid as possible. Now my concern is, where should I put the base.html in my project, so that the system knew where to find it? Also, what changes should I make in the settings.py file in order for the system to be able to connect the templates? Is there a standard or a known method that takes minimal effort for this sort of arrangement? -
How to list available authentication backends for a Django user?
I have a project that uses Python 3.6 and Django 1.11 where I use the built-in User model. The user objects are all inside the default database (which is postgres), but the project uses a second authentication backend because some users need to be authenticated against a legacy Oracle database. # settings.py AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', # new postgres DB 'project_config.auth_backends.OtherBackend', # legacy Oracle DB ] This works fine so far, but now I have 3 groups of users: some users can only authenticate in ModelBackend because they are not in the legacy DB (because they are new users). some users can only authenticate in the legacy DB; they have usr.has_usable_password() == False because they have not set their password in the new postgres DB yet. some users can authenticate in both backends, maybe even with different passwords in each one; this is because they changed their password in the new system, but by design that change is not transmitted back to the legacy DB (don't shoot me, the only way to change the password in the legacy DB is to do it manually through the user interface). For auditing purposes, I want to list all users and see which … -
How can I delete a records out of the django-database by using confirm in JavaScript?
I have a model named Actie in models.py. This is my template I rendered by a view. The context I passed: {'actie': Actie.objects.all(), 'user': request.user} Actie is just a model in models.py. {% for actie in actie %} {% if actie.actie_gebruiker.id == user.id %} <tr onclick="window.location.href={{ actie.id }}"> <td>{{ actie.id }}</td> <td>{{ actie.actie_naam }}</td> <td>{{ actie.actie_status.status_naam }}</td> <td>{{ actie.actie_aanmaakdatum|date:"d-m-y [ H:i ]" }}</td> <td>{{ actie.actie_einddatum|date:"d-m-y" }}</td> <td>{{ actie.actie_eindtijdstip|date:"[ H:i ]" }}</td> <td>{{ actie.actie_gebruiker }}</td> </tr> <a id="verwijderenButton" href="" onclick="bevestigVerwijdering();"><img class="icontje" src="{% static 'MyApp/verwijderen.png' %}"></a> <script> function bevestigVerwijdering() { var actie_id = '{{ actie.id }}'; var antwoord = confirm("Are you sure you want to delete this?"); if (antwoord == true) { document.getElementById('verwijderenButton').href = 'verwijderen/' + actie_id + '/'; alert(actie_id); alert(document.getElementById('verwijderenButton').href); } } </script> {% endif %} {% endfor %} Now what I want this code to do is that when I click on the image, that it deletes that specifc record out of the database. It deletes nothing when I don't click on the first record. It deletes the last record when I click on the first record. This is my view: def verwijderActie(request, id): Actie.objects.filter(id=id).delete() return HttpResponseRedirect('../../') -
Flutter with Python Django RESTFUL API
Need Help I have written a flutter widgets for my application for the User Signup in my application and also an API with Django RESTFUL API. How do I connect or integrate the API routes/URL in python Django with the flutter widgets? Please, I need a sample code. I will appreciate any help. Here is my signup flutter widget: import 'package:flutter/material.dart'; class SignUpPage2 extends StatefulWidget { @override SignUpPage2State createState() => SignUpPage2State(); } class SignUpPage2State extends State { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, leading: IconButton( icon: new Icon(Icons.arrow_back, color:Colors.orange.shade700), onPressed: () { Navigator.pop(context); }, ), title: Text("Create acount", style: TextStyle(color:Colors.orange.shade700)), backgroundColor: Colors.black, ), backgroundColor: Colors.black45, body: Center( child: ListView( shrinkWrap: true, padding: EdgeInsets.only(left: 24.0, right: 24.0), children: <Widget>[ new Center( child: new Text("Welcome", style: new TextStyle( color: Colors.orange.shade700, fontFamily: 'Poppins-Bold', fontSize: 30.0, ), textAlign: TextAlign.center, ), ), SizedBox(height: 10.0), new Center( child: new Text("Please, Introduce Yourself", style: new TextStyle( color: Colors.white, fontFamily: 'Poppins', fontSize: 20.0, ), textAlign: TextAlign.center, ), ), SizedBox(height: 20.0), TextField( keyboardType: TextInputType.text, autofocus: false, decoration: InputDecoration( hintText: 'First Name', filled: true, fillColor: Colors.white, contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0), border: OutlineInputBorder( borderRadius: BorderRadius.circular(32.0), ), ), ), SizedBox(height: 15.0), TextField( keyboardType: TextInputType.text, autofocus: false, … -
Django Rest Framework: SerializerMethodField and get_queryset
In my database I have two tables - users and user_properties I need to filter output using GET parameter phone. But both that tables has column phone and has different values. I need to do request with GET parameter ex. "?phone=123456789" and search User by phone number using not only user_properties.phone, but user.phone too! I googled and found a way partially to do this using get_queryset(filtering) and SerializerMethodField(to modify output): views.py class UserPropertiesViewSet(viewsets.ModelViewSet): queryset = UserProperties.objects.all() serializer_class = serializers.UserPropertiesSerializer def get_queryset(self): queryset = self.queryset # phone number from GET phone = self.request.query_params.get('phone') # Search users matches in user_properties using by phone number if phone: queryset = UserProperties.objects.all() users = queryset.filter(phone__contains=phone) return users else: return queryset serializers.py class UserPropertiesSerializer(serializers.ModelSerializer): all_phones = serializers.SerializerMethodField() class Meta: model = models.UserProperties fields = ['user_id', 'phone', 'fio', 'url', 'all_phones',] # phone numbers from user and user_properties tables def get_all_phones(self, obj): # search phones in <user> table by user_id user_phones = models.User.objects.filter(id__exact=obj.user_id).values_list('phone', flat=True) # add phones from user_properties table result = [obj.phone,] # add phones from user table for phone in user_phones[0].split(','): result.append(''.join(filter(lambda x: x.isdigit(), phone))) # return list with all phones return set(result) And I get all_phones column in my filtered results: { "count": 1, "next": … -
Removing a user from a group does not remove that group's permissions
I am working with Django Groups & Permissions programatically and getting confused. When I add a user to a group, that group's permissions are also added. But when I remove a user from a group, that group's permissions are not also removed. Here is some code: from django.contrib.auth import get_user_model from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType User = get_user_model() user_ct = ContentType.objects.get_for_model(User) group, _ = Group.objects.get_or_create(name="MyGroup") permission, _ = Permission.objects.get_or_create(content_type=user_ct, codename="my_permission", name="My Permission") permission_name = f"{permission.content_type.app_label}.{permission.codename}" group.permissions.add(permission) group.user_set.add(user) assert group in user.groups.all() # THIS WORKS... assert permission_name in user.get_group_permissions() group.user_set.remove(user) assert group not in user.groups.all() # THIS FAILS... assert permission_name not in user.get_roup_permissions() Although the group has been successfully removed, the associated permission still remains. Any ideas on what I'm dong wrong? -
How to convert pdf to html in django?
I know how to convert html to pdf using python packages and in jquery, but i have a task to perform the opposite, i want exact html from a pdf. How to do so? Is there any jquery or python package or method in which i can do so? -
Django : Set url dynamical with <a> element in template
I'm wondering how I can change in Django this link : <a href="http://localhost:8000{% url 'my-token' token=token %}">{{title}}</a> I would like to set http://localhost:8000 dynamical. If I'm working in local, it will be http://localhost:8000 and if I am on my dev server or production server it could be https://subdomaine.domain.com My idea : I could create different settings file : local.py / dev.py / prod.py and define inside each one : #local.py SITE_URL = "http://localhost:8000" #dev.py SITE_URL = "http://dev.domain.com" #prod.py SITE_URL = "http://prod.domain.com" So how I can handle my <a> link to add SITE_URL ? -
Django login redirect_field_name 'next' forces new session
I'm building an e-commerce website, I enable guest users to add products to their carts saving the cart_id in session and when they proceed to checkout, I redirect them to login as follows inside the checkout view if not request.user.is_authenticated: login_url = reverse('accounts:login') check_out_url = reverse('cart:checkout') redirect_url = "{}?next={}".format(login_url, check_out_url) return redirect(redirect_url) # checkout process here It works, however the cart_id is no longer in the session. If I don't use the next parameter and just redirect to login_url the cart_id stays in session. P.S: Same thing happens with login_required_decorator Is there a way to keep the session data intact ?