Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom arithmetic filter clause in ORM
I am trying to retrieve from a particular table all rows for which a certain subtraction results in a value smaller or equal to a certain fixed value. In SQL it would look like this: SELECT * FROM my_table WHERE column_a - column_b <= 1; In Django, I thought I could apply a filter combining F expressions, but as far as I have seen that is only possible if the value to compare against is a column or annotation. Since usage of the the extra keyword is discouraged and RawSQL is also not an attractive option, I would like to know if there is a built-in way to apply this kind of filtering. Of course I could also do with an annotation, but out of curiosity would be good to know if there is a more 'direct' way. Thanks in advance! -
Django: Form Instance Not loading
I'm using a view to load objects onto the form .I'm using Material Form Library I have added CKEditor on the form through Jquery, the form is saved but I cannot seem to load the data onto the form. urls.py url(r'^viewprescription/(?P<tid>\d+)/$', views.get_template, name='viewtemplates'), views.py def get_template(request, tid): template = presciptiontemplates.objects.get(templateid=tid) if request.method == "GET": form = templateform(request.GET, instance=template) messages.success(request, 'Prescription loaded') print(form) if form.is_valid(): form.save(commit=False) Presciptiontemplates = presciptiontemplates() Presciptiontemplates.savedate = datetime.now() Presciptiontemplates.template = form.cleaned_data.get('template') Presciptiontemplates.draft = form.cleaned_data.get('draft') Presciptiontemplates.save() messages.success(request, 'Prescription Saved Successfully') else: form = templateform(request.GET, instance=template) messages.error(request, 'Please Try Again') print(form) return render(request, 'presapp/viewtemplate.html', {'form': form}) forms.py class templateform(forms.ModelForm): template = forms.CharField(widget=forms.Textarea, label='') draft = forms.BooleanField(required=False) layout = Layout(Fieldset('Template'), ('template'), ('draft')) class Meta: model = presciptiontemplates fields = ['template', 'draft'] models.py class presciptiontemplates(models.Model): templateid = models.AutoField(primary_key=True) template = RichTextField() draft = models.BooleanField(default=False) savedate = models.DateTimeField(default=datetime.now()) patientid=models.IntegerField() viewtemplate.html <div id="preview-content"> <form method="POST" style="margin-top:20px;"> {% csrf_token %} {% form %} {% endform %} <div class="" style="margin-top:20px ;"> <button class="btn waves-effect waves-light left" type="submit">Submit <i class="material-icons right">add_circle</i> </button> </form> </div> </div> -
Error with Signals Post_Save and Pre_Save
It is necessary that after the addition of the series, the number of the series is automatically added, if the administrator forgets to add, in this way: we take the last created series, from there we take the series number, and add to this the number of the series 1, and add to our series! But constantly vylazyut such errors as: 1) lacks the argument "self", add it (although why it is there at all, it is not known) and still does not work! 2) series_change_number () missing 1 required positional argument: 'created' And the like! this is my models and SIGNALS class Series(models.Model): id = models.AutoField(primary_key=True) rus_name = models.CharField(max_length=60) eng_name = models.CharField(max_length=60) slug = models.SlugField(unique=False) serial_of_this_series = models.ForeignKey(Serial, on_delete=models.CASCADE, default=True) season_of_this_series = models.ForeignKey(Season, on_delete=models.CASCADE, default=True) number_of_series = models.IntegerField(default=0, blank=True, null=True) description = models.TextField(max_length=700, blank=True, default=None) size_of_torent_file = models.CharField(max_length=60, default=None) link_for_dowloand_serie_in_quality_360p = models.CharField(max_length=60, default=None) link_for_dowloand_serie_in_quality_720p = models.CharField(max_length=60, default=None) link_for_dowloand_serie_in_quality_1080p = models.CharField(max_length=60, default=None) rating = models.FloatField(default=0, blank=True) is_active = models.BooleanField(default=True) timestamp_rus = models.DateField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) timestamp_eng = models.CharField(max_length=60) time_of_series = models.DecimalField(max_digits=10, decimal_places=2, default=42) def get_absolute_url(self): return reverse('series:post_of_serie', kwargs= {'serial_slug': self.serial_of_this_series.slug, 'season_slug': self.season_of_this_series.slug, 'series_slug': self.slug}) def __str__(self): return "%s | %s" % (self.rus_name, self.number_of_series) class Meta: ordering = ["-timestamp_rus"] … -
install GeoIP on Heroku
I got problems with pushing my Django project with GeoIP on Heroku. remote: Installing collected packages: dj-database-url, Django, GeoIP, psycopg2, whitenoise remote: Running setup.py install for GeoIP: started remote: Running setup.py install for GeoIP: finished with status 'error' remote: Complete output from command /app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-Aup5AY/GeoIP/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-3RTdk0-record/install-record.txt --single-version-externally-managed --compile: remote: /app/.heroku/python/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'bugtrack_url' remote: warnings.warn(msg) remote: running install remote: running build remote: running build_ext remote: building 'GeoIP' extension remote: creating build remote: creating build/temp.linux-x86_64-2.7 remote: gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/app/.heroku/python/include/python2.7 -c py_GeoIP.c -o build/temp.linux-x86_64-2.7/py_GeoIP.o -fno-strict-aliasing remote: py_GeoIP.c:23:19: fatal error: GeoIP.h: No such file or directory remote: #include "GeoIP.h" remote: ^ remote: compilation terminated. remote: error: command 'gcc' failed with exit status 1 remote: remote: ---------------------------------------- remote: Command "/app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-Aup5AY/GeoIP/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-3RTdk0-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-Aup5AY/GeoIP/ remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed Heroku buildpacks heroku/python Heroku config BUILDPACK_URL: git://github.com/Bouke/heroku-buildpack-python.git Requirements.txt appdirs==1.4.3 dj-database-url==0.4.2 Django==1.9.6 GeoIP==1.3.2 packaging==16.8 psycopg2==2.7.1 pyparsing==2.2.0 six==1.10.0 whitenoise==3.3.0 I have added official heroku buildpack https://github.com/Bouke/heroku-buildpack-python-geoip/tree/master, but … -
profile form not populated with current value
I have a form for updating the user profile. The profile update is working abnormally because the forms are not populated with current value so if i update only some fields the other fields are saved as empty. How can i show the form with current value when using django rest framework? serializers class ProfileSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True) token = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Profile fields = ('token', 'user', 'current_location', 'permanent_location', 'dob', 'about_me', 'gender_status', 'create_profile_for', 'marital_status', 'height', 'weight', 'body_type', 'complexion',) class UserDetailSerializer(serializers.ModelSerializer): profile = ProfileSerializer() email = serializers.EmailField(source="user.email", read_only=True) class Meta: model = User fields = ('id', 'profile', 'username', 'email', 'first_name', 'last_name',) def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile #updating user data instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.username = validated_data.get('username', instance.username) instance.email = validated_data.get('email', instance.email) instance.save() #updating profile data if not profile: Profile.objects.create(user=instance, **profile_data) profile.current_location = profile_data.get('current_location', profile.current_location) profile.permanent_location = profile_data.get('permanent_location', profile.permanent_location) profile.weight = profile_data.get('weight', profile.weight) profile.create_profile_for = profile_data.get('create_profile_for', profile.create_profile_for) profile.body_type = profile_data.get('body_type', profile.body_type) profile.save() return instance views class UserProfile(APIView): serializer_class = UserDetailSerializer def get(self, request, token=None, format=None): """ Returns a list of profile of user """ reply={} print('request', request.user) try: # user_instance = User.objects.filter(user=request.user) if token: user = User.objects.get(id=token) reply['data'] = self.serializer_class(user).data … -
How to retain the value of a global variable after initialising it in constructor in python?
While creating a form using django, I faced this issue. class DetailForm(forms.Form): row_id = 2 def __init__(self, *args, **kwargs): global row_id row_id = kwargs.pop('r_id') super(DetailForm, self).__init__(*args, **kwargs) row=Prewash.objects.get(id=row_id) The row_id is a global variable and I want to use it's value, initialized in the constructor by kwargs pop. I can not use functions. I have to update the global variable value. -
I want to make a view in django to get String as it is
I am working on Openlayers and Saved a polygon in database . MY model is like this buffer_line = models.TextField('Buffer_line', default=0) And I am sending data in it like this buffer_line=this.buffer_share.toString(); Buffer sharing is calculating distance so its working fine. Now I want to make a view to get it back from database. till now I am thinking like this self.request.POST.getlist('Buffer_line'): . -
Get last event for each person
I am using Django 1.11 and trying to get the last event filter by a range of date per each person. So for example, get the last event for each person from 11-01-2017 to 15-01-2017 and show the full name, location name, sign_in time, sign out time in an efficient way. It would be easy but inefficient getting the last event for each person, store the IDs in a list and filter by those IDS but it would be N+1 queries. My models are the next ones: class Building(BaseModel): name = models.CharField(_('Name'), max_length=100) class Person(AbstractBaseUser): name = models.CharField(max_length=255) surname = models.CharField(max_length=255) # .... class Swipe(BaseModel): action = models.CharField(max_length=50) time = models.DateTimeField(null=True, blank=True) location = models.ForeignKey("buildings.Building", null=True, blank=True) class Event(BaseModel): subject = models.CharField(max_length=200, null=True, blank=True) user = models.ForeignKey("users.Person", on_delete=models.CASCADE, related_name='events') host = models.ForeignKey("users.Person", null=True, blank=True, on_delete=models.CASCADE, related_name='events_host') time = models.DateTimeField(null=True, blank=True) sign_in = models.OneToOneField(Swipe, null=True, blank=True, related_name='swipe_in', on_delete=models.PROTECT) sign_out = models.OneToOneField(Swipe, null=True, blank=True, related_name='swipe_out', on_delete=models.PROTECT) Any ideas? -
Django model field to upload file from one app but save with another
We are developing an intranet with Django which has to have a consistent and centralized file managmenet. We implemented a filemanager app which should handle all the uploads and downloads, do mimetype checks, permission checks etc. The upload ist achieved through a Django form: class UploadFileForm(forms.ModelForm): class Meta: model = PhysicalFile fields = ('path', 'directory') def save(self, commit=True): """ Override save method of ModelForm to create Physical File object of uploaded file and to process meta data """ # Proceed with default behaviour but DO NOT commit! # pfile contains the PhysicalFile object which is not yet written to DB pfile = super(UploadFileForm, self).save(commit=False) # set pfile's meta data according to: # https://docs.djangoproject.com/en/1.11/ref/files/uploads/ pfile.name = self.cleaned_data['path'].name pfile.size = self.cleaned_data['path'].size pfile.mimetype = self.cleaned_data['path'].content_type # NOW save to database, ignoring commit parameter pfile.save() return pfile Now we need want to perform uploads in ANOTHER app (say a members app with profile picture upload) using the same form as above. However, it needs to be included into an app specific form. E.g. a form with name, address etc. Basically we would only need to save the corresponding foreignKey of the file into the memberModel and process the upload with the filemanger's form. That … -
Unit Testing Django Views that uploads image to s3
I wrote a simple unit test to test django view. The view uploads the image file that is passed along with the request object to S3. Code: url = 'view-endpoint-url' myfile = open('pathtoimage')) payload = {'data1': 'xyz', 'file': myfile} response = client.post(url, payload, MULTIPART_CONTENT) At this point when the view under test is called: the image file is stored as expected in request.FILE['file']InMemoryUploadedFile. When the view tries to open(request.FILE['file']) and read() I get a IOError no such file or directory I'm confused because the image file does exist within the location but for some reason it's not being picked up. I did the similar testing using curl command and all works fine. Is there any workaround that can help me with the unit testing? -
use extras.SelectDateWidget and crispy form
for birthday in profile model, i add extras.SelectDateWidget to my form, but when try form.save get error 'Profile' object is not iterable Request Method: POST Request URL: http://localhost:8000/profile/ Django Version: 1.11 Exception Type: TypeError Exception Value: 'Profile' object is not iterable Exception Location: C:\Program Files\Python35\lib\site-packages\django\template\defaulttags.py in render, line 172 Python Executable: C:\Program Files\Python35\python.exe Python Version: 3.5.3 In template C:\Program Files\Python35\lib\site-packages\crispy_forms\templates\bootstrap3\uni_form.html, error at line 8 'Profile' object is not iterable 1 {% load crispy_forms_utils %} 2 3 {% specialspaceless %} 4 {% if include_media %}{{ form.media }}{% endif %} 5 {% if form_show_errors %} 6 {% include "bootstrap3/errors.html" %} 7 {% endif %} 8 {% for field in form %} 9 {% include "bootstrap3/field.html" %} 10 {% endfor %} 11 {% endspecialspaceless %} when i comment form.save or comment extras.SelectDateWidget i dont get error, anybody has same issue? -
Django hidden input set dynamic value (depending on link)?
I am trying to create a Django form with one of the hidden input value set dynamically. I have 5 links -> Class 1, Class 2, Class 3, Class 4, Class 5 All of them redirects to the same form. But if the person clicks say 'Class 1' the value of hidden input value will be 'Class 1' and so on. I am pretty new to Django. So, any help/suggestions would be appreciated. -
MEDIA_ROOT: shall I hardcode the path or use os.path.join?
Django 1.11 The documentation shows that we should place, say, images to /var/www//media/ https://docs.djangoproject.com/en/1.11/ref/settings/#media-root But in the book "Two Scoops of Django" they recommend: # Configuring MEDIA_ROOT # ’DONT DO THIS! Hardcoded to just one user's preferences MEDIA_ROOT = "/Users/pydanny/twoscoops_project/media" And then suggest their way: root = lambda *dirs: join(abspath(BASE_DIR), *dirs) # Configuring MEDIA_ROOT MEDIA_ROOT = root("media") Do you accept the way Two Scoops of Django recommends? In this case MEDIA_ROOT will be inside the project itself. This is bad, I think. This is somehow a mix of code and user data. So, I like what the documentation of Django recommends: just hardcode a path to /var/www/example.com/media/. MEDIA_ROOT is not even STATIC_ROOT. Static files are collected from inside the project. And they contain something which is more or less (CSS) a code. Whereas user uploaded files are definitely the data, not the code. Could you comment? What your MEDIA_ROOT looks like? Shall I use different MEDIA_ROOTS for my local machine and the production serve? -
ManyToMany edit form - django
MultiField admin widget I have a m2m relationship between 2 models and I would like to create a form to edit an userprofile. Model.py class Country(models.Model): id = models.AutoField(primary_key=True) code_iso = models.CharField(max_length=2, default="XX") country_FR = models.CharField(max_length=100, default="Pays inconnu") country_EN = models.CharField(max_length=100, default="Unknown country") def __str__(self): return self.country_FR class UserProfile(models.Model): user = models.OneToOneField(User, related_name='user_profile', primary_key=True) countries = models.ManyToManyField(Country) def __str__(self): return self.user.username I don't know how to create this form (espescially the Media class, how to get js and css from admin profile?). It would be super cool if you guys could help me to write the form/view/url.py :) Thx a lot! PS: I already have a form in a view for profile.html, how can I add a second form on this view (and url)? -
Starting django with uwsgi as systemd service (Ubuntu)
I'm trying to set uwsgi running as systemd process, following the guide, but have some problems. My current systemd config is: [Unit] Description=Photobank Service [Service] WorkingDirectory=/var/www/photobank ExecStart=/usr/local/bin/uwsgi --ini /var/www/photobank/uwsgi.ini Restart=on-failure KillSignal=SIGQUIT Type=notify StandardError=syslog NotifyAccess=all User=root Group=root [Install] WantedBy=multi-user.target When I write sudo service photobank start everything seems fine, excepts the fact the sevice isn't running. In my uwsgi.ini I added a string to log uwsgi output. Thats what I'm getting: *** Starting uWSGI 2.0.13.1 (64bit) on [Tue May 2 12:32:07 2017] *** compiled with version: 5.3.1 20160413 on 12 June 2016 00:25:58 os: Linux-4.4.0-75-generic #96-Ubuntu SMP Thu Apr 20 09:56:33 UTC 2017 nodename: ubuntu-server machine: x86_64 clock source: unix detected number of CPU cores: 4 current working directory: /var/www/photobank writing pidfile to /tmp/photobank-project-master.pid detected binary path: /usr/local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! setgid() to 1000 set additional group 4 (adm) set additional group 24 (cdrom) set additional group 27 (sudo) set additional group 30 (dip) set additional group 46 (plugdev) set additional group 110 (lxd) set additional group 117 (lpadmin) set additional group 118 (sambashare) setuid() to 1000 chdir() to /var/www/photobank/photobank your processes number limit is 63346 your memory page size is 4096 bytes detected … -
source toaster start failed with error start django although it is exists
I am trying to start the Yocto toaster i installed python 2.7 and django Traceback (most recent call last): File "", line 1, in ImportError: No module named 'django' This program needs Django>1.8,<1.9 Please install with pip install -r /home/elia/YoctoProject/poky/bitbake/toaster-requirements.txt i tried also the virtual environment The sys path are: /usr/lib/python2.7 /usr/lib/python2.7/plat-x86_64-linux-gnu /usr/lib/python2.7/lib-tk /usr/lib/python2.7/lib-old /usr/lib/python2.7/lib-dynload /home/elia/.local/lib/python2.7/site-packages /usr/local/lib/python2.7/dist-packages /usr/lib/python2.7/dist-packages django-admin --version returns: 1.8.18 And from the python itself i am getting the django version ok print(django.get_version()) 1.8.18 without the error that source toaster start is telling. Can you please tell me what should i do to start toaster? Thanks! -
Django Got a `TypeError` when calling Model.objects.create()
I have ForeignKey - user on Tasklist Model. When I try create example of TaskList I get this error Got a TypeError when calling Tasklist.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Tasklist.objects.create(). You may need to make the field read-only, or override the TasklistSerializer.create() method to handle this correctly. What should I do to fix this problem? I use this classes class TasklistSerializer(serializers.ModelSerializer): tasks = serializers.StringRelatedField(many=True) class Meta: model = Tasklist fields = ('name', 'tasks') #read_only_fields = ('owner',) class TasklistCreateView(generics.ListCreateAPIView): #queryset = Tasklist.objects.all() serializer_class = TasklistSerializer def get_queryset(self): queryset = Tasklist.objects.all() #list_id = self.kwargs.get('list_id', None) #if list_id is not None: queryset = queryset.filter(owner=self.request.user.id) return queryset def perform_create(self, serializer): #list_id = self.kwargs.get('list_id', None) try: tasklist = Tasklist.objects.get(owner=self.request.user.id) except Tasklist.DoesNotExist: raise NotFound() serializer.save(tasklist=tasklist) -
'home' conflicts with the name of an existing Python module
>>> import django >>> django.VERSION (1, 11, 0, 'final', 1) Could you comment on this: (django11test) michael@ThinkPad:~/workspace/django11test$ python manage.py startapp home CommandError: 'home' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name. It is a newly started project: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] I have always used applications called "home". And now it starts conflicting. I have already used Django 1.11 in another project. And the creation of home application didn't inflict any error messages. Could you comment: with what does it conflict? -
How to dynamically schedule tasks in Django?
I need to build an app in Django that lets the user do some task everyday at the time they specify at runtime. I have looked at Celery but couldn't find anything that will help. I found apply_async and I can get the task to execute once at the specificied duration but not recurrent. I am missing something but don't know what. Please suggest how can I achieve this. -
Problems with pip install django-socketio
pip3 install -U django-socketio outputs the following errors python version on this environment is 3.4.3. The same thing appears when I try to install django channels on python 3.5 or higher Collecting django-socketio Downloading django-socketio-0.3.9.tar.gz (48kB) 100% |████████████████████████████████| 51kB 204kB/s Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-j3y67yvi/django-socketio/setup.py", line 7, in <module> version = __import__("django_socketio").__version__, File "/tmp/pip-build-j3y67yvi/django-socketio/django_socketio/__init__.py", line 2, in <module> from django_socketio.utils import NoSocket, send, broadcast, broadcast_channel File "/tmp/pip-build-j3y67yvi/django-socketio/django_socketio/utils.py", line 44 except IndexError, KeyError: ^ SyntaxError: invalid syntax ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-j3y67yvi/django-socketio/ -
Heroku: Background Tasks in Python with RQ
I am trying to set a background task for my Django app with Heroku. I am following the steps explained in the Heroku documentation. However, I got stuck already at the very beginning. I have installed RQ successfully: pip install rq I created the worker.py file, containing exactly the same code as in the documentation. But then, when I try to run: python worker.py I get the following error: Traceback (most recent call last): File "/Users/MyUser/my_app/lib/python3.5/site-packages/redis/connection.py", line 439, in connect sock = self._connect() File "/Users/MyUser/my_app/lib/python3.5/site-packages/redis/connection.py", line 494, in _connect raise err File "/Users/MyUser/my_app/lib/python3.5/site-packages/redis/connection.py", line 482, in _connect sock.connect(socket_address) ConnectionRefusedError: [Errno 61] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/MyUser/my_app/lib/python3.5/site-packages/redis/client.py", line 572, in execute_command connection.send_command(*args) File "/Users/MyUser/my_app/lib/python3.5/site-packages/redis/connection.py", line 563, in send_command self.send_packed_command(self.pack_command(*args)) File "/Users/MyUser/my_app/lib/python3.5/site-packages/redis/connection.py", line 538, in send_packed_command self.connect() File "/Users/MyUser/my_app/lib/python3.5/site-packages/redis/connection.py", line 442, in connect raise ConnectionError(self._error_message(e)) redis.exceptions.ConnectionError: Error 61 connecting to localhost:6379. Connection refused. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/MyUser/my_app/lib/python3.5/site-packages/redis/connection.py", line 439, in connect sock = self._connect() File "/Users/MyUser/my_app/lib/python3.5/site-packages/redis/connection.py", line 494, in _connect raise err File "/Users/MyUser/my_app/lib/python3.5/site-packages/redis/connection.py", line 482, in _connect sock.connect(socket_address) ConnectionRefusedError: [Errno 61] Connection refused During handling of … -
Creating a JSON RESTful API to load contents of a CSV file and display
I have been given an assignment to load the contents of a CSV file and display the content in a mobile application using Python and Django. I am relatively new to Python and Django. I know of the Django REST framework. But how do I go about with it? Please do let me know -
Uncaught TypeError: Cannot read property 'x' of undefined at jsts.geom.PrecisionModel.makePrecise2 (jsts.js:196) when I try to save in database
I am creating a buffered polygon using JSTS library. Now I want to store it in database but getting this error. Although I get perfect buffer shape on map but problem is in saving into database geom = features[i].geometry; strGeom = new OpenLayers.Format.WKT(geom); input = reader.read(strGeom.toString()); buffer = input.buffer(radius); buffers[i] = parser.write(buffer); Here I got buffered points in buffer . So when I pass this to database It gives this error Any solution why getting this error ? -
Database table doesnt show up in django admin
I'm new to django and I'm wondering why the database table I created with django models won't show up on the admin page. Here's what I did in a bash window. And my admin page. It seems the Cards table has been created but I don't see the table on my admin page and I want to know why. Any advice will be much appreciated. -
How to test migrations faster in Django?
I have tried writing a test on specific migration files. Basically I wanted to test the current state of the database and data between a pair of migrations. I used MigrationExecutor as follows: executor = MigrationExecutor(connection) old_apps = executor.loader.project_state(self.migrate_from).apps executor.migrate(self.migrate_from) # do something here executor.migrate(self.migrate_to) We have so many migration files in the project, so running all of them with unit tests takes a lot of time. Usually, I would set the migration modules to None in the a settings_test.py: MIGRATION_MODULES: { 'my_app': None } With this setting, the test would run really fast. The problem is that the migration files to test (self.migrate_from and self.migrate_to) can no longer be found: django.db.migrations.exceptions.NodeNotFoundError: Node ('poleluxe', '0090_auto_previous_migration') not a valid node So I had to include the migration modules again in the test. Is there a way to include migration files without running all them? In my case, I want to skip all the migrations from 0001 to 0089 and run only 0090 (as self.migration_from) and 0091 (as self.migrate_to).