Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ForeignKey filter issue
Is there anyway to add filter on django foreignkey field. class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category) image = models.ImageField() description = models.TextField() def __str__(self): return self.name -
Django Content Types - Can the value in ContentType for a modal change if modals are added or removed from application?
While running test cases for Django, initially the value for a modal in ContentType is different than what I come across in test case. Any thoughts? -
Change field from date to datetime
I need to change a models field from DateFieldto DateTimeField. The migrations generated by ./manage.py makemigrations only change the column type from date to datetime, but they don't migrate existing data. For example when I change the following model class Post(models.Model): time = models.DateField() to class Post(models.Model): time = models.DateTimeField() the values of the time column will still be dates (like 2016-12-21) in the database. As a result, post.time will be None for every Post. Instead, each object like datetime.date(2016, 12, 21) should become datetime.datetime(2016, 12, 21, 0, 0) automatically. What's the best way to solve this? -
Making a calculation in django based on the input from another model but experiencing errors. Can someone please help me out on this one
I'm trying to subtract an amount from the fee that is in the Fees Model and a foreign key to Payment Model. I'm do the calculation below to automatically get the balance upon save but experiencing unsupported error. The return value from Fees Model is a total amount to be paid. Here's the error I'm getting: unsupported operand type(s) for -: 'Fees' and 'int' class Payment(models.Model): fee = models.ForeignKey( Fees ) installment = models.CharField( _('Installment'), max_length=30, choices=INSTALLMENT_CHOICES, default=u' ', null=False, blank=False ) amount = models.IntegerField( _('Amount'), null=False, blank=False ) balance = models.IntegerField( _('Balance'), null=True, blank=True ) def save(self, *args, **kwargs): self.balance = self.fee - self.amount super(Payment, self).save(*args, **kwargs) -
I'm getting an error while creating Python Django Project
C:\Python27\Scripts>django-admin startproject python_tutorial Traceback (most recent call last): File "c:\python27\lib\runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "c:\python27\lib\runpy.py", line 72, in _run_code exec code in run_globals File "C:\Python27\Scripts\django-admin.exe\__main__.py", line 9, in <module> File "c:\python27\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "c:\python27\lib\site-packages\django\core\management\__init__.py", line 316, in execute settings.INSTALLED_APPS File "c:\python27\lib\site-packages\django\conf\__init__.py", line 53, in __getattr__ self._setup(name) File "c:\python27\lib\site-packages\django\conf\__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "c:\python27\lib\site-packages\django\conf\__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "c:\python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) ImportError: Import by filename is not supported. Can someone please suggest what to do? -
Keep the original value from pandas dataframe
I have a csv file and it is in the following format: A, -0.1234540756893158 B, 0.123450496711731 C, 0.12345994493484497 D, -0.12345484461784363 E, 12344656.0 F, -1234648.0 G, 12342316.0 H, 12552.37109375 I, 16247.228515625 J, -12.123796875 K, 1081104201 L, 123 I am reading it with: df = pd.read_csv('/output.csv', header=None, names=['c1','c2']) Then I will get the interesting indexes as follows, and save it in a csv: my_list = [0,1,2,3,4,5,6,7,8,9,10,11] df[df.index.isin(my_list)].to_csv(thefile2, sep=',', header=None, index = False) But when I check the content of "thefile2", I get such an output: A,-0.123454075689 B,0.123450496712 C,0.123459944935 D,-0.123454844618 E,12344656.0 F,-1234648.0 G,12342316.0 H,12552.3710938 I,16247.2285156 J,-12.123797 K,1081104201.0 L,123.0 As it can be seen, values for A, B, C, D, H, I and J are rounded up, and K and L are having a 0 at the end. in the output file. My question is, how can I get the original values in the second column? -
Django datetime.datetime to Decimal is not supported migrations
Below is the model and the error that is coming up when I try to migrate. I am using django 1.10 and my database is empty when I try to migrate. Model: from django.db import models class OrderEntry(models.Model): quote_num = models.CharField(max_length=50, primary_key=True) customer = models.CharField(max_length=100) cust_po = models.CharField(max_length=50) pdf = models.CharField(max_length=500) datetime = models.DateTimeField(auto_now=True, editable=True, null=True) class Items(models.Model): quote_num = models.CharField(max_length=50, primary_key=True) item_1 = models.CharField(max_length=100) item_2 = models.CharField(max_length=100) item_3 = models.CharField(max_length=100) item_4 = models.CharField(max_length=100) item_5 = models.CharField(max_length=100) item_6 = models.CharField(max_length=100) item_7 = models.CharField(max_length=100) item_8 = models.CharField(max_length=100) item_9 = models.CharField(max_length=100) item_10 = models.CharField(max_length=100) class ItemDetails(models.Model): item = models.CharField(max_length=100, primary_key=True) quote_num = models.CharField(max_length=50) quan = models.CharField(max_length=100) desc = models.TextField(max_length=1000) price = models.DecimalField(max_digits=10, decimal_places=2, default=0, null=True) Error: C:\Users\Evan\Desktop\webapp>py manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, orders, sessions Running migrations: Applying orders.0013_itemdetails_price...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Evan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\Evan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Evan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Evan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 345, in execute output = self.handle(*args, **options) File "C:\Users\Evan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle fake_initial=fake_initial, File "C:\Users\Evan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Evan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\executor.py", line 145, in β¦ -
Get instances of active filters in django-filter
I am using django-rest-framework 3.5.3 and django-filter 1.0.1 to filter items. When for instance a ProductFilter is defined: import django_filters from django_filters.rest_framework import FilterSet from myapp.models import Product class ProductFilter(FilterSet): class Meta: model = Product fields = ['category', 'brand'] and this filter is used in a view: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() filter_backends = (DjangoFilterBackend,) filter_class = ProductFilter then I can successfully filter products by category and/or brand: /products/?category=category1&brand=brand2 Now what would be the easiest way to retrieve instances of the active filters, so in this example a Category (pk=category1) and a Brand (pk=brand2)? I could not find existing methods to achieve this. Do I have to parse the GET-params myself and retrieve the objects from the database? -
handle multiple request parallely by using Django
I want to handle multiple request at a same time. suppose after coming 1st request this function will execute => def testFun(): print('Starting') while True: time.sleep(3) print('looping') time.sleep(3) print('3 Seconds Later') this is a infinite loop. after executing the 1st request, response will be sent. At that time if I send another request while executing 1st request then server will automatically accept the request and both request will work intermediately(will not take in queue) and after executing the testFun() then server will send response to the 2nd request. Like this parallely it can handle N number of request. I want to make such a server that will accept multiple request parallely by using Django. how i will do this?? -
Reported coverage on console is different from the HTML report
So, I'm using the coverage.py console utility, as follows (on a django project): $ coverage run --source='.' --omit='*__init__*, *manage.py*' ./manage.py test And as a final result on the coverage reported right there on screen, I get 27%, but then I create the HTML report like this: $ coverage html -d ./folder And there I get an 8% Any idea why I'm getting different numbers for what should be the same report? Thanks -
Custom parameters in django form fields
I want to store a parameter in form fields for checking rendering part. Use case: There are full-width and haft-width inputs in form and need identifier for that. Using field id or label is not an option as it will be used in all forms. Creating custom fields (CharField, EmailField, ModelChoiceField and etc.) is also not an option as there are different form types in system and having custom for all of them will look weird. What will be best option for such use case? Code example: field_name = forms.CharField( label="Label", required=True, widget=forms.TextInput(attrs={}) ) In template: field.label, field.field.required, field.help_text, field.errors, field PS. Widget attrs are added to input field automatically, but in that case custom class parameter will be added to div element before input and that is reason for not using widget attributes. -
Adding contents of a queryset to a list in Django/Python
I'm pretty new to Django. I'm trying to iterate over my queryset and add the field which happens to be called 'id' of each to a new list. My end result should be a list looking something like this (for example): [1, 2, 3, 7, 10] My code looks like this: my_list = [] for foo in bar: number = foo.id my_list += number I'm getting this error: TypeError: 'long' object is not iterable The type of foo.id is long I have tried changing the foo.id to an int or str using: number = str(number) Have also tried the solution here (I'm using Python 2.7): TypeError: 'long' object is not iterable but I get this: AttributeError: 'QuerySet' object has no attribute 'iteritems' Any help much appreciated! -
Django-Registration-Redux - retrieve lost username
Django-registration-redux provides functionality to reset or change your password but both of these operations behave under the assumption that the user still remembers their username. What happens if a user has forgotten their username and needs to retrieve it somehow (ie: have it emailed to them). The reset password functionality prompts for your email address. The user enters their email address and then clicks the confirmation link that is emailed to them. At that point they enter their new password. But they still can't log on if they have forgotten their username. Regarding the change password functionality, you need to be logged in first so once again,...what if the user has forgotten their username? Ideally I would far prefer not to use usernames. They are old fashioned and unnecessary to use as a primary authentication method. Most sites simply use an email address + password these days. Unfortunately my django site has a lot of integration with the default user model so trying to create a custom user model at this stage is not ideal. -
Django : Cannot import name <ModelName>
Hi guys am having an issue importing a model, i think is something related to circular imports.i keep getting the error cannot import name PurchaseOrder despite having this model my models are class Project(MAIDEAModel): office = models.ForeignKey( Office, related_name='projects', help_text=_('Office which the project is under') ) name = models.CharField( _("Name"), max_length=50, validators=[MinLengthValidator(5), validate_sluggable], help_text=_('Name of the project') ) status = models.IntegerField( _("Status"), choices=STATUS, default=STATUS_ACTIVE, help_text=_('Activity status of the Project') ) type = models.IntegerField( _("Type"), choices=PROJECT_TYPES, help_text=_('Type of project') class PurchaseOrder(MAIDEAModel): """ This model holds PO numbers for a project """ project = models.ForeignKey( Project, related_name='purchase_orders', ) number = models.BigIntegerField( _('PO Number'), validators=[MaxValueValidator(9999999999)] ) So when i import from maidea.apps.somalia.models import Project, PurchaseOrder i get an error ImportError Traceback (most recent call last) <ipython-input-8-6ed2e10f0c28> in <module>() ----> 1 from maidea.apps.somalia.models import PurchaseOrder ImportError: cannot import name PurchaseOrder i have tried using from django.apps.import apps apps.get_model('somalia','PurchaseOrder') i get this error LookupError: App 'somalia' doesn't have a 'purchaseorder' model. am running django version In [28]: django.VERSION Out[28]: (1, 9, 5, 'final', 0) i kindly need help what am i missing here. Thanks -
How to put all the apps of our django project in one folder.
I got one project where all the django apps are kept in one folder and app contains model,view,templatetags but not urls.py file then how user is able to acess the view of that app. -
Django: TemplateDoesNotExist error for base template
I learnt about Django template inheritance and was working on it. I made a base_post_login.html template in the same directory as other templates. and type {% extends "base_post_login.html" %} as the first line in in a child template. But when the child template is rendered through back-end the TemplateDoesNotExist error is raised. this is settings.py(relevant part): TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] all templates are rendered properly if it does not extend and parent template. What should I do? -
realtime Firebase with AWS vs REST framework with AWS
The project is a collaboration tool. I already have a Django python stack with Postgresql database at the backend. On the frontend, I've Android application and an Angular dashboard. I need to synchronize data between different users with the application[i.e. if one user updates a list, it should reflect to all the team members] as well as update the admin Dashboard of the team. The situation currently is that the Android app fires and api request to check whether the data has been changed/ to be changed. Instead, I can use Firebase in between to synchronise app users. Though I'd have to make an api call from the server to get the data. The admin Dashboard then gets the data from the server. Hence, the latency at the Dashboard increases. Plus I'm not sure how efficient Firebase will prove. Another option is i use WebSockets, Django channels to synchronise members as well as the dashboard. But then I'll need to do all the hard work of keeping checks for the right flow of data. Also, I'm not sure of the Scalability issues with Web sockets. I need to benchmark the options, but i'm not sure how i can do that- β¦ -
TypeError: unorderable types: NoneType() <= datetime.datetime()
I have fields in my django app live_from and live_to these fields are non required. When this fields are empty i get an error in my metod: Fields: live_from = models.DateTimeField('live from', blank=True, null=True) live_to = models.DateTimeField('live to', blank=True, null=True) here is my method: def is_live(self): return (self.live_from <= timezone.now()) and (self.live_to >= timezone.now()) Bug: TypeError: unorderable types: NoneType() <= datetime.datetime() -
DRF: Get request object in custom renderer
I'm building a serverside using django==1.10 and djangorestframework==3.4.6 I have build a JSONRenderer: class CustomJSONRenderer(JSONRenderer): def render(self, data, accepted_media_type=None, renderer_context=None): meta_fields = ["temp_save", "subject", "visit"] a = {"fields": {}} for k in data: try: meta_fields.index(k) # Crashes with ValueError if not found a[k] = data[k] except ValueError: a["fields"][k] = data[k] return super(CustomJSONRenderer, self).render(a, accepted_media_type, renderer_context) Question: Is it possible to get the views request object? I specifically want to access the urls parameters (e.g request.kwargs['pk'] -
Getting middleware errors in integrating django cms with existing django project
I have a working django project which contains around ten apps. I am integrating django cms in my app, so I can edit the pages content. I have followed the procedure of the documentation but I am getting middleware errors when I am doing "python manage cms check". The errors are in this format: cms.middleware.user.CurrentUserMiddleware middleware must be in MIDDLEWARE_CLASSES [ERROR] My middlewares are in following order in my settings.py: MIDDLEWARE = [ 'cms.middleware.utils.ApphookReloadMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Any help would be appreciated. -
Getting a css ribbon to appear on selected images only from a django database
I am using django framework. I have a css that creates a ribbon on an image. the problem is that I do not want the ribbon on every image in the database. In the HTML file for mt product details I have {% if product.get_image_url %} <div class="ribbon-wrapper-orange"><div class="ribbon-orange">{{ product.duration }}</div></div> <a href='{{ product.get_absolute_url }}'><img id='img' src='{{ product.get_image_url }}' class='img-responsive' /></a> {% endif %} The bove works fine if there is a time duration in the database, but if there is not, then an empty ribbon still comes on the image. Any ideas how I can have the ribbon appear on images with times in the product duration field only? -
Django reading uploaded file & iterating thru bytes
I am a beginner reading a file uploaded to Django and having trouble understanding read() and splitlines() with the file. Plain text file looks like this. 04-05-2011 - 04-05-2012 Something happened between these dates 12-05-2015 - 14-03-2016 We need to make some more money in this period. I'm processing it in a Django view like this. if file_form.is_valid(): file = request.FILES['filename'].read() print(type(file)) for x in file: print(x, type(x)) This prints type 'bytes' and a long stream of (Ascii) 'integer' types like this... <class 'bytes'> 48 <class 'int'> 52 <class 'int'> 45 <class 'int'> 48 <class 'int'> 53 <class 'int'> ... If I add .splitlines() after reading the file... file = request.FILES['filename'].read().splitlines() print(type(file)) for x in file: print(x, type(x)) then I get the type 'list' and lines of 'bytes' types instead... <class 'list'> b'04-05-2011 - 04-05-2012' <class 'bytes'> b'Something happened between these dates' <class 'bytes'> b'12-05-2015 - 14-03-2016' <class 'bytes'> b'We need to make some more money in this period.' <class 'bytes'> My question is why does the print of .read() return ascii integers while printing .splitlines() returns a list of bytes? I would have imagined that printing .read() without .splitlines() would still return bytes but with the newline '\n' included β¦ -
Django - NoReverseMatch while extending base.html
I've got some problem with my django app. It doesn't work when I use extends statement on the top of the page. If I remove this, page works correctly (At least I don't get error message). I'm sure I'm missing something small but I can't do this on my own. urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<user>\w+)/$', views.detail, name='detail')] index.html {% extends 'organizer/base.html' %} {% block content %} {% if all_users %} <ul> {% for user in all_users %} <li><a href="/organizer/{{ user.user }}/">{{ user.name }}</a></li> {% endfor %} </ul> {% else %} <h2>You don't have any users</h2> {% endif %} {% endblock %} views.py def index(request): all_users = User.objects.all() # connect to database return render(request, 'organizer/index.html', {'all_users': all_users}) part of my path organizer β βββ templates β βββ organizer β βββ base.html β βββ detail.html β βββ index.html -
Group Django model objects to a distinct column
I have the following Django model class TestModel(models.Model): company_name = models.CharField(max_length=100) nick_name = models.CharField(max_length=100) created_at = models.DateTimeField() Now I want to create a query/multiple queries which will group all the TestModel objects to the particular company_name. In a nutshell it will have the following structure. out - { "company_name_test_1": [TestModel1, TestModel2, TestModel3], "company_name_test_2": [TestModel4, TestModel5, TestModel6], } -
Django DecimalField "." instead of ","
Is there a way to get the DecimalField to output period . instead of a comma , when printing the field in the HTML template? If I paste or type in 11.766647100448608 into the field in the admin and hit save, it changes the . to a , like 11,766647100448608. Is that normal behavior, is it something on my end? And I need the point because it is coordinates for mapbox. And my markers end up on way off on the other side of the globe. From the model: class Map(models.Model): project = models.ForeignKey(Project, related_name='map') lon = models.DecimalField(max_digits=17, decimal_places=15, default='') lat = models.DecimalField(max_digits=17, decimal_places=15, default='') From the template: "type": "Feature", "geometry": { "type": "Point", "coordinates": [ {{ map.lon }}, {{ map.lat }} ] } THis is what I want: { "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [ 11.766647100448608, 55.22922803094453 ] } } But this is what I get: { "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [ 11,766647100448608, 55,22922803094453 ] } }