Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Custom User - Not using username - Username unique constraint failed
So I created my own user model by sub-classing AbstractBaseUser as is recommended by the docs. The goal here was to use a new field called mob_phone as the identifying field for registration and log-in. It works a charm - for the first user. It sets the username field as nothing - blank.But when I register a second user I get a "UNIQUE constraint failed: user_account_customuser.username". I basically want to do away with the username field altogether. How can I achieve this? I've tried lots of suggestions I found elsewhere but to no avail. I basically need to either find a way of making the username field not unique or remove it altogether. Cheers! Dean models.py from django.contrib.auth.models import AbstractUser, BaseUserManager class MyUserManager(BaseUserManager): def create_user(self, mob_phone, email, password=None): """ Creates and saves a User with the given mobile number and password. """ if not mob_phone: raise ValueError('Users must mobile phone number') user = self.model( mob_phone=mob_phone, email=email ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, mob_phone, email, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( mob_phone=mob_phone, email=email, password=password ) user.is_admin = True user.save(using=self._db) return user class CustomUser(AbstractUser): mob_phone = models.CharField(blank=False, … -
How to add a chart with a table in Chart.js?
I am using Chart JS 2.5 to visualize 2 data objects in bar charts and I can visualize the data values from both objects but I would like to see a table that also shows the data below these two graphs. Table view that I would like to have Date Data Object 1 Data Object 2 2 Jan 6 16 9 Jan 87 57 16 Jan 56 23 23 Jan 15 60 30 Jan 88 78 6 Feb 60 40 13 Feb 12 42 This is the code I currently have for generating the graphs. How do I retrieve the data Django - code snippet for the data retrieval from the internal web API class ChartData(APIView): def get(self,request, format=None): .... # get the filtered json per engineer for the current week weeks_of_data = [] for index, value in enumerate(list_of_engineers): week_of_data.append(filter_url(list_of_engineers[index]).json()) def filter_url(engineer): filters = {"filter": { "filters": [{ "field": "Triage_DateTime", "operator": "gte", "value": "2017-07-16 23:59:59" }, { "field": "Triage_DateTime", "operator": "lte", "value": "2017-08-11 23:59:59" }, { "field": "Triage_Subcategory", "operator": "neq", "value": "Temporary Degradation" }, { "field": "Triage_Engineer", "operator": "eq", "value": str(engineer) }], "logic": "and" }} Raw JS script to display the graphs <script> {% block jquery %} var endpoint = … -
Django API and Front-End Separation Issues
I'm starting to learn Django Rest Framework for my back-end and using Angular 4 for the front-end. I've read that some people are separating the two via GIT for scalability and team separation among other things, so I thought I would follow that idea and also try to separate the in two separate directories. I have installed Django on a Centos7 box with Apache. (the webserver is on my home network and is port-forwarded through my home router) The Django files are in one directory and my Angular files are in a separate directory. There are many other projects on the server so I'm not running Django on the root. An example url would be http://0.0.0.0/project1 I also have http://0.0.0.0/project2 and etc... This Django project is http://0.0.0.0/myproject/api which I can access and run just fine. But, when I put my front-end code in the front-end directory (http://0.0.0.0/myproject/front_end) and try to access it I get a Django 404 error. (I have debug=True on) My goal is to have my api accessed like http://0.0.0.0/myproject/api/example and front-end accessed using http://0.0.0.0/myproject. I may have to use virtual hosts to make that happen, but I'm not sure. What I cannot figure out is why is … -
How to calculate 3D distance (including altitude) between two points in GeoDjango
Prologue: This is a question arising often in SO: 3d distance calculations with GeoDjango Calculating distance between two points using latitude longitude and altitude (elevation) Distance between two 3D point in geodjango (postgis) I wanted to compose an example on SO Documentation but the geodjango chapter never took off and since the Documentation got shutdown on August 8 2017, I will follow the suggestion of [this widely upvoted and discussed meta answer][1] and write my example as a self-answered post. Of course I would be more than happy to see any different approach as well!! Question: Assume the model: class MyModel(models.Model): name = models.CharField() coordinates = models.PointField() Where I store the point in the coordinate variable as a lan, lng, alt point: MyModel.objects.create( name='point_name', coordinates='SRID=3857;POINT Z (100.00 10.00 150)') I am trying to calculate the 3D distance between two such points: p1 = MyModel.objects.get(name='point_1').coordinates p2 = MyModel.objects.get(name='point_2').coordinates d = Distance(m=p1.distance(p2)) Now d=X in meters. If I change only the altitude of one of the points in question: For example: p1.coordinates = 'SRID=3857;POINT Z (100.00 10.00 200)' from 150 previously, the calculation: d = Distance(m=p1.distance(p2)) returns d=X again, like the elevation is ignored. How can I calculate the 3D distance between … -
Where should the forms.py file be located?
I'm starting to write my first Django project right now and I need to make my forms.py file for an app. I've seen some tutorials store the file under the main folder for the project and some in the app directory. Which one is best for me to do if I want to make a form that only applies to one app? And is it suitable to make more than one file to keep my forms code in? Thanks! -
DRF setup_eager_loading for ManyToManyField through with list_serializer_class
I need help to optimize my DRF query. below are my related codes: models: class Product(Model): c = ManyToManyField(to=Category, through='ProductByCategory') ...other fields of Product... class ProductByCategory(Model): product = ForeignKey(to=Product, on_delete=models.CASCADE) category = ForeignKey(to=Category, on_delete=models.CASCADE) ...other fields of ProductByCategory... serializers: class ProductSerializer(ModelSerializer): productid = ReadOnlyField(source='id') procat = ProductByCategorySerializer(source='productbycategory_set', many=True) ...other fields of serializer... class Meta: model = Product fields = ('productid', 'procat') read_only_fields = ('procat', ) @staticmethod def setup_eager_loading(queryset): # select_related for 'to-one' relationships queryset = queryset.select_related('field1', 'unit1') # other fields # prefetch_related for 'to-many' relationships queryset = queryset.prefetch_related('productbycategory_set', 'productbycategory_set__product', 'productbycategory_set__category') return queryset class ProductByCategorySerializer(ModelSerializer): class Meta: model = ProductByCategory fields = (field1, field2) # no FK views: class ProductApi(APIView): def get(self, request): ...other codes... products = Product.objects.filter(productbycategory__category=category, productbycategory__status=active, productpromo__promopack=promopack).all() p_serializer = ProductSerializer.setup_eager_loading(products) d = ProductSerializer(p_serializer,many=True,context={'request': request}).data ...other codes... return Response(r) If I use above codes, the response time about 1 second, which is good for me. But I need to filter the output of nested serializer (ProductByCategorySerializer) only for specific category. So I follow this, to create filter with list_serializer_class. here's the serializers update: class ProductByCategorySerializer(ModelSerializer): class Meta: list_serializer_class = FilteredProductByCategorySerializer model = ProductByCategory fields = (field1, field2) # no FK class FilteredProductByCategorySerializer(ListSerializer): def update(self, instance, validated_data): return super(FilteredProductByCategorySerializer, self).update(instance, … -
Reordering stackedinlines in django admin
I am trying to reorder the below stacks. From Personal Information Permissions Important dates Profile To Personal Information Profile Permissions Important date admin.py -- from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from .models import UserProfile class ProfileInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'Profile' fk_name = 'user' class CustomUserAdmin(UserAdmin): inlines = (ProfileInline, ) list_display = ('email', 'first_name', 'last_name', 'is_staff') list_select_related = ( 'profile', ) exclude = ('username',) fieldsets = ( ('Personal information', {'fields': ('first_name', 'last_name', 'email', 'password')}), ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), ('Important dates', {'fields': ('last_login', 'date_joined')}), ) def get_inline_instances(self, request, obj=None): if not obj: return list() return super(CustomUserAdmin, self).get_inline_instances(request, obj) admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) Profile section sits at the end of the page. Is there any way to bring it up just after Personal Information. Any help is highly appreciated. -
Django: how to get template views to display images -- Noob edition
Note: There are a lot of questions related to this on Stack Overflow. However, this is not duplicate, as it requests noob level explanation (i.e. someone who has completed the Django tutorial). So I completed the Django tutorial and am off to make my own site to reinforce what I learned (and augment it as well). I wanted to make a site which could display some images of a given object. Since a lot of the before mentioned posts use goods and pictures (e.g. to emulate multiple images for a product on Amazon), lets go with that for this post as well. I made myself an app, and am using name-spaced urls and templates (as described in the tutorial). In addition, following the Many-to-One documentation, I have two models Product and ProductImage with the latter having a ForeignKey to the former. class Product(models.Model): ... class ProductImage(models.Model): product = models.ForeignKey("Product", on_delete=models.CASCADE) image = models.ImageField(upload_to=product_dir_path) Using a reverse many-to-one monitor (e.g. aSpecificProduct.productimage_set.all() ) I grabbed all my images which I set up in a directory under the app's directory <my_app>/uploads/product_<id>/image_<id> using the little upload_to trick in the model field reference part of the documentation. def product_dir_path(instance, filename): return "<my_app>/uploads/product_{0}/{1}".format(instance.product.id, filename) Great, so … -
Django forms with questions from model
I'm writing a "quiz" web application. I have this model class Question(models.Model): question = models.CharField(max_length=300) answer1 = models.CharField(max_length=300, default="") answer2 = models.CharField(max_length=300, default="") answer3 = models.CharField(max_length=300, default="") answer4 = models.CharField(max_length=300, default="") and I'm trying to create a form for a "multiple choices" school test, with the questions and answers I insert from the admin page into the database. I can't figure out how to do, I looked up into the documentation and I've found that ModelForm, but as I understood, it is for "add things into the database, not for showing data from the database. What I'm trying to do is showing the questions and let students pick the answer with radiobuttons. One solution I explored was to use the templating system like : {{% for q in questions %}} <h3>{{ q.question }}</h3> ... {{% endfor %}} and then check with javascript the answers, but I was looking for something "built in", in order to ease the programming, have more flexibility and easily let the students submit the test -
Can't get attribute value from the database while using CreateView and ModelForm
I'm trying to create a form to add a blog to a subscription list of a logged in user. Right now I'm only interested in the first part of the form_valid till 'except' class AddBlogToSubList(CreateView): model = SubscriptionList form_class = SubsListForm template_name = 'blog/add_blog_to_sub_list.html' success_url = reverse_lazy('blog:blog-list') def form_valid(self, form): try: # first I'm trying to find out if an instance of a # SubscriptionList model is in the database model_instance = self.request.user.subscription_list # Then I create an instance of a form with kwarg 'instance' # to work with the default model instance f = SubsListForm(self.request.POST, instance=model_instance) # As far as I understand here I get a instance of a model in # the database with the ability to update it as I've mentioned # earlier instance=model_instance existing_instance = f.save(commit=False) blog = Blog.objects.get(pk=self.kwargs['blog_pk']) # update a subscription list of a current user with a new blog existing_instance.blogs_in_subscription.add(blog) # save an updated instance existing_instance.save() f.save_m2m() return super(AddBlogToSubList, self).form_valid(form) except SubscriptionList.DoesNotExist: pass The thing that I expect is that if I'm updating the instance of a SubscriptionList (dew to instance=model_instance, according to the django docs) that is already in the database the 'user' attribute will be already set. But I get this … -
Using 'onload' alike function for td element
I have a datatable in my django template, I have a td element in the table as shown below <td id="allStatus{{x.id}}"onclick="setColor('{{x.status}}',`{{x.id}},'tab')">{{x.status}}</td>` I need this element to run the function 'setColor' everytime the webpage is loaded. I am unable to use onload here as oload is not valid for such elements, but I need to pass those parameters(because I am using a for loop here and this function gets called mutliple times in the loop with different {{x.id}}) which restricts me to only call this function from the exact td element. Is there a way that I could achieve this, so that the function gets called when the page loads and also the parameters are passed to the function? -
mod_wsgi-express service not stating
I'm trying to use mod_wsgi-express for a django project. This project will be served through the main instance of apache, with a proxy. My purpose is to serve a python 3 application with a mod_wsgi for python 2 installed on the "main" apache server. (I've many apps on the same server) I've created a systemd service which should launch the mod_wsgi-express instance, using my own service file : https://gist.github.com/frague59/87529fc28b098dd116f09be92cf66af0 and https://gist.github.com/frague59/8de1d03800042db95c82452af280dffe I've to mention that those scripts works on another server, same distro, same version (debian oldstable) ... but the mod_wsgi-express does not start : no error message, no log... I've noticed that a dir is created in tmp: /tmp/mod_wsgi-127.0.0.1:8081:993 I've tried to start the apachectl from here: # apachectl configtest And I have a weird message: AH00526: Syntax error on line 241 of /tmp/mod_wsgi-127.0.0.1:8081:993/httpd.conf: Invalid option to WSGI daemon process definition. I posts the generated httpd.conf file for example: https://gist.github.com/frague59/a6d8d26b704565b39f7352a7c16e07d3 Error seems to be around: send-buffer-size=0 \ -
Where is the Salt key in a Pylons/Pyramid app?
I have a legacy 2010 Pylons app I want to replace with a newer Django one. In Django, it is my understanding that the Salt that is used in hashing passwords is the SECRET_KEY in the config file. Correct me if I am wrong. Pretty easy to find. Anyway, the company isn't keen on resetting everyone's passwords due to the different hashing algorithm used in Django. So I was going to change Django's to match the Pylons one, or find a way to decrypt the Pylons hashed ones, and re-encrypt under Django's. Problem is I don't know where the Salt is in the Pylons application after looking through documentation and Googling it. Anyone have an idea? -
Force celery daemon to use Python 3
So I have struggled with this with quite a while but I can't seem to find a solution. I have installed celery with pip3 install --user celery And everything was working fine until I try to run a celery worker and beat as a daemon following the official documentation http://docs.celeryproject.org/en/latest/userguide/daemonizing.html The specific problem I have is that the configuration file for the daemon needs the full route to celery, which I have located and specified in the file like this CELERY_BIN="/home/my_home/.local/bin/celery" but when I run the daemon it says that I do not have a module named Celery me@my_computer:/etc/default$ sudo /etc/init.d/celeryd start celery init v10.1. Using config script: /etc/default/celeryd Traceback (most recent call last): File "/home/my_home/.local/bin/celery", line 7, in <module> from celery.__main__ import main ImportError: No module named 'celery' Trying different things I think I have found the problem, apparently Celery daemon is trying to run celery using python 2 but since I installed it for python 3 it says that it can't find it. Any clues on how to fix this or if I should try something else? Additional output: Python 2: Python 2.7.6 (default, Oct 26 2016, 20:32:47) [GCC 4.8.4] on linux2 Type "help", "copyright", "credits" or "license" … -
Django timezone is wrong
I can't seem to make timezone works with Django 1.11. My Settings.py: TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True I'm starting the server at : And it outputs the following: Which is 4:09PM And of course when doing: form django.utils import timezone today = timezone.localtime(timezone.now()) print(today) The outuput is also wrong by +1 hour, while the time is indeed specified as +00: 2017-08-10 16:09:04.208536+00:00 Any idea of what i'm missing ? -
Trying to connect social login with django and allauth. Help me out with the error
I have the error trace: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 307, in execute settings.INSTALLED_APPS File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/reddykumarasimha/Desktop/fblogin/fblogin/settings.py", line 131, in <module> 'allauth.account.auth_backends.AuthenticationBackend', ) TypeError: repr() takes exactly one argument (2 given) And here is my code: -
virtualenv and Django directories structure
I was trying to use virutalenv in windows but there is something odd that I barely understand about the directories structure. When you create a new virtual environemnt it creates for you the following structure: C:\Projects\djang_venv\ Include\ Lib\ pip-selfcheck.json Scripts\ tcl\ If I want to work on my django project where should I put my project, in the django_vent directory ? C:\Projects\djang_venv\ django_site\ Include\ Lib\ pip-selfcheck.json Scripts\ tcl\ It's not looking right, like something is messy here. Where should I put my application when I create a virtual environment ? -
Django Apache: Target WSGI Script Cannot Be Loaded as Python Module
I am getting the following error. I tried the other answers provided for the same error but nothing is working. Any help would be appreciated. Apache error log: [Thu Aug 10 19:51:22.397653 2017] [wsgi:error] [pid 10908:tid 3048807232] [remote 10.0.2.15:12215] mod_wsgi (pid=10908): Target WSGI script '/home/sharan/myproject/proj_VivRx1/proj_VivRx1/wsgi.py' cannot be loaded as Python module. [Thu Aug 10 19:51:22.397731 2017] [wsgi:error] [pid 10908:tid 3048807232] [remote 10.0.2.15:12215] mod_wsgi (pid=10908): Exception occurred processing WSGI script '/home/sharan/myproject/proj_VivRx1/proj_VivRx1/wsgi.py'. [Thu Aug 10 19:51:22.398589 2017] [wsgi:error] [pid 10908:tid 3048807232] [remote 10.0.2.15:12215] Traceback (most recent call last): [Thu Aug 10 19:51:22.398657 2017] [wsgi:error] [pid 10908:tid 3048807232] [remote 10.0.2.15:12215] File "/home/sharan/myproject/proj_VivRx1/proj_VivRx1/wsgi.py", line 16, in <module> [Thu Aug 10 19:51:22.398664 2017] [wsgi:error] [pid 10908:tid 3048807232] [remote 10.0.2.15:12215] application = get_wsgi_application() [Thu Aug 10 19:51:22.398675 2017] [wsgi:error] [pid 10908:tid 3048807232] [remote 10.0.2.15:12215] File "/home/sharan/myproject/myprojectenv/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Thu Aug 10 19:51:22.398680 2017] [wsgi:error] [pid 10908:tid 3048807232] [remote 10.0.2.15:12215] django.setup(set_prefix=False) [Thu Aug 10 19:51:22.398689 2017] [wsgi:error] [pid 10908:tid 3048807232] [remote 10.0.2.15:12215] File "/home/sharan/myproject/myprojectenv/lib/python3.5/site-packages/django/__init__.py", line 22, in setup [Thu Aug 10 19:51:22.398694 2017] [wsgi:error] [pid 10908:tid 3048807232] [remote 10.0.2.15:12215] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Thu Aug 10 19:51:22.398703 2017] [wsgi:error] [pid 10908:tid 3048807232] [remote 10.0.2.15:12215] File "/home/sharan/myproject/myprojectenv/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__ [Thu Aug 10 19:51:22.398708 2017] [wsgi:error] [pid … -
django rest framework return a custom object using ModelSerializer and ModelViewSet
I have three models, three serializers, one modelviewset below. I am using django-rest-framework to make a rest api for android. The restaurant model was created first. Then I created a star model and an image model. What I want to do is to add star and image objects into restaurant objects. finally I've got what I want result but I think my viewset code looks like wrong.. Is there another way not to use "for loop"? Models class Restaurant(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) address = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE) weather = models.ForeignKey(Weather, on_delete=models.CASCADE) distance = models.ForeignKey(Distance, on_delete=models.CASCADE) description = models.TextField('DESCRIPTION') def __str__(self): return self.name class Star(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.IntegerField('RATING') def __str__(self): return self.restaurant class RestaurantImage(models.Model): id = models.AutoField(primary_key=True) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) path = models.CharField(max_length=255) Serializer class StarSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('id', 'restaurant', 'user', 'rating', ) class RestaurantDetailSerializer(serializers.ModelSerializer): category = CategorySerializer() weather = WeatherSerializer() distance = DistanceSerializer() class Meta: model = Restaurant fields = ('id', 'name', 'address', 'category', 'weather', 'distance', 'description', ) class ImageSerializer(serializers.ModelSerializer): class Meta: model = RestaurantImage fields = ('id', 'path', 'restaurant') ViewSet class RestaurantDetailInfoViewSet(viewsets.ModelViewSet): queryset = Restaurant.objects.all() serializer_class = RestaurantSerializer def list(self, … -
Django deployment in Heroku: Fails in createsuperuser : django.db.utils.OperationalError: no such table: auth_user
There has been a lot of stackoverflow question regarding this particular error but I think none has the similar situation that I have. I've been following djangogirls heroku deployment tutorial, from database setup in settings.py ensuring that I have done it correctly. I got the app up and running in the host. Trying to access admin now, it still has the Operational Error for auth_user. Therefore I thought that I might've just gone wrong with the migration. So following these steps I did this: 1.) python manage.py makemigrations 2.) python manage.py migrate 3.) git add . , git commit -m "-" , git push heroku master 4.) heroku run python manage.py makemigrations 5.) heroku run python manage.py migrate And now the last step, everything fails here, saying that there is still things to migrate. 6.) heroku run python manage.py createsuperuser The steps that I did are the suggestions that they presented and was accepted but it can't seem to work in my case. Any ideas? git push heroku master Counting objects: 6, done. Delta compression using up to 2 threads. Compressing objects: 100% (6/6), done. Writing objects: 100% (6/6), 584 bytes | 0 bytes/s, done. Total 6 (delta 5), reused … -
Django can't migrate after cloning repo
I've been working on a Django app on another machine, with a local postgis database. I pushed the entire thing to GitHub, except what is in the .gitignore. .gitignore venv *.pyc staticfiles .env .idea uploads Came home and cloned the repo, installed all the requirements and created a new local postgres database with the same settings from settings.py and the same postgis extension. settings.py DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'db_name', 'USER': 'postgres', 'PASSWORD': '******', 'HOST': 'localhost', 'PORT': '5432', } } But I can't create any migrations. I just get an error django.db.utils.ProgrammingError: relation "something_something" does not exist I have tried rooling back to the first initial migration file, but with the same result. makemigrations applabel 0001 It is as if Django think it is still the same db, but with all the tables missing. But I can't migrate and get Django to create them. How can I get out of this mess? Can I for a migrate somehow? If you need additional information, that I've left out please ask. -
pie chart highcharts from django query
I am running a query in views.py in a django environment. All is currently running local with the idea to push it finally into a heroku environment. I use PostgreSQL. def test(request): click_results = clickstats.objects.filter(user=request.user.username, urlid=pk_int) data = parse_data_browser(request, click_results) template = get_template('index.html') context = { 'data': data, } return HttpResponse(template.render(context,request)) def parse_data_browser(request,click_results): browsers = click_results.values('browser').annotate(browser_qty=Count('browser')).order_by() print("browsers") print(browsers) return browsers the printed output by parse_data_browser looks like this: <QuerySet [{'browser': 'Chrome Mobile', 'browser_qty': 4}, {'browser': 'Chrome', 'browser_qty': 9}]> the challenge is to get it in this shape: data = [{name: 'Chrome Mobile', y: 4}, {name: 'Chrome', y: 9}] then passing it on to my index.html using following scripts: <script> var chart_id = {{ chartID|safe }} var chart = {{ chart|safe }} var title = {{ title|safe }} var yAxis = {{ yAxis|safe }} var data = {{ data|safe }} </script> and finally create the chart with this script: <script> $(function () { var myChart = Highcharts.chart('chartID', { chart: { plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false, type: 'pie' }, series: [{ name: 'Brands', colorByPoint: true, data: [{name: 'Chrome Mobile', y: 4}, {name: 'Chrome', y: 9}] }] }); }); </script> I tried multiple things with dict and append functions, but nothing does … -
datetime field is not showing on html template django
i have a model which have datetime field. when i update using django ORM. then table created date get null. 2nd date field is also not showing on html template. I am writing like below. but showing None. dl.date_time Sorry for my bad English. Thanks in advance. Regards, Abdhesh -
Django - unique toghter case insensitive
For Django 1.11: It is possible to have unique together with case insensitive ?. now is case sensitive Ho can I override the unique_together Validation Error ? -
Form valid in unit test even though ValidationError was raised
I'm testing my view for handling invalid form data. In my test case I'm submitting form with missing field and expect view to handle it by displaying error message. Here is a relevant snippet from clean in my form: Form: def clean(self): first_name = self.cleaned_data.get('first_name', '') last_name = self.cleaned_data.get('last_name', '') if not first_name or not last_name: print('Form is invalid') # This is always executed. raise ValidationError('All fields are required.') # other stuff ValidationError is always raised, however, form.is_valid() returns True nonetheless: View: form = forms.EditProfileForm(request.POST, instance=user) if form.is_valid(): print('Form is valid') # Update user data. # Always executed even though error was raised. This leads to test failing, since I'm asserting that form validation will fail: Test Case: def test_invalid_data(self): formdata = { 'first_name': 'Bruno', 'last_name': '', # Missing data. 'email': 'bruno@schulz.pl', 'password': 'metamorphosis' } request = self.factory.post('/accounts/profile', formdata) request.user = self.user setup_messages(request) response = ProfileView.as_view()(request) self.assertEqual(response.status_code, 200) self.assertNotEqual(self.user.first_name, formdata['first_name']) # Fails. self.assertNotEqual(self.user.last_name, formdata['last_name']) self.assertNotEqual(self.user.email, formdata['email']) self.assertNotEqual(self.user.username, formdata['email']) Form validation works properly on a live server (tested "by hand"). It looks like ValidationError is ignored during TestCase evaluation. *Test output: .Form is invalid F..Form is valid . ====================================================================== FAIL: test_invalid_data (.tests.ProfileTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/apps/accounts/tests.py", line …