Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which type of model inheritance to choose in Django
I am trying to write models for an inventory-type project in Django and am unsure how to best define my models. Do I choose Abstract Base Classes, Multi-Table Inheritance, Proxy Models or something else to get my models to behave according to these requirements: A generic Product model that can track the stock level of a product Admin users must be able to add a new generic Product via the admin Specific Product models that can have the hardware serial number added as an attribute Specific Product can be associated with my Order/Customer models Is it possible to just do this and have it meet my reqs without any issues or is there a better approach? class Product(models.Model): name = models.CharField(max_length=250) description = models.TextField(blank=True) price = models.DecimalField(max_digits=8, decimal_places=2) stock_level = models.IntegerField() class SpecificProduct(Product): product = models.OneToOneField(Product) order = models.OneToOneField(Order) owner = models.OneToOneField(Customer) serial_nr = models.CharField(blank=True, max_length=250) Ideally, I would like to have behavior that works something like this: customer = Customer.objects.create([. . .]) order = Order.objects.create([. . .]) widget = Product.objects.create([. . .]) my_widget = SpecificProduct.objects.create( product=widget, order=order, owner=customer, serial_nr="12345" ) Am I on the right track? Any help/advice would be much appreciated! -
Expected view to be called with a url keyword argument named pk
I am using Django.. Here are my views class SettingsValues(generics.ListAPIView): serializer_class = SettingsSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def get_queryset(self): queryset = Settings.objects.all() queryset = queryset.filter(user=self.request.user.id) return queryset class SettingsValuesUpdate(generics.UpdateAPIView): queryset = Settings.objects.all() serializer_class = SettingsSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_update(self, serializer): serializer.save(user=self.request.user.id) Here is my model class Settings(models.Model): user = models.OneToOneField('auth.User', related_name='settings', on_delete=models.CASCADE) boolean1 = models.BooleanField(default=False) boolean2 = models.BooleanField(default=False) boolean3 = models.BooleanField(default=False) string1 = models.CharField(max_length=100, default='No description') My serializer class SettingsSerializer(serializers.ModelSerializer): class Meta: model = Settings fields = ('id', 'boolean1', 'boolean2', 'boolean3', 'string1') class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password' ,'settings', 'image') extra_kwargs = {'password': {'write_only': True}} My urls url(r'^settings/?$', views.SettingsValues.as_view()), url(r'^updsettings/?$', views.SettingsValuesUpdate.as_view()), I am using Angular 2 or postman app it does not matter.. When i return settings it is working fine. but when i try to update the user settings (PUT) it shows an error Expected view SettingsValuesUpdate to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly Any idea ? -
Error with ordering Django 1.9 models how to fix this?
Output from CMD django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: posts.Comments: (models.E015) 'ordering' refers to the non-existent field 'timestamp'. posts.Comments: (models.E015) 'ordering' refers to the non-existent field 'updated'. System check identified 2 issues (0 silenced). THE CODE HIMSELF! from __future__ import unicode_literals from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import pre_save from django.utils import timezone from django.utils.text import slugify # Create your models here. class PostManager(models.Manager): def active(self, *args, **kwargs): return super(PostManager, self).filter(draf=False).filter(publish__lte=timezone.now()) def upload_location(instance, filename): return "%s/%s" %(instance.id, filename) class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) title = models.CharField(max_length=70) slug = models.SlugField(unique=True) image = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") width_field = models.IntegerField(default=0) height_field = models.IntegerField(default=0) content = models.TextField(max_length=220) draf = models.BooleanField(default=False) publish = models.DateField(auto_now=False, auto_now_add=False) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) class Comments(models.Model): class Meta: db_table = 'comments' comments_text = models.CharField(max_length=120) comments_posts = models.ForeignKey(Post) objects = PostManager() def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"slug": self.slug}) #return "/posts/%s/" %(self.id) class Meta: ordering = ["-timestamp", "-updated"] def create_slug(instance, new_slug=None): slug = slugify(instance.title) if new_slug is not None: slug = new_slug qs = Post.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" %(slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug def pre_save_post_receiver(sender, β¦ -
Handle dynamic staticfiles path with Django
I'm almost overcoming to finish my Theme Selector with Django but I'm blocking on one point : ==> I don't arrive to get a dynamic staticfiles path according to the form result given by user. I will explain the process : User fills a Django form by checking a RadioSelect box. He has a choice between two options : Datasystems Cameroun Both options correspond to 2 themes which have two differents background-colors. Datasystems is blue & white and Cameroun is green & red. So, I pick up the form result corresponding to one of both theme which are situated in static files : |--- app1 |--- app2 βββ static β βββ Theme β βββ Cameroun β β βββ css β β β βββ Base.css β β β βββ Base_Accueil.css β β β βββ Base_Birthcertificate.css β β β βββ Base_Configurations.css β β β βββ Base_Identity.css β β β βββ Base_Mairie.css β β β βββ Base_Recensement.css β β β βββ Base_Table.css β β βββ images β β βββ admin.png β β βββ chantier.jpeg β β βββ chantier.png β β βββ employe?\201.png β β βββ logo.png β β βββ maire.png β β βββ officier.png β β βββ stats.jpeg β β βββ visiteur.png β β¦ -
Static files with bootstraps directory
I thought it would be easier to download bootstrap and adjust it to my code, instead of messing about a cdn. So I downloaded bootstrap and my directory looks like this. My static directory is properly (I think) setup since my style.css and maps.js are working fine. In my base.html I reference the files with: The old way <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel='stylesheet' type='text/css' href="{% static 'style.css' %}" /> <script src="{% static 'maps.js' %}"></script> <script src="{% static 'bootstrap-3.3.7' %}"></script> The static boostrap-3.3.7 is not working. The cdn worked however. My question is how would my static import look to have this setup with the bootstrap directory properly work? I'm sorry if it's a stupid question. -
OSError: [Errno 18] Invalid cross-device link
I'm working with django 1.6.5 and python 2.7. I have import feature in my app and I get error: OSError: [Errno 18] Invalid cross-device link I have problem with this part of code: os.rename(db_temp, settings.DATABASES['bookmat']['NAME']) code in settings: 'bookmat': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/my_projects/book/db/theasoft.sqlite3', }, -
How do I implement a comparison table in Django?
Essentially I want create something like in the image. When the user selects their option, it'll display in the table. This table only pops up when a selection is made, otherwise it's invisible. I dont need any code, just an idea on how would I achieve this? -
testing django user login by username?
I am trying to run a test case on whether the register user is logged in or not tests.py class RegistrationFormTestCase(TestCase): def test_valid_form(self): response = self.client.post(reverse('user-registration'), { 'username':'admin99', 'password1':'qwertyui', 'password2':'qwertyui', 'email':'admin@example.com', }) user = User.objects.get(username='admin99') self.assertEqual(response.status_code,302) The following test case is getting passed and I want to check whether the user exists or not, response is HttpResponse object. I have retrive the obtained username from response and compare it to the user eg: self.assertEqual(response(username),user) Any help would be apprectiated.Thanks in advance...:) -
using django.setup() from a subdirectory, how to reference settings?
I have a folder outside of my django app that I want to use to pull some data from django to use in some external scripts. However when i run setup i get the below error: [root@localhost cronjobs]# python Python 2.7.5 (default, Nov 6 2016, 00:28:07) [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.environ.setdefault("DJANGO_SETTINGS_MODULE", "infternal.settings") 'infternal.settings' >>> from django.conf import settings >>> import django >>> django.setup() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.7/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/lib64/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/usr/lib64/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/lib64/python2.7/site-packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportE How to I reference the settings module outside of the django folder? Thanks -
Django,django-modeltranslation
I'm new with modeltranslation and I have a problem. When I do the manage.py makemigrations myapp command after creating my model and registering the fields to translate in translation.py the modeltranslation app doesn't add the translated field to the model. The fields are in the table though. modeltranslation: Registered 0 models for translation () [pid: 8333]. in my setting.py from django.utils.translation import ugettext_lazy as _ gettext = lambda s: s LANGUAGES = ( ('hi', _('Hindi')), ('en', _('English')), ('ru', _('Russian')), ('ur', _('Urdu')), ('zh', _('Chinese')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGE_CODE = 'hi' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ from modeltranslation.translator import translator STATIC_URL = '/static/' MODELTRANSLATION_DEFAULT_LANGUAGE = 'hi' MODELTRANSLATION_LANGUAGES = ('hi', 'en') MODELTRANSLATION_FALLBACK_LANGUAGES = ('hi', 'en') MODELTRANSLATION_PREPOPULATE_LANGUAGE = 'hi' MODELTRANSLATION_TRANSLATION_FILES = ( 'i18ntest.translation', ) in my models.py from django.db import models from django.utils.translation import ugettext_lazy from django.conf import settings class MyThing(models.Model): name = models.CharField(help_text=ugettext_lazy('This is the help text'),max_length = 150,null = True, blank = True) def __unicode__(self): return self.name # Create your models here. class Profile(models.Model): name = models.CharField(max_length = 150,null = True, blank = True) def __unicode__(self): return self.name in my translations.py from modeltranslation.translator β¦ -
How to call a instance method from a CharField in Django
My code is as follows... state_choice = (('To Do','To Do'),('Doing','Doing'),('Done','Done')) def get_color_depends_state(self): if self.state: if self.state == 'To Do': self.color_code = '87CEEB' elif self.state == 'Doing': self.color_code = '7D3C98' elif self.state == 'Done': self.color_code = '00FF7F' state = models.CharField(max_length=200,choices=state_choice,default='todo') color_code = models.CharField(max_length=6, default=self.get_color_depends_state) My field color_code depends on the values of state field. I am trying to call the function from the color_code field but it is giving errors like self not defined or module has no attribute get_color_depends_state. How I can call an instance method from field which intern depends on other field values(Here state) -
'dict' object has no attribute 'encode' django mails
I'm trying to send an email after a form submission using django-mail-templated. When I submit my form I get this error : 'dict' object has no attribute 'encode' settings.py EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'example@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 views.py from django.core.mail import send_mail send_mail( 'autres/ticket_m.tpl', {'user': request.user}, 'example@gmail.com ', ['example@domain.ch'] ) ticket_m.tpl {% extends "mail_templated/base.tpl" %} {% block subject %} Hello {{ user }} {% endblock %} {% block body %} {{ user }}, this is a plain text message. {% endblock %} {% block html %} {{ user }}, this is an <strong>html</strong> message. {% endblock %} As you can see I am using django-mail-templated as the documentation so why do I get this error ? -
how to treat django's json fixtures data as pytest fixtures
I have django's fixtures in json files I want use it for every test (with session scope) I have tests runned by pytest how to wrap django's fixture with pytest.fixture ? -
How do I update the user's model fields in Django?
I'm currently creating a Social platform with Django. Right now, I'm developing the Profile Settings page and want endusers to be able to change their Header and Display-image. However, I'm not able to make the form work. Both the Header and Display-images are passing correctly through the POST form and end up getting stored in the media root, from where I call all my Header and Display-images in the template. So the problem right now is refering the submitted images as a Header or Display-image for the current user. This is my Profiel (dutch for Profile)Models.py: class Profiel(models.Model): user = models.OneToOneField(User, primary_key=True) Profielfoto = models.ImageField(blank=True, upload_to="profile_image", default="profile_image/no_profile_pic.jpg") Profielheader = models.ImageField(blank=True, upload_to="profile_header") Biografie = models.CharField(blank=True, max_length=150, default="Biografie nog niet ingevuld.") def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = Profiel.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) My Views.py @login_required def profile_edit_view(request): if request.method == 'POST': form = Edit_profile_forms(request.POST, request.FILES) if form.is_valid(): form.save() # Redirect to the document list after POST return HttpResponseRedirect(reverse('profiel_edit')) else: form = Edit_profile_forms(request.POST, request.FILES) args = {'form':form} return render(request, 'Dashboard/profiel_edit.html', args) And my forms.py: class Edit_profile_forms(forms.ModelForm): class Meta: model = Profiel fields = ( 'Profielfoto', 'Profielheader', 'Biografie', ) I think these are the only ones needed to show you guys β¦ -
py.warning: Just one line, but stacktrace needed for debugging
I see this warning in my logs: py.warnings._decompression_bomb_check +2261: WARNING [1091] /usr/lib64/python2.7/site-packages/PIL/Image.py:2261: DecompressionBombWarning: Image size (139332960 pixels) exceeds limit of 89478485 pixels, could be decompression bomb DOS attack. Unfortunately this line alone does not help me to debug this. I would like to see the stacktrace and other data like the request-URL. We use Django 1.8 and Python 2.7 -
Remove blank "---------" from RadioSelect
I don't find a way to remove the first line from my Choices_list which is displayed like -------. I already tried some things : blank=True, Blank=False, ... and this line is still there. This is what I'm getting in my Django website : My models.py and forms.py files look like : # models.py # coding: utf-8 from django.db import models from django.utils.encoding import force_text FAVORITE_THEME = ( ('Datasystems', 'Datasystems'), ('Cameroun', 'Cameroun'), ) class Theme(models.Model): favorite_theme = models.CharField(max_length = 20, choices=FAVORITE_THEME, verbose_name="Sélectionner le thème") # forms.py #-*- coding: utf-8 -*- from django import forms from django.forms import ModelForm from .models import Theme class ThemeForm(forms.ModelForm): class Meta: model = Theme widgets = {'favorite_theme' : forms.RadioSelect,} fields=('favorite_theme',) Do you have an idea to delete or hide this line ? Thank you -
google CloudSQL mysql emoji (1366, "Incorrect string value: '\\xF0\\x9F\\x98\\x80\\xF0\\x9F...' for column 'name' at row 1")
I can't make it to post emojis to the database when I use my-app.appspot.com but when I run it locally python manage.py runserverwith the same libraries on GAE everything works perfectly and I can post and retrieve emojis . here is my settings .py import os if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'): # Running on production App Engine, so use a Google Cloud SQL database. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/my-app:us-central1:my-app-mysql', 'NAME': '********', 'USER': 'root', 'PASSWORD': '*********', } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '*******', 'USER': 'root', 'PASSWORD': '*********', 'HOST': '**********', 'PORT': '3306', 'OPTIONS': { 'charset': 'utf8mb4', } } } here is the charset when using cloud shell mysql> SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%'; +--------------------------+--------------------+ | Variable_name | Value | +--------------------------+--------------------+ | character_set_client | utf8 | | character_set_connection | utf8 | | character_set_database | utf8mb4 | | character_set_filesystem | binary | | character_set_results | utf8 | | character_set_server | utf8mb4 | | character_set_system | utf8 | | collation_connection | utf8_general_ci | | collation_database | utf8mb4_general_ci | | collation_server | utf8mb4_general_ci | +--------------------------+--------------------+ 10 rows in set (0.15 sec) and here is the charset when I connect using the IP β¦ -
Edit migration in django
I face a ValueError while migrate old migrations because of removing a model in another app. How should I modify the migration to get rid of the error? -
django-filter pass request to FilterSet
I want to use request in django-filter but I have a hard time making it work. The docs say that The FilterSet may be initialized with an optional request argument but I can't get it to work. Filterset import django_filters from reservations.models import Reservation class ReservationFilter(django_filters.FilterSet): class Meta: model = Reservation exclude = [] def __init__(self, *args, **kwargs): super(ReservationFilter, self).__init__(*args, **kwargs) self.form.fields['service_date'].widget.attrs['class'] = 'datepicker' @property def qs(self): parent = super(ReservationFilter, self).qs return parent.filter(author=self.request.user) And this is how i call it class ListReservations(LoginRequiredMixin, FilterView): template_name = 'reservations/homepage.html' paginate_by = 25 model = Reservation filterset_class = ReservationFilter(request=self.request) This is obviously not working, I get File "/../views.py", line 41, in ListReservations filterset_class = ReservationFilter(request=self.request) NameError: name 'self' is not defined Then I tried def __init__(self): super(ListReservations, self).__init__() self.filterset_class = ReservationFilter(request=self.request) And it still didn't work 'ListReservations' object has no attribute 'request' So, how can I access request in FilterSet -
How to set required=False for Django Rest Framework serializer field?
How can I set required to be false for a django rest framework JSON serializer field? It seems to be enforcing validation regardless of the required flag: serializer field results = serializers.JSONField(required=False, label='Result') model field results = models.TextField(blank=True, default="") But when I submit the form with a blank input, I get: "results": [ "Value must be valid JSON." ], I've also tried changing the model default to {} in both the model field and the serializer field, but have the same response. -
Django REST Framework: How can you implement filters by property
I am wondering how can I implement filter by property. My model.py is like this: class Order(BaseOrderModel): uuid = models.CharField(primary_key=True, max_length=128) user = models.ForeignKey(User, related_name='orders') @property def brand(self): return self.get_attribute_value_by_code('brand') I'm trying to implement the following filters: class OrderFilter(df.FilterSet): brand = df.CharFilter(method='filter_on_brand') class Meta: model = Order fields = ['uuid', 'brand'] def filter_on_brand(self, queryset, name, value): return queryset.filter(brand=value) but I'm getting the follow error: django.core.exceptions.FieldError: Cannot resolve keyword 'brand' into field. Choices are: user, user_id, uuid... Is there a way to implement this filter? -
Getting 403(Forbidden) CSRF verification failed. Request aborted. AngularJS & Django
There is a Django RESTFremwork server is seted up in my local machine.But I am not able to make a post request to that here I include code for both index.html and app.js. <html> <head> <title>TEST API</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" media="all"> </head> <script src="https://code.angularjs.org/1.6.0/angular.js"></script> <script src="https://code.angularjs.org/1.6.0/angular-cookies.js"></script> <body ng-app="newApp" onbeforeunload="return false"> <div class="container" ng-controller="mainController"> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand " href="#"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> TEST API {{1+1}} </a> </div> </div> </nav> <button ng-click="sendData()">Click Here</button> </div> <!-- Modules --> <script src="app.js"></script> <!-- Controllers --> </body> </html> This is app.js file. Where I am trying to do POST request to REST api server.Always getting csrf verification failed. Altough I have defined it in headers.How can I fetch csrftoken from response headers while doing only GET on Django REST server. var app = angular.module('newApp',['ngCookies']); app.config(['$httpProvider', function($httpProvider,$http) { alert("in config"); $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; //$http.defaults.headers.post['X-CSRFToken'] = $cookies['csrftoken']; //$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken; // $httpProvider.defaults.withCredentials = true; }]); app.controller('mainController', function($scope,$http,$cookies){ alert("Main Controller"); $scope.sendData =function ($scope) { alert("in function"); /* $http({ url: 'http://yodaplus.localhost:8000/core/api-auth/login/', method: "GET" }) .then(function(response) { // success console.log(response); β¦ -
django login user, after successful login user stay on same page
I have to implement Login in django, But the login can be done at product purchase time, on creating comment, and so on. Here i am redirecting user on Index page after login. But i have to make user stay on same page from which(order, rating) page he is login. How i can do this ? Here what i have implemented: def login_view(request): if request.method=='POST': form=UserLoginForm(request.POST or None) if form.is_valid(): email = form.cleaned_data["email"] password = form.cleaned_data["password"] try: user = Customer.objects.get(email=email) if user.check_password(password) : if user.is_active and user.is_customer: if user.mobile_verified : user = authenticate(username=user.email, password=password) login(request, user) if request.POST.get('card_data'): for items in request.POST.get('card_data').split(","): cart = Cart(user=user, product_id=items) cart.save() total_cart = user.card_user.count() else: total_cart = 0 messages.success(request, "Login successfully.") responss = redirect("Peru:home") responss.delete_cookie('add_card_token') return responss else: messages.success(request,"Mobile number is not verified") return redirect("Peru:home") else : messages.info(request, "Your account may not be activated") return redirect("Peru:home") else: messages.error(request,"Email or Password does not match") return redirect("Peru:home") except Exception as e: messages.error(request, "User may not exists !") return redirect("Peru:home") else: return redirect("Peru:home", forms=form) else: return redirect('Peru:home') -
Querying database
I'm trying to implement search in django. My view is as follows : search_term = request.GET['search_term'] customers = Customer.objects.filter( Q(chassis__icontains=search_term) | Q(registration__icontains=search_term) | Q(email__icontains=search_term) | Q(firstname__icontains=search_term) | Q(lastname__icontains=search_term)) calculations_data = [] if customers: for customer in customers: try: calculation = Calculations.objects.get(customer=customer, user=request.user) calculations_data.append({ 'calculation': calculation, 'price': price_incl_vat(calculation.purchase_price), 'customer_fullname': '{} {} '.format(customer.firstname, customer.lastname), 'car_chassis': customer.chassis, 'car_registration': customer.registration, }) except Calculations.DoesNotExist: pass context = {'search_term': search_term, 'total_result': len(calculations_data), 'calculation_data': calculations_data} return render(request, 'master/search.html', context) I have two models, calculations and customer. Inside calculation I have customer as ForeignKey, but it can be empty. Thus, every calculation doesn't need to have a customer. In my example, if I have search term the result is good, but If there is not search term, then I get only the calculations which have a customer. But what I need is, if there is no search_term, I want to get all calculations. Is there maybe a better way to write the query? Thanks. -
datetime plotting issue with django-chartit
I am trying to plot a LineChart using django-chartit. I am using this code : query_FansEvolution = Facebook_Page_Insights_Metrics.objects.filter(page=page, created_at__lte=date_to, created_at__gte=date_from).order_by('-created_at').distinct('created_at') # Step 1: Create a DataPool with the data we want to retrieve. chart_data_FansEvolution = \ DataPool( series=[{ 'options': {'source': query_FansEvolution}, 'terms': [('created_at', lambda d: time.mktime(d.timetuple())), 'page_fans'] }]) # Step 2: Create the Chart object chart_FansEvolution = Chart( datasource=chart_data_FansEvolution, series_options=[{ 'options': {'type': 'line', 'stacking': True}, 'terms': {'created_at': ['page_fans']} }], chart_options={ 'title': {'text': ' '}, 'xAxis': {'title': {'text': 'Time'}}, 'yAxis': {'title': {'text': 'Fans'}} }, x_sortf_mapf_mts=(None, lambda i: datetime.fromtimestamp(i).strftime("%D"), False)) context['chart_FansEvolution'] = chart_FansEvolution (i got this code from here) The plotting looks like this : As you can see, the intervals between date is not proportional. How can I get this fixed ?