Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Elastic beanstalk Django admin css not loading
Using Django 1.11.6, python 3.6.2 Short summary: static files are collected correctly on server but only one app's sub directory is served, the admin's static files return as 404. Running the local development server everything works as expected. After deploying to my EB instance none of the static files for the admin app load. If i run eb ssh and look around on the server I can see the collected static folder, along with all the different app's subfolders. The files are all there where I'd expect. The links produced on the django front-end map in a sensible way to these paths, it's just that anything in static/admin returns a 404, while the files in static/entities work fine. Testing paths on the front end: /static/admin/css/base.css (404) /static/entities/style.css (works) On server, all collected files in static look fine: /opt/python/current/app/static/admin/css /opt/python/current/app/static/entities No idea why one sub directory is server fine but the others return 404s. From my django.config option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "spf.settings" "PYTHONPATH": "/opt/python/current/app:$PYTHONPATH" "ALLOWED_HOSTS": ".elasticbeanstalk.com" "aws:elasticbeanstalk:container:python": WSGIPath: spf/wsgi.py NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "static/" ... 03_collectstatic: command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput" Running the collectstatic command locally produces the correct static folder with the same subdirectories for each … -
Django queryset, order by dynamic criteria based on external value
I need to scramble order of a queryset, based on an external value. The order must be replicable. For example (with sorted, but if it's possible inside the queryset is better): value = 1 sorted(MyModel.objects.all(), lambda n, value: < what to put here?>) For example, If MyModel has 5 objects, I think something like: value | order 1 | 1, 4, 2, 5, 3 2 | 4, 1, 5, 3, 2 3 | 5, 1, 3, 2, 4 -
Django prefetch_related and select_related
I am wondering about the behaviour of prefetch_related() and select_related(). If I do something like Model.objects.filter(...).prefetch_related(), I notice that there are much less database queries occurring. So my initial guess is that, if one does not specify the needed look-ups in prefetch_related(), it will automatically go through all of the model fields and do the needed job. However, I cannot find any reference to it on the web, which seems pretty strange to me. Is my guess correct or am I missing something? -
DRF: Creating a list in a field
I am new to DRF and I want to create a field that can take multiple value. I tried using StringListField as: in my serializers.py,: class StringListField(serializers.ListField): child = serializers.CharField() class XYZSerializer(serializers.ModelSerializer): branch = StringListField(max_length=20) class Meta: model = Api fields = ('id', 'notice_name', 'notice_desc', 'notice_author', 'notice_valid_till', 'notice_publish_date','year', 'branch') views.py class AddNotice(APIView): permission_class = (IsAuthenticated,) serializer_class = AddNoticeSerializer def post(self, request, format=None): data = request.data serializer = AddNoticeSerializer(data=data) if serializer.is_valid(raise_exception=True): serializer.save() new_data = serializer.data return Response(new_data) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) But as soon as I post it gives something like this error: File "/home/yathartha/.local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/yathartha/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/yathartha/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/yathartha/.local/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/yathartha/.local/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/yathartha/.local/lib/python3.5/site-packages/rest_framework/views.py", line 489, in dispatch response = self.handle_exception(exc) File "/home/yathartha/.local/lib/python3.5/site-packages/rest_framework/views.py", line 449, in handle_exception self.raise_uncaught_exception(exc) File "/home/yathartha/.local/lib/python3.5/site-packages/rest_framework/views.py", line 486, in dispatch response = handler(request, *args, **kwargs) File "/home/yathartha/Desktop/Desktop/notices-api/api/views.py", line 28, in post serializer.save() File "/home/yathartha/.local/lib/python3.5/site-packages/rest_framework/serializers.py", line 215, in save self.instance = self.create(validated_data) File "/home/yathartha/Desktop/Desktop/notices-api/api/Serializers.py", line 19, in create return Api.objects.create(**validated_data) File "/home/yathartha/.local/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, … -
How to get extension of file
I am trying to get mimetype from decoded string. I sent base64 string of a xls file, This is my code: def save_file(request_data, id=None): """ """ data = base64.b64decode(request_data.get('file')) mime = magic.Magic(mime=True) content_type = mime.from_buffer(data) print(content_type) print(guess_extension(content_type.decode("utf-8"))) Output: b'application/octet-stream' Unable to get file extensions. Does anyone know how to get file extension from base64 string. -
Generating single hash of CSV file
I have a service that received CSV files with size ranging from MBs to GBs and I need to generate a single hash against all contents of a file. Is there an optimized solution for this that doesn't require me to read the file line by line and concatenate each line in a string and then generate a hash of that string? That method would take too much time for a file that can contain millions of rows. Any help will be appreciated. By the way, I will be using SHA256 from hashlib for hashing. -
Datatables uncaught reference error with django
Hi i'm using datatable in a django/python app, i have an index page that load a list from a DB and put it in a datatable. Since this morning i have an error that start with : TypeError : C is undefined (that seem to point on the line where i define the datatable) and then of course this error pop everytime the setInterval is called on this tab : ReferenceError : oTable is undefined My view : def index(request): listOPT = [] Data = [] fluxManagerState = settings.FLUX_MANAGER_STATE cursor = connections['site'].cursor() try: cursor.execute("{CALL SP_webGET_RESUME_MVT_INIT_ACTIF}") mouvements = dictfetchall(cursor) finally: cursor.close() return render(request, 'index.html', locals()) Function that works with ajax to refresh the datatable : def listMVTinit(request): cursor = connections['site'].cursor() try: cursor.execute("{CALL SP_webGET_RESUME_MVT_INIT_ACTIF}") data = dictfetchall(cursor) finally: cursor.close() return HttpResponse(json.dumps(data), content_type = "application/json") My template : {% load static %} <!doctype html> <html> <head> <meta charset="utf-8"> <title>Liste Mouvement initiaux</title> <meta name="generator" content="WYSIWYG Web Builder 12 - http://www.wysiwygwebbuilder.com"> <link href="{% static 'css/Gestion_Mouvements.css' %}" rel="stylesheet"> <link href="{% static 'css/index.css' %}" rel="stylesheet"> <link href="{% static 'css/base/jquery-ui.min.css' %}" media="all" rel="stylesheet"> <link href="{% static 'css/jquery.dataTables.min.css' %}" media="all" rel="stylesheet"> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet" media="all"> <link href="{% static 'css//bootstrap-datetimepicker.min.css' %}" media="all" rel="stylesheet"> <script src="{% static 'js/jquery-1.12.4.min.js' … -
NoReverseMatch django template url
Sory for my english. I can understand why my code doesnt work. Before it work, but now, i run server, test, and this code not work. I have url when user is registration, i send him activation email, like this: def send_activation_email(serializer, request, user): current_site = get_current_site(request) message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) mail_subject = 'Activate your blog account.' to_email = serializer.data['email'] email = EmailMessage(mail_subject, message, to=[to_email]) email.send() acc_active_email.html {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} and my url file . . url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate_account, name='activate'), . . but i have error: Exception Type: NoReverseMatch Exception Value: Reverse for 'activate' with keyword arguments '{'uidb64': b'NDM', 'token': '4qz-8f770502bd8b02786da9'}' not found. 1 pattern(s) tried: ['activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] highlights this line http://{{ domain }}{% url 'activate' uidb64=uid token=token %} -
One view for multiple sub-domains using django-hosts
I need to have multiple sub domains for my project. Each sub domain represents some company. For example: company1.myproject.io, company2.myproject.io. I used django-hosts library to set up sub domains. hosts file: 127.0.0.1 localhost 127.0.0.1 myproject.io 127.0.0.1 www.myproject.io 127.0.0.1 company1.myproject.io 127.0.0.1 company2.myproject.io settings.py: ROOT_URLCONF = 'core.urls' ROOT_HOSTCONF = 'core.hosts' DEFAULT_HOST = 'www' DEFAULT_REDIRECT_URL = "http://www.myproject.io:8000" core/hosts.py: from hostsconf import urls as redirect_urls host_patterns = [ host(r'www', settings.ROOT_URLCONF, name='www'), host(r'(?!www).*', redirect_urls, name='wildcard'), ] hostsconf/urls.py: from .views import wildcard_redirect urlpatterns = [ url(r'^(?P<path>.*)', wildcard_redirect) ] hostsconf/views.py: DEFAULT_REDIRECT_URL = getattr(settings, "DEFAULT_REDIRECT_URL", "http://www.myproject.io:8000") def wildcard_redirect(request, path=None): new_url = DEFAULT_REDIRECT_URL if path is not None: new_url = DEFAULT_REDIRECT_URL + "/" + path return HttpResponseRedirect(new_url) I have a few problems now: When I go to myproject.io it succesfully redirects me to the www.myproject.io. But when I go to company1.myproject.io I got an Invalid HTTP_HOST header: 'company1.myproject.io:8000'. You may need to add u'company1.myproject.io' to ALLOWED_HOSTS Do I really need each time add new host to ALLOWED_HOSTS when I got new sub domain or I am doing something wrong? How to implement a single view for all sub-domains where will by dynamic context for each company. Basically I need to make queries into the db by sub domain name. … -
After upgrade to Django 1.11 site doesn't work in Chrome
I face strange problem. When running django development server I cant display pages in Chrome but I can in FireFox and MsEdge. The server returns 200 response, so page should be displayed. I did not touch any options related to security. Chrome stucks on spinning wheel, and no other information is available, no timeout, no errors. Django 1.11.7 here. Do not hasitate to comment as it could lead us to an answer. -
Is there 'imagecreatefromjpeg' function in python like in PHP ?
I'm trying to add a cover profile into my web application that could be repositionned .. I found a useful tutorial in this link The problem is that the server side code is in PHP and I'm working with PYTHON and Django . I can't find some functions used in PHP like imagecreatefromjpeg , imageSY , imagedestroy ...etc.. Any help ? -
check existing template in mandrill django
in my database, I stored template info. now I need to check my template is existing in mandrill or not. I read documentaion of mandrill. but I could not check it. could anyone suggest any way to check my template is existing in mandrill or not? -
response['Content-Disposition'] = 'attachment;' in django not downloading the file
filename = "/filepath/in/server" with open(filename, 'rb') as f: response = HttpResponse(f.read(), content_type='application/octet-stream') response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment; filename=filename' print response return response`enter code here` //Clicking on button in my web application should download and save the file from server to my desktop. My html code contains only the button and onclick function(which submits the form and invokes POST). The Post script is written in views.py. The above code is also written in views.py but clicking on the button doesn't download the file as attachment. I can see response content printed in server side. -
Why is my CSS in pythonanywhere taking a day to load?
I change a CSS file, run collectstatic but nothing happens - the app keeps the previous styling, even though that CSS no longer exists anywhere in my files. I got frustrated and gave up yesterday, and found that this morning it had updated, but the initial problem persists. Has anyone else experienced this? Is it just an issue with pythonanywhere or might there be a problem in my code? -
Auto Fill User In Django Form
In my project as soon as user signup it is redirected to update view where he has to fill this information.Since the user has also logged in automatically after signup I want that user field to be filled automatically and can't be edited. models.py class Userpro(models.Model): user = models.OneToOneField(User) dob = models.DateField(default=datetime.date.today) country = models.CharField(max_length=50, default='') qualification = models.CharField(max_length=10, choices=CHO, default='No') university = models.CharField(max_length=100, default='') location = models.CharField(max_length=100, default='') def __str__(self): return str(self.user) forms.py class UserProForm(forms.ModelForm): class Meta: model = Userpro fields = '__all__' views.py def update(request): if request.method == 'POST': form = UserProForm(request.POST or None) if form.is_valid(): form.save() return redirect('/') else: redirect('/') else: form = UserProForm() return render(request, 'app/update.html', {'form': form}) All the required libraries are imported. -
I am unable to deploy my django app on the heroku .How to solve?
So I am trying to deploy my django app over heroku since 3 hrs . Went through many tutorials but still I am unable to make it work . The app is working fine locally Even the foreman app is running the app fine . But I am unable to make it work on heroku .It is deployed successfully but fails to works. Kindly help. Directory and files are in following manner The directories and files are made like that. The codes are on github : https://github.com/Atif8Ted/test_blog This is first try on heroku . Kindly be gentle. -
Django website on VPS with WHM CPanel
What's the difference between mod_wsgi and mod_python. In order to publish django websites on VPS, which one should I install on VPS? -
crispy forms + Bootstrap3: bad position of error field with input-group-addon
When using a input-group-addon, when there's an error, the span element of the error is wrapped by the input-group-addon: the html: <div class="controls col-md-6 input-group"> <input name="name" value="English" class="lang_name dropdown-toggle dropdowntogglewidget form-control form-control-danger" maxlength="40" required="" id="id_name" type="text"> <span role="button" class=" input-group-addon dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="caret"></span></span> <span id="error_1_id_name" class="help-block"><strong>Languages with this Name already exists.</strong></span> </div> my forms.py: class LanguagesForm(forms.ModelForm): ... def __init__(self, *args, **kwargs): super(LanguagesForm, self).__init__(*args,**kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal text_detail' self.helper.label_class = 'col-md-3' self.helper.field_class = 'col-md-6 input-group' ... I guess it's the same problem than Bootstrap 3 form using input-group-addon wrapping error labels with Jquery Validate but here, we have less option... -
How do I prepopulate an inline formset that is purely ImageFields?
I have two models: Profile and CredentialImage. I have implemented inlineformsets to allow the Profile to upload up to 5 maximum images(CredentialImage). Currently, the images save to the database but they will not pre-populate when I revisit the update form, thus allowing the user to upload an unlimited amount of photos 5 at a time. Ideally, the same images saved to the database would pre-populate on the form as to limit the Profile to own and edit only 5 photos at a time. From my understanding, I need to pass in the object to the page to pre-populate information, and I believe I'm doing just that by defining get_object. Here are the two models: class Profile(models.Model): ... def get_absolute_url(self): return reverse("profile:profile_detail", kwargs={"username": self.user}) class CredentialImage(models.Model): profile = models.ForeignKey(Profile, default=None, related_name='credentialimage') image = models.ImageField(upload_to=credential_photo_upload_loc) The modelforms + initialization of the inlineformset_factory: from django.forms.models import inlineformset_factory class ProfileUpdateForm(ModelForm): class Meta: model = Profile fields = [ "introduction", "biography", ] class CredentialImageForm(ModelForm): image = ImageField() class Meta: model = CredentialImage fields = ['image', ] CredentialImageFormSet = inlineformset_factory(Profile, CredentialImage, fields=('image', ), extra=4, max_num=4) A class-based UpdateView for updating a Profile: class ProfileUpdateView(LoginRequiredMixin, UpdateView): form_class = ProfileUpdateForm template_name = 'profile/profile_edit.html' def get_context_data(self, **kwargs): context = … -
Can I execute makemigrations and migrate command in my PyCharm?
I changed my project interpreter to python 3.5, and I still has used to in the terminal to execute the : python manage.py makemigrations python manage.py migrate Because I have changed the project interpreter to python 3.5, I must use python3 manage.py migrate to realize that, sometimes I will write python rather than python3. So is there a method in PyCharm to realize that? -
django TypeError: 'NoneType' object does not support item assignment
class HomeView(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) e = [{'year': '2017'}, {'year': '2016'}, {'year': '2015'}] context['e'] = e return context Trying to set the context variable by means of "hard code" results me in TypeError: 'NoneType' object does not support item assignment I am hardcoding the value but it says none is assigned. Doesn't make sense to me.Any clues? -
Displaying two related models in a single get() request
I have two models that are related to each other with user_id, now I want to have a get request in which I will have fields from both the tables. How to make this possible? I guess it would be possible with foreign key, but how do I implement it. Two models look like: model1 class Account(AbstractBaseUser): fullname = models.CharField(max_length=100, blank=True) username = models.CharField(unique=True, max_length=50) email = models.EmailField(unique=True) phonenumber = models.IntegerField(null=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) is_admin = models.BooleanField(default=False) objects = AccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] models2 class Profile(models.Model): User = get_user_model() branch = models.CharField(max_length=20, null=True) year = models.IntegerField(null=True) image = models.ImageField(upload_to="accounts/images/", null=True, blank=True) user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=False, null=True ) I want to display particular user details based on who is logged in at the moment. My get request looks something like this: def get(self, request, format=None): current_user = request.user acc = Account.objects.filter(pk=current_user.pk) serializer = AccountSerializer(acc, many=True) return Response(serializer.data) But this will show only data as of Account model, I want data of Profile model too. How do I do it? -
Django REST framework custom format for all out responses
In my project I use DRF as backend and Angular as frontend. Django==1.10 djangorestframework==3.7.1 I need all responses from DRF to be in the following format. { "status": "", // 200,400,.....etc "error": "", // True, False "data": [], // data "message": "" // Success messages } for this i have written a custom viewset and overridden the functions list, detail, create, update class ResponseModelViewSet(viewsets.ModelViewSet): def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) custom_data = { "status": True, "error": False, "message": 'message', "data": serializer.data } return Response(custom_data) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) custom_data = { "status": True, "error": False, "message": 'message', "data": serializer.data } return Response(custom_data, status=status.HTTP_201_CREATED, headers=headers) def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) custom_data = { "status": True, "error": False, "message": 'message', "data": serializer.data } return Response(custom_data) def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) if getattr(instance, '_prefetched_objects_cache', None): # If 'prefetch_related' has been applied to a queryset, we need to # forcibly invalidate the prefetch cache on … -
Error WindowsError: [Error 193] %1 is not a valid Win32 application with gdal - GeoDjango
I installed GEODjango with install gdal in Window. But it came error: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal201", "gdal20", "gdal111", "g dal110", "gdal19"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. After that, I config GDAL_LIBRARY_PATH by insert this line to setting.py: GDAL_LIBRARY_PATH = 'C:\Users\User\Desktop\FeedGit\env\Lib\site-packages\osgeo\gdal.py' It came to this error: File "C:\Users\User\Desktop\FeedGit\env\lib\site-packages\django\contrib\gis\gdal\libgdal.py", line 49, in <module> lgdal = CDLL(lib_path) File "c:\python27\Lib\ctypes\__init__.py", line 366, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 193] %1 is not a valid Win32 application I think this is a mistake between Window64 bit and Window32bit. This is my python version: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. My computer is running Window 7 64bit. How can I fix this error, please help me. I really need GeoDjango to mapping many fields on my project. Thanks in advance! -
How to check if a queryset is empty?
Pagination code: try: page = paginator.page(page_number) print(page.object_list) So the following output is the result of print(page.object_list) for my pagination: <QuerySet [<Comment: I can't believe it's happeinig>, <Comment: Just trying to fill up the comments>, <Comment: Another one!>, <Comment: Evenmore noe>, <Comment: Something>, <Comment: Lol>, <Comment: Are comments showing up?>, <Comment: Great for the economy.>, <Comment: honestly>, <Comment: Even though the the onlyEven though the only one to udnertstnaf!>]> <QuerySet [<Comment: Yeah it's crazy how fast aswell. It's very awesome how it's doing atm. >]> <QuerySet []> <QuerySet [<Comment: Sure>, <Comment: No worries>]> <QuerySet []> <QuerySet []> <QuerySet [<Comment: attempt 2!>]> <QuerySet [<Comment: Attempt 3!>]> <QuerySet []> <QuerySet [<Comment: 12>]> <QuerySet []> <QuerySet [<Comment: Somewhere?>]> <QuerySet []> <QuerySet [<Comment: lol>]> <QuerySet []> <QuerySet [<Comment: 12>]> <QuerySet []> As you can see I have empty querysets, and these are causing errors in my code. I therefore would like to iterate over these querysets and spot the empty ones. I tried to add this for loop: for i in page.object_list: if len(i) < 0: but I get an error: TypeError at /news/11/ object of type 'Comment' has no len() Any help appreciated.