Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Timestamp values changing Django
The timestamp when storing in database its correct but while querying it back the value of time is changing. models.py aed = models.CharField(max_length=100) gbp = models.CharField(max_length=100) timestamp = models.DateTimeField(auto_now= False,auto_now_add=True) Database Record Values My query Values 2018-01-10 07:47:05.107542+00:00 2018-01-10 07:47:05 2018-01-10 07:49:01.873091+00:00 2018-01-10 07:49:01 2018-01-10 07:51:01.913048+00:00 2018-01-10 07:51:01 2018-01-10 07:48:01.803399+00:00 2018-01-10 07:48:01 2018-01-10 07:50:04.476807+00:00 2018-01-10 07:50:04 The Time is getting changed. My Settings.py TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True -
Django ORM proper left join
This is my model class Item(models.Model): mame = models.CharField(db_index=True, max_length=256) class ItemState(models.Model): item = models.ForeignKey(Item, related_name='states') user = models.CharField(db_index=True, max_length=256, null=True) So basically it s an Item object with a list of states ( oneToMany relation ) I want a query to get the item and its state for a given user id or state as null if there is no entries for the user in ItemState. I create this request which works qs = Item.objects.filter(Q(states__user__isnull=True) | Q(states__user=self.request.user.id)) print qs.query The states__user__isnull=True generates a left join and I didn't find an other way but the generated query is not optimal SELECT "mydb_item"."name" FROM "mydb_item" LEFT OUTER JOIN "mydb_itemstate" ON ("mydb_item"."id" = "hbp_stream_itemstate"."item_id") WHERE ("mydb_itemstate"."user" IS NULL OR "mydb_itemstate"."user" = 300183) should be SELECT "mydb_item"."name" FROM "mydb_item" LEFT OUTER JOIN "mydb_itemstate" ON ("mydb_item"."id" = "hbp_stream_itemstate"."item_id") WHERE "mydb_itemstate"."user" = 300183 -
Does Easy-Thumbnails use a "box" parameter in order to crop an image?
I'm developing a website with: Python Django Wagtail In this project there are a lot of images and all of them have an ugly yellow border. In order to remove this border I need to crop all the images sistematically. Every image has its own focal area (feature supplied by wagtail), a box that exclude the yellow border. However the standard tool for cropping, of wagtail, is useless in this situation and to achieve my goal I've decided to use easy-thumbnails. Here an example of code in which I use the focal_point of image_object to set all the parameters needed for the cropping operation: parameters = { 'size': (width, height), 'crop': True, 'detail': False, 'upscale': False, } if image_object.has_focal_point(): focal_point = image_object.get_focal_point() parameters['box'] = "%s,%s,%s,%s" % ( int(focal_point.left), int(focal_point.top), int(focal_point.right - focal_point.left), int(focal_point.bottom - focal_point.top), ) return get_thumbnailer(image_object.file).get_thumbnail(parameters, generate=True).url My question is about the "box" parameter. I can't find it on the easy thumbnails docs but I've found examples of use around internet. Can anyone tell me where I can found any reference about it? Or at least a list of all the parameters allowed with the get_thumbnail method? Thanks in advance, nifel87 -
Error when create a superUser in django
OperationalError at /admin/ no such table: auth_user Request Method: POST Request URL: http://127.0.0.1:8000/admin/ Django Version: 1.6.5 Exception Type: OperationalError Exception Value: no such table: auth_user Exception Location: C:\Users\FAHADA~1\Desktop\venv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 451 Python Executable: C:\Users\FAHADA~1\Desktop\venv\Scripts\python.exe Python Version: 2.7.14 Python Path: ['C:\Users\Fahad Aziz\Desktop\venv\src', 'C:\Windows\SYSTEM32\python27.zip', 'C:\Users\FAHADA~1\Desktop\venv\DLLs', 'C:\Users\FAHADA~1\Desktop\venv\lib', 'C:\Users\FAHADA~1\Desktop\venv\lib\plat-win', 'C:\Users\FAHADA~1\Desktop\venv\lib\lib-tk', 'C:\Users\FAHADA~1\Desktop\venv\Scripts', 'c:\python27\Lib', 'c:\python27\DLLs', 'c:\python27\Lib\lib-tk', 'C:\Users\FAHADA~1\Desktop\venv', 'C:\Users\FAHADA~1\Desktop\venv\lib\site-packages'] Server time: Wed, 10 Jan 2018 12:58:10 +0500 -
Overriding django rest auth to allow AUTO SIGNUP = False like django allauth
I have installed django-allauth and django-rest-auth. I have found that we can set SOCIALACCOUNT_AUTO_SIGNUP = False in django-allauth that is mentioned in its documentation. Its working well for website login with third party platforms. But I did not find anything regarding this django-rest-auth as according to my business requirements I need to follow the process for third party login in my rest api to allow this thing in our mobile application. But there is nothing available in its documenation about this procedure. Can anyone suggest me something to figure it out? Any kind of suggestion or help highly appreciated -
Using sqlite with Mongodb in django
I am a newbie in Django,I want to create an app where I will use SQLite for storing the login details in the table which is provided by default in Django(the table storing the admin details).Now I want to use Mongodb for storing images and provide access control of some images to particular users.I have done the SQLite part,Please help me in doing the Mongodb part,How should I proceed??? -
Django - ValueError: --enable-jpeg requested but jpeg not found, aborting
I am a beginner in Django. I am trying to create an online shop. When I tried to install Pillow using "pip install Pillow==3.0.0" in Windows command prompt, the following error occurs: ValueError: --enable-jpeg requested but jpeg not found, aborting. Rolling back uninstall of pillow How can I fix this issue? Here is the complete code of the error: running install running build running build_py creating build creating build\lib.win32-3.6 creating build\lib.win32-3.6\PIL copying PIL\BdfFontFile.py -> build\lib.win32-3.6\PIL copying PIL\BmpImagePlugin.py -> build\lib.win32-3.6\PIL copying PIL\BufrStubImagePlugin.py -> build\lib.win32-3.6\PIL copying PIL\ContainerIO.py -> build\lib.win32-3.6\PIL copying PIL\CurImagePlugin.py -> build\lib.win32-3.6\PIL copying PIL\DcxImagePlugin.py -> build\lib.win32-3.6\PIL copying PIL\EpsImagePlugin.py -> build\lib.win32-3.6\PIL copying PIL\ExifTags.py -> build\lib.win32-3.6\PIL copying PIL\features.py -> build\lib.win32-3.6\PIL copying PIL\FitsStubImagePlugin.py -> build\lib.win32-3.6\PIL copying PIL\FliImagePlugin.py -> build\lib.win32-3.6\PIL copying PIL\FontFile.py -> build\lib.win32-3.6\PIL copying PIL\FpxImagePlugin.py -> build\lib.win32-3.6\PIL copying PIL\GbrImagePlugin.py -> build\lib.win32-3.6\PIL copying PIL\GdImageFile.py -> build\lib.win32-3.6\PIL copying PIL\GifImagePlugin.py -> build\lib.win32-3.6\PIL copying PIL\GimpGradientFile.py -> build\lib.win32-3.6\PIL copying PIL\GimpPaletteFile.py -> build\lib.win32-3.6\PIL copying PIL\GribStubImagePlugin.py -> build\lib.win32-3.6\PIL copying PIL\Hdf5StubImagePlugin.py -> build\lib.win32-3.6\PIL copying PIL\IcnsImagePlugin.py -> build\lib.win32-3.6\PIL copying PIL\IcoImagePlugin.py -> build\lib.win32-3.6\PIL copying PIL\Image.py -> build\lib.win32-3.6\PIL copying PIL\ImageChops.py -> build\lib.win32-3.6\PIL copying PIL\ImageCms.py -> build\lib.win32-3.6\PIL copying PIL\ImageColor.py -> build\lib.win32-3.6\PIL copying PIL\ImageDraw.py -> build\lib.win32-3.6\PIL copying PIL\ImageDraw2.py -> build\lib.win32-3.6\PIL copying PIL\ImageEnhance.py -> build\lib.win32-3.6\PIL copying PIL\ImageFile.py -> build\lib.win32-3.6\PIL copying PIL\ImageFilter.py -> build\lib.win32-3.6\PIL copying PIL\ImageFont.py -> build\lib.win32-3.6\PIL copying … -
How to send a dictionary using AJAX GET method in django
I need to send a dictionary(its length is 31) and need to get the dictionary in Django. Jquery: $('#shift_save').click(function(){ $("#usershift tr").each(function(){ usershift={}; var userid = $(this).attr('id'); usershift['shiftmember'] = userid; $("#usershift tr#" +userid+" td").each(function(){ var shiftname = $(this).text(); var shiftday = $(this).attr('id'); usershift[shiftday] = shiftname; }); var currenturl = window.location.href; currenturl = currenturl.split("/"); year = currenturl[5]; month = currenturl[6]; url = "/roster/saveshift/"+year+"/"+month; $.get(url, {my_user_shift: usershift}, function(data){ Materialize.toast(data['status'], 8000, 'rounded'); }); }) }) Views.py: def save_mass_shift(request,year,month): try: data_json = {} user_shift = request.GET['my_user_shift'] save_user_shift(user_shift,month,year) data_json['status'] = 'Saved successfully' return HttpResponse(json.dumps(data_json),content_type="application/json") except Exception as e: data_json['status'] = str(e) print(str(e)) return HttpResponse(json.dumps(data_json),content_type="application/json") Error: Just showing the jquery dictionary name as error date dict looks like : [![enter image description here][1]][1] -
Install djcelery python in site-packages directory
I deleted the installed "djcelery" directory from site-packages. Now I am trying to install it using pip install django-celery It says requirement already satisfied: django-celery in .../lib/python2.7/site-packages, but I do not see it. Any idea on what I need to do? -
How to POST JSON Object to Django Server using Volley Library in Android
I am using volley library to Post json object to django server.I am accepting the data from user using edittext field.I want to post data in this format. { "count": 1, "next": null, "previous": null, "results": [ { "user": { "first_name": "Satyam", "last_name": "Gondhale", "username": "satyam@gmail.com", "email": "satyam@gmail.com", "groups": [], "is_active": true }, "phone": "9028571487", "address": "Pune" } ] } I am accepting fields from user are first_name,last_name,username,email,phone,addres My JSON request is of the form private void sendData() { // getDetails(); String req = "request"; String url = "http://192.168.1.106:9500/api/userprofile/"; JSONObject jsonObject = new JSONObject(); try { JSONArray jsonArray=new JSONArray(); JSONObject jsonObjectUser=new JSONObject(); jsonObjectUser.put("first_name",first_name); jsonObjectUser.put("last_name",last_name); jsonObjectUser.put("username",username); jsonObjectUser.put("email",email); JSONObject jsonObject1=new JSONObject(); jsonObject1.put("user",jsonObjectUser); jsonObject1.put("address","Pune"); jsonObject1.put("phone",phone); jsonArray.put(jsonObject1); jsonObject.put("results",jsonArray.toString()); } catch (JSONException e) { e.printStackTrace(); } JsonObjectRequest request=new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<>(); String credentials = name+":"+pass; String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); headers.put("Content-type", "application/json"); headers.put("Authorization", auth); return headers; } }; AppController.getInstance().addToRequestQueue(request,req); } } Every time I send the send the request I am getting error Bad Request … -
Django: Sort and filter rows by specific many to one value
In the provided schema I would like to sort Records by a specific Attribute of the record. I'd like to do this in native Django. Example: Query all Records (regardless of Attribute.color), but sort by Attribute.value where Attribute.color is 'red'. Obviously Records missing a 'red' Attribute can't be sorted, so they could be just interpreted as NULL or sent to the end. Each Record is guaranteed to have one or zero of an Attribute of a particular color (enforced by unique_together). Given this is a one to many relationship, a Record can have Attributes of more than` one color. class Record(Model): pass class Attribute(Model): color = CharField() # **See note below value = IntegerField() record = ForeignKey(Record) class Meta: unique_together = (('color', 'record'),) I will also need to filter Records by Attribute.value and Attribute.color as well. I'm open to changing the schema, but the schema above seems to be the simplest to represent what I need to model. How can I: Query all Records where it has an Attribute.color of 'red' and, say, an Attribute.value of 10 Query all Records and sort by the Attribute.value of the associated Attribute where Attribute.color is 'red'. ** I've simplified it above -- in … -
Using gevent in custom Django management command
I'm trying to do a hello world with gevent and a Django management command. from gevent import monkey monkey.patch_all() from django.core.management.base import BaseCommand class Command(BaseCommand): # https://docs.djangoproject.com/en/1.11/howto/custom-management-commands/ def add_arguments(self, parser): parser.add_argument( '--since', dest='since', type=int ) def handle(self, *args, **options): self.stdout.write(str(options['since'])) Without trying to use gevent or access the Database, this gives me: Traceback (most recent call last): File "./manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "env/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "env/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "env/lib/python3.6/site-packages/django/core/management/base.py", line 296, in run_from_argv connections.close_all() File "env/lib/python3.6/site-packages/django/db/utils.py", line 234, in close_all connection.close() File "env/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 221, in close self.validate_thread_sharing() File "env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 542, in validate_thread_sharing % (self.alias, self._thread_ident, thread.get_ident()) django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 140735610057536 and this is thread id 4446749960. This is with Django 1.11.4 and gevent 1.2.2. -
Django CheckboxSelectMultiple widget : render only selected data by default
Greeting, I have a manytomany field call user in my model_A model, in my form, how can I display only the list of selected data associated to the model_A by default instead of listing entire entries from the User model in my html page? my intention is to create a setting page where I can remove the user associated to a project below is my code : model.py : class model_A(models.Model): user = models.ManyToManyField(User, blank=True) form.py : class EditForm(forms.ModelForm): prefix = 'edit_form' class Meta: model = model_A fields = '__all__' widgets = {'user':forms.CheckboxSelectMultiple} html : <div class="field"> {{form.user}} </div> Any help is much appreciated thanks -
Compare fields within relationship on Django ORM
I have two models, route and stop. A route can have several stop, each stop have a name and a number. On same route, stop.number are unique. The problem: I need to search which route has two different stops and one stop.number is less than the other stop.number Consider the following models: class Route(models.Model): name = models.CharField(max_length=20) class Stop(models.Model): route = models.ForeignKey(Route) number = models.PositiveSmallIntegerField() location = models.CharField(max_length=45) And the following data: Stop table | id | route_id | number | location | |----|----------|--------|----------| | 1 | 1 | 1 | 'A' | | 2 | 1 | 2 | 'B' | | 3 | 1 | 3 | 'C' | | 4 | 2 | 1 | 'C' | | 5 | 2 | 2 | 'B' | | 6 | 2 | 3 | 'A' | In example: Given two locations 'A' and 'B', search which routes have both location and A.number is less than B.number With the previous data, it should match route id 1 and not route id 2 On raw SQL, this works with a single query: SELECT `route`.id FROM `route` LEFT JOIN `stop` stop_from ON stop_from.`route_id` = `route`.`id` LEFT JOIN `stop` stop_to ON stop_to.`route_id` … -
"File not found" using manage.py with pytest-django
I have a Django project in which certain environment variables are set in manage.py which later serve as the values defined in settings.py. Therefore, in order to run pytest-django, I'd like to run manage.py first. I'm trying to follow the instructions in https://pytest-django.readthedocs.io/en/latest/faq.html#how-can-i-use-manage-py-test-with-pytest-django, but I'm running into an unexpected error. I have the following directory structure: . ├── lucy │ ├── settings │ ├── base.py │ ├── development.py │ ├── production.py │ └── staging.py │ ├── staticfiles │ ├── urls.py │ └── wsgi.py ├── lucy_web │ ├── __init__.py │ ├── actions.py │ ├── admin │ ├── apps.py │ ├── fixtures │ ├── forms │ ├── lib │ ├── management │ ├── migrations │ ├── models │ ├── runner.py │ ├── serializers.py │ ├── static │ ├── templates │ ├── templatetags │ ├── tests │ ├── urls.py │ └── views ├── manage.py ├── pytest.ini The contents of runner.py are taken exactly from the FAQ: class PytestTestRunner(object): """Runs pytest to discover and run tests.""" def __init__(self, verbosity=1, failfast=False, keepdb=False, **kwargs): self.verbosity = verbosity self.failfast = failfast self.keepdb = keepdb def run_tests(self, test_labels): """Run pytest and return the exitcode. It translates some of Django's test command option to pytest's. """ import pytest argv … -
why do I bind to ip 0 failed?
I know if I use IP 0, I will bind to all public IP in my local network.But actually when I run python manage.py runserver 0:8000, it says: [Errno 11004],get addrinfo failed. But in the past, I can ran it successfully. I don't know how to solve it. -
Django - query filtering - Finding IP's equal to or between to IP's
I'm trying to find an IP in a table. My table has two columns, a startIp and and endIp. Sometimes just the start Ip is given (in this case only an IP matching that IP is the valid one). Other times, a range is given. In that case any IP between the start and the end is valid. Is it possible to create that query in one line using Django filters or do I need to query for the ones with a null endIP matching the exact startIp then join those results with the ones equal to and greater than the startIP and less then to equal to the endIP? -
Django + sass styling
So I'm integrating sass/scss into an existing django project, and am currently facing an issue with using django syntax in sass, and it's preventing watching/compiling of the .scss into .css. This is the line/django method that's causing trouble: background-image: url("{% static "onepage/img/bglight.png" &}"); Any help would be appreciated! Gonzo -
Error running server django
I have moved my django project to another new machine driven by virtualBox. I have installed everything I need to run my project. Unfortunately, when I try to run it I got an error saying something that is not possible to find all project required paths. my path project is: path: C:\users\Dev\Documents\GitHub\Python\django\local_sites --local_sites --manage.py ----local_sites ------forms ------models ------urls ------etc. When, I run in the local_sites where is located the manage.py the runserver I got the error below: I when thru the file urls.py to check out the line 17 , but I dont understand really how to figure it out I appreciate the help you can give me. thanks so much -
Django - Trouble adding User to User Group with custom User Model
Previously, I have been using the default Django user model and have been adding users to specific user groups when they register with no problem using this code in my views.py: user.save() user.groups.add(Group.objects.get(name='customers')) However, I have now changed to a custom user model so I can remove the 'username' field in my register form and now this code no longer works. This error message is being thrown when new users try to register: 'User' object has no attribute 'groups' I have searched but can't find an answer to this question. I am very new to working on the backend with Django so please be very descriptive in your answers (i.e where I need to put the code you suggest, models.py/views.py/forms.py etc). Any help would be much appreciated! -
Can't Import Django using Python3 on macOS Sierra
Have both versions of Python (Legacy 2.7.10 and 3.6.2) installed on macOS Sierra. Installed pip using the following steps. Downloaded it using curl: curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py Installed pip it by running the installer script: sudo python get-pip.py Checked for any upgrades / updates for pip: sudo pip install -U pip Installed django 1.11: sudo pip install django==1.11 When I run python (legacy): python Python 2.7.10 (default, Feb 7 2017, 00:08:15) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> print(django.get_version()) 1.11 However, when trying it using python3: python3 Python 3.6.2 (v3.6.2:5fd33b5926, Jul 16 2017, 20:11:06) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import django Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'django' Note: I followed a different tutorial and got python3 working with django 1.11 using virtualenv - please don't suggest this as I am new to the python world and just want to use python3 / django 1.11 in a non-virtual environment - I just want have it working like the legacy python interpreter … -
django-taggit - display all tags based on date vlog published
Using django-taggit, I can display all the tags associated for a test vlog. I have vlogs stored in the db that are not yet released to the public (only displayed after a certain date), so that I can store numerous vlog details in the db and then release each individual vlog on a certain day (say Tuesday of each week). This means that the display all tags will include tags for vlog entries that are not yet displayed in the vlog. How can I only display the tags and the count for vlog entries where the vlog_date_published is greater than now? Here is my models code: from taggit.managers import TaggableManager class VlogDetails(models.Model): .... vlog_date_published = models.DateField(null=False, blank=False, default=datetime.now, help_text='The date the vlog video will be made public.') vlog_tags = TaggableManager(blank=True, help_text='To make a new tag, add a comma after the new tag name.') .... Here is the display all tags template code: {% get_taglist as vlog_tags %} {% for tag in vlog_tags %} {% if tag.num_times > 0 %} <a class='u-tags-v1 g-color-grey g-bg-grey-opacity-0_1 g-bg-grey--hover g-color-white--hover g-rounded-50 g-py-4 g-px-15' href="{% url 'vlog_tag' tag %}" hreflang="en" rel="tooltip" title="{% blocktrans %}Display all vlog entries containing this tag.{% endblocktrans %}"><i class="fa fa-tag icon_padding"></i> {{tag}} … -
Django model validate two ArrayFields have the same length
Given two ArrayField's, how you can validate the length of both are always the same? from django.contrib.postgres.fields import ArrayField class MyModel(models.Model): x = ArrayField(models.FloatField()) y = ArrayField(models.FloatField()) I know you can specific the ArrayField parameter to be the same on both, but what if I want the size to be variable for each record? -
Django - Creating a Custom Template Tag to show Model Name
I have a model: class Survey(models.Model): name = models.CharField(max_length = 200) def __str__(self): return self.name And in my template I want to show the name of the current Survey model: <h1> {{survey.name |name}} </h1> I'm using a custom template tag/filter to display that name; however, it is showing as 'str' instead of the name of the current Survey model. Here is the filter code: from django import template register = template.Library() @register.filter def name(value): return value.__class__.__name__ What am I doing wrong here? -
Windows 10 VS Code running Virtualenv. I am getting No module named django.__main__ when I checked the Django version
Running Windows 10 VS Code. I installed python 2.7 I also Installed virtualenv. I am running a virtual environment and pip install Django version 1.4 I ran the following command in my terminal python -m django version I get the following error: C:\Proyectos\virtual\webapp\Scripts\python.exe: No module named django.main; 'django' is a package and cannot be directly executed I cannot start any Django projects. Pip freeze shows it is installed PS C:\Proyectos\virtual\webapp> pip freeze Django==1.4 ./lib/site-packages shows the module directory