Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django user.save() not working once deployed
I have two forms on a webpage, which can be saved and this should update the user data. This works perfectly locally but once I deploy my application to Heroku the user.save() method does not work for one of the two forms. In my logs I see the following: 10.76.24.178 - - [10/Jan/2018:09:45:39 +0000] "POST /profile/edit HTTP/1.1" 500 27 "http://www.url.nl/profile/edit/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5" 2018-01-10T09:45:39.777946+00:00 heroku[router]: at=info method=POST path="/profile/edit" host=www.url.nl request_id=56c38d5d-138b-427d-9694-ac8e0dc2976f fwd="145.109.1.117" dyno=web.1 connect=0ms service=246ms status=500 bytes=234 protocol=http The method that causes this error is user.save() and this same method works on heroku for the other form and works for both forms locally. Any idea how I can resolve this or how I can get more insight into what is going wrong? -
Push rejected to herokuapp
I am trying to host my dango rest app on heroku. When i run git push heroku master I get the error log remote: -----> Python app detected remote: ! The latest version of Python 3 is python-3.6.4 (you are using python-3.6.3, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3.6.4). remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing requirements with pip remote: Collecting pkg-resources==0.0.0 (from -r /tmp/build_76cc8692e5f28e80c394427df6e4d58b/requirements.txt (line 9)) remote: Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r / tmp/build_76cc8692e5f28e80c394427df6e4d58b/requirements.txt (line 9)) (from versions: ) remote: No matching distribution found for pkg- resources==0.0.0 (from -r /tmp/build_76cc8692e5f28e80c394427df6e4d58b/requirements.txt (line 9)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to myapp. remote: To https://git.heroku.com/myapp.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/myapp.git' push is rejected by heroku. please help. -
When in run test cases then I will get this error: psycopg2.OperationalError: cursor "_django_curs_140351416325888_23" does not exist
I'm tring to run test cases I got below error. Run commond : python manage.py test Type 'yes' if you would like to try deleting the test database 'test_project_management_db', or 'no' to cancel: yes Destroying old test database for alias 'default'... Traceback (most recent call last): File "manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 62, in handle failures = test_runner.run_tests(test_labels) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/test/runner.py", line 601, in run_tests old_config = self.setup_databases() File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/test/runner.py", line 546, in setup_databases self.parallel, **kwargs File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/test/utils.py", line 187, in setup_databases serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True), File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/db/backends/base/creation.py", line 77, in create_test_db self.connection._test_serialized_contents = self.serialize_db_to_string() File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/db/backends/base/creation.py", line 121, in serialize_db_to_string serializers.serialize("json", get_objects(), indent=None, stream=out) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/serializers/__init__.py", line 129, in serialize s.serialize(queryset, **options) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/serializers/base.py", line 80, in serialize for count, obj in enumerate(queryset, start=1): File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/db/backends/base/creation.py", line 117, in get_objects for obj in queryset.iterator(): File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 880, in execute_sql cursor.close() psycopg2.OperationalError: cursor "_django_curs_140351416325888_23" does not exist -
Preparing a user registration site using django including Login for existing user
A beginner, recently started to learn Django I have gone through the basic tutorial of Django for creating a first app(POLLING) given in documentation. I wanted to create a dummy website through which I'll be able to register a new user and login an existing user and logout them after successfully logging in. I tried to use Django Documentation for this (https://docs.djangoproject.com/en/1.11/topics/auth/default/#user-objects) But I don't get how to use the info in the documentation and convert that info into my views, forms and template ?? In other words I'm just confused on how to proceed!! -
django rest framework- usrename field showing "Deleted" when related lookup
I'm using Django==1.11 and django rest framework==3.7.3 I make two models - Post and User (Post object have their own user) When I get request to Post list view (in PostViewSet), I can't see my user's username field. (It's email now) - Only I can see is "Deleted". Is it because of Django itself, or django rest framework? I searched both code in github, but I can't find any code that make username field to "Deleted". I also trying making user_email field in serializer, but it happens the same. What happened? p.s. I use allauth and django-rest-auth for accounts. But I couldn't found any code too. Below is api response and part of my code. It obviously has email, and I checked twice in db. API response for posts { "user": { "id": 3, "password": "", "last_login": null, "is_superuser": false, "created_at": "2017-12-01T16:27:41.335721+09:00", "updated_at": "2017-12-01T16:27:41.335741+09:00", "email": "Deleted", "user_type": 2, "extra": null, "is_active": true, "is_staff": false, "groups": [], "user_permissions": [] }, "title": "test", "description": "", "logo": null, "deadline": null, "slug": "test-y3jj", "created_at": "2018-01-08T10:55:06.397192+09:00", }, Post serializer class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ( "user_email", "user", "title", "description", "logo", "deadline", "slug", "created_at", ) read_only_fields = ( "id", "slug", "created_at", ) … -
HighCharts Render Annotated Queryset in Jinja2 Template
In my Jinja2 template I want to render a JavaScript array similar to this: [{ name: 'test', data: [ [Date.UTC(1970, 9, 29), 0], [Date.UTC(1970, 10, 9), 0.4], ... ] }, { name: 'Transport', data: [ [Date.UTC(1970, 10, 25), 0], ... ] }] I already managed to build a rather complex queryset in my Django code. It looks like the following: (Category.objects.filter(expense__period=p) .annotate(day=Trunc('expense__date', 'day')) .values('title', 'day') .order_by('title', 'day') .annotate(Sum('expense__amount'), Count('id'))) Which results in: TITLE DAY EXPENSE__AMOUNT__SUM ID__COUNT test 2017-12-30 00:00:00+00:00 10.00 1 test 2018-01-08 00:00:00+00:00 2.70 1 test 2018-01-09 00:00:00+00:00 62.00 2 Transport 2018-01-03 00:00:00+00:00 111.00 1 Transport 2018-01-09 00:00:00+00:00 15.00 1 Transport 2018-01-10 00:00:00+00:00 12.00 1 I am stuck at this point and look for a performant way to apply the retrieved data to my template. Any idea how to break the rows into categories/loop over the results without querying the database multiple times? My models.py is: class Period(models.Model): title = models.CharField(max_length=100) slug = AutoSlugField(populate_from='title') class Category(models.Model): title = models.CharField(max_length=100) class Expense(models.Model): period = models.ForeignKey(Period, on_delete=models.CASCADE, null=True) date = models.DateField(default=date.today) title = models.CharField(max_length=100) category = models.ForeignKey(Category, null=True) amount = MoneyField(max_digits=10, decimal_places=2, default_currency='EUR') -
LookupError: No installed app with label 'myproject' when get /admin/
i am using django'admin site, but an error occured, the error is "LookupError: No installed app with label 'myproject'" i have add myapp in installed-apps,but what is the app label with "myproject", anyone who can tell me what's going on? -
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