Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Attach link to a button in Django
The following Django template code for opening a different page template works fine: <p> <a id="selenium" href="{% url 'javascript:results' %}">Selenium</a> </p> However, I want the link to open upon button click, but the followng code does not work: <button> <a id="selenium" href="{% url 'javascript:results' %}">Selenium</a> </button> How do I attach a link to a button in Django then? -
Pyinstaller windowed and noconsole is not working
I'm using pyinstaller 3.3.1 and python 3.6.My problem is I cant run pyinstaller script in both no-console and windowed mode. My project is a web application built using Django 1.9. Error Log: Error: [<class 'OSError'>, OSError(9, 'The handle is invalid', None, 6, None), <traceback object at 0x03B098A0>] Traceback (most recent call last): File "site-packages\django\core\handlers\base.py", line 149, in get_response File "site-packages\django\core\handlers\base.py", line 147, in get_response File "crumbs_tableau\views.py", line 1603, in parser File "site-packages\django\shortcuts.py", line 67, in render File "site-packages\django\template\loader.py", line 96, in render_to_string File "site-packages\django\template\loader.py", line 43, in get_template django.template.exceptions.TemplateDoesNotExist: helpers/error.html Internal Server Error: / Traceback (most recent call last): File "crumbs_tableau\views.py", line 286, in parser File "crumbs_tableau\views.py", line 248, in mac_list File "subprocess.py", line 336, in check_output File "subprocess.py", line 403, in run File "subprocess.py", line 667, in __init__ File "subprocess.py", line 905, in _get_handles File "subprocess.py", line 955, in _make_inheritable OSError: [WinError 6] The handle is invalid -
what is the best way to test modules in views?
I have gone through this post, but it didn't contain any relevant answer. I am using Django 1.11 , and my views.py is modular (not class based). I want to test views modules (functions) in the shell, in django's python shell. >>> python manage.py shell Is there any preferred way or shall I import views from django in shell or copy the function directly ? What is the best practice for this? -
django-taggit: how to programmatically create tags?
For example: tags_input = "hello, foo, bar, ok" tagset = tag_parser(tags_input) # {'bar', 'foo', 'hello', 'ok'} obj = Post(title=title, tags=tagset) obj.save() The above snippet doesn't seem to work. How can I create tags programmatically? e.g. in views -
How to scrape data from inside Django app
As an exercise, I came up with an idea of the following Django project: a web app with literally one button to scrape room data from Airbnb and one text area to display the retrieved data in a sorted manner. Preferably, for scraping I would like to use Selenium, as there is no API for this page. So the button would somehow need to launch the browser automation. So question number one is: is it possible to launch selenium from a web app? Furthermore, I already have the working script for collecting the data, however I dont't know how to fit it in a Django project: models, views, separate script? My initial idea was to launch the scraping script on button click, then dump retrieved room-related data to database (updating model's Room attributes like "price" and "link" for example) and display the data back in the text area mentioned before. So question two is: is it possbile to launch Python script in a web app on button click, for example by nesting in a Django template? Or would other technologies be required, such as Javascript? I know my question is general, but I am also looking for general advice, not … -
Use Django to programmatically drop and create indexes at runtime
I am writing an app using python and Django that inserts approximately 800 million records across about 1000 tables per day into a PostgreSQL database. I want to drop the indexes on the tables before processing and then recreate them afterwards. I can directly execute on the connection.cursor to achieve this, (e.g. this post provides a good example of dropping indexes) but I was wondering if there is a more elegant solution using the Django Index object to achieve this? I haven't seen anything except declarative uses of the Index object. Any help much appreciated. -
Issue with many to many relationships
I am not able to add one more player to this coach. Essentially a player can have many coaches, and a coach can have many players under him. I tried to do a Many to Many relationships but then I was able to add the same player to the same coach twice. What should I do here ? class CoachPlayer(models.Model): coach = models.OneToOneField('Coach', on_delete=models.CASCADE) player = models.ForeignKey('player.Player', on_delete=models.CASCADE) start_date = models.DateTimeField(auto_now_add=True) -
I searched lot in Django Doc but i did not find useful difference between this self.kwargs['pk'] vs self.kwargs.get('pk', None)?
I searched lot in Django Doc but i did not find useful difference between this self.kwargs['pk'] vs self.kwargs.get('pk', None) please what is the difference between this two in Django -
Create Generator from queryset results - Python?
I am new to python I need to convert this following function to the generator to save memory, how can I achieve that? question = <QuerySet [<Question: foobar?.>]> for index, question in enumerate(questions): if question["pk"] == self.pk: try: next_question = questions[index + 1] if next_question["pk"]: prev_next.update({"next" : next_question["pk"] }) except IndexError: prev_next.update({"complete" : True }) try: if index > 0: previous_question = questions[index - 1] if previous_question["pk"]: prev_next.update({"prev" : previous_question["pk"] }) except IndexError: pass return prev_next -
Django output Fixtures from UserTeams
I am trying to print a list of fixtures for the logged in player, where the fixtures they can view are only those for the teams they are a member of. Basically I want to output the fixtures where the hometeamID/awayteamID = each teamID in UserTeams where the userID = request.user. Fixtures model: class Fixtures(models.Model): fixture = models.CharField(max_length=100) hometeamID = models.ForeignKey(Team,related_name='team1',on_delete=models.CASCADE) awayteamID = models.ForeignKey(Team,related_name='team2',on_delete=models.CASCADE) datetime = models.DateTimeField() homegoals = models.PositiveSmallIntegerField() awaygoals = models.PositiveSmallIntegerField() played = models.NullBooleanField() UserTeams model: class UserTeams(models.Model): userID = models.ForeignKey(User,on_delete=models.CASCADE) teamID = models.ForeignKey(Team,on_delete=models.CASCADE) Fixtures View: def fixturesview(request): query = Fixtures.objects.all() return render(request, 'teammanager/fixtures.html', { "fixtures": query }) HTML: <p>Fixtures</p> {%for team in teams%} <h3>{{fixtures.fixture}}</h3> {%endfor%} -
wkhtmltopdf with pdfkit not working on VPS server
I've installed wkhtmltopdf and xvfb. It's working fine in server with command line as well as in django/python shell but with uwsgi+nginx it throwing the below error wkhtmltopdf exited with non-zero code 127. error: /usr/bin/xvfb-run: 25: /usr/bin/xvfb-run: awk: not found /usr/bin/xvfb-run: 97: /usr/bin/xvfb-run: getopt: not found Django Version: 1.11.6 Exception Type: OSError Exception Value: wkhtmltopdf exited with non-zero code 127. error: /usr/bin/xvfb-run: 25: /usr/bin/xvfb-run: awk: not found /usr/bin/xvfb-run: 97: /usr/bin/xvfb-run: getopt: not found Exception Location: /home/dev/env3/lib/python3.5/site-packages/pdfkit/pdfkit.py in to_pdf, line 159 Python Executable: /usr/bin/uwsgi-core Python Version: 3.5.2 Thanks. -
Receive thumbnail of uploaded video in javascript
I have an upload box which changes its background to the uploaded image via the following code: $('input#id_image').on('change', function(e) { var imagePath = URL.createObjectURL(e.target.files[0]); $('.add_file_label').css('background', 'url(' + imagePath + ') scroll no-repeat center/cover'); }); however I want to be able to change the background when a video is uploaded, using a randomly generated thumbnail. I can already acquire that thumbnail in my Django backend via the following code using Moviepy (instance is the uploaded FileField: def generate_thumbnail(instance): filename = instance.image.path thumbnail = VideoFileClip(filename) name = random_string() + '.png' time = random.randrange(60) thumbnail.save_frame('media/' + name, t=time, withmask=True) instance.thumbnail = name and this thumbnail is used as the thumbnail after the form is submitted. However I need to obtain the thumbnail before the form is submitted as I want the upload box to change its background to the thumbnail as soon as the user selects their uploaded video (similar to how it changes when someone uploads an image). So is there any way to obtain the thumbnail generated from my Django backend? The thumbnail saves in my media folder but that's only after the form has been submitted so it isn't accessible via AJAX. Or could generating the thumbnail in the front-end … -
Customize Python package - django-paypal
I'm working on a project in which I need to make some changes in django-paypal package. I have cloned the package's GitHub repo and make a very simple change (Just change a form submit type=image source) and then install it via python setup.py install but now I couldn't find any path to import this package. For example when I install it by using pip install django-paypal i was able to import it like from paypal.standard.forms import PayPalPaymentsForm but after installing it via python setup.py install from my local changed source then it couldn't find any paypal package. How can i fix this issue? Help me, please! Thanks in advance! -
django data migration type not mach error
I have the following model class Region(models.Model): polygon = models.PolygonField(_("polygon")) name = models.CharField(_("name"), max_length=100) Now I am going to convert PolygonField to MultiPolygonField and for sure I have to convert the current data type from Polygon to MultiPolygon. The migration I have written: def convert_polygon_to_multipolygon(): migrations.RunSQL(""" UPDATE locations.region set polygon_tmp = (Select ST_Multi(polygon) from locations_region) """) class Migration(migrations.Migration): operations = [ migrations.AlterField( model_name='region', name='polygon', field=django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326, verbose_name='polygon'), ), migrations.RunPython(convert_polygon_to_multipolygon), ] In which I change column type and then convert data, but I am facing this error: django.db.utils.DataError: Geometry type (Polygon) does not match column type (MultiPolygon) The other way I tried was to first create a new column with MultiPolygon type, then copy and convert Polygon column data to MultiPolygon in this new column, then remove the old Polygon column and rename the new column to Polygon again, which encounters the same error again. My migraion: def convert_polygon_to_multipolygon(): migrations.RunSQL(""" UPDATE locations.region set polygon_tmp = (Select ST_Multi(polygon) from locations_region) """) class Migration(migrations.Migration): operations = [ migrations.AddField( model_name='region', name='polygon_tmp', field=django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326, verbose_name='polygon', null=True), ), migrations.AlterField( model_name='region', name='polygon', field=django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326, verbose_name='polygon'), ), migrations.RunPython(convert_polygon_to_multipolygon), migrations.RemoveField( model_name='region', name='polygon', ), migrations.RenameField( model_name='region', old_name='polygon_tmp', new_name='polygon', ), ] where is the problem? tnx -
how to give a user to a model field to choose from during signup?
how to make a user registration form including a model field in it as a required field? like i want college field to show up on registration page as a drop-down menu my models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) college = models.ForeignKey(College, on_delete=models.CASCADE) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() class College(models.Model): col = models.CharField(max_length=100) def __str__(self): return self.col my forms.py class SignUpForm(UserCreationForm): college = forms.CharField() class Meta: model = User fields = ('username', 'college', 'password1', 'password2', ) and the views.py includes this: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'registration_form.html', {'form': form}) -
django - Importing dictionary data into model data with Foreign Key
I get the below model.py from django.db import models class User(models.Model): user_name = models.CharField(max_length = 50) def __str__(self): return self.user_name class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) hobby = models.CharField(max_length = 50, unique = True) job = models.CharField(max_length = 60) I created a user object instance named 'Elvin'. I get the below views.py from django.shortcuts import render from django.db import IntegrityError from .models import User, Profile item = { 'user': 'Elvin', 'hobby': 'horse riding', 'job': 'banker'} def create(request): try: profile = Profile.objects.create(**item) profile.save() except IntegrityError: pass template = 'index.html' thing = Profile.objects.order_by('-hobby') context = {'thing':thing} return render(request, template, context) However, it returns a ValueError. Cannot assign "'Elvin'": "Profile.user" must be a "User" instance. I wonder how i can import my dictionary data into a ForeignKey data in model data? Thanks. -
myslq-python install error: Cannot open include file: 'config-win.h
Hi, Im trying to 'pip install mysql-python' and I keep getting an error. I was wondering if anyone knows what I need to do get this working? I'm using Windows 10, python 3.6 and mysql 5.7. I'm new to coding so if there is something I missed please let me know. Thanks This is the error I keep getting: _mysql.c(42): fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.13.26128\\bin\\HostX86\\x64\\cl .exe' failed with exit status 2 -
django.db.utils.DataError: invalid input syntax for integer: "user"
I made one change to my model, everything went fine during python manage.py makemigrations but then when I ran python manage.py migrate I got this error and traceback: django.db.utils.DataError: invalid input syntax for integer: "user" File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/usr/local/lib/python2.7/dist-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 "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 515, in alter_field old_db_params, new_db_params, strict) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field new_db_params, strict, File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 684, in _alter_field params, File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in … -
Does django accept Jinja loop together with condintion in one line?
There's a wonderful example in Jinja docs regarding how not to use break: {% for user in users if not user.hidden %} <li>{{ user.username|e }}</li> {% endfor %} However when trying to use similar approach in Django template it gives me error: TemplateSyntaxError at /childminder/task-list/ 'for' statements should use the format 'for x in y': for link in form.links if link.status == form.status Original code: {% for link in form.links if link.status == form.status %} {% url link.url id=application_id %} {% else %} {% for link in form.links if link.status == "Other" %} {% url link.url id=application_id %} {% endfor %} {% endfor %} Point is that I list of links in a list of forms (so those links belongs to specific form only), and there's status and url in that list of links. IF all link statuses didn't match form statuses THEN search for link status Other and print it's link. Can't come up with another approach. Just adding one more link_default object to a form doesn't sound too good for me. -
MoviePy error: the file /tmp/testvideo.mp4 could not be found ! Please check that you entered the correct path
I'm trying to generate a thumbnail from an uploaded video using Moviepy. Here's my function (instance is the uploaded FileField (video)): def generate_thumbnail(instance): filename = instance.image.path.split('/')[-1] print(filename) #successfully prints name of uploaded file: "testvideo.mp4" thumbnail = VideoFileClip('/tmp/%s' % filename) #this line sparks the error name = random_string() + '.png' time = random.randrange(60) thumbnail.save_frame('media/' + name, t=time, withmask=True) instance.thumbnail = name thumbnail = VideoFileClip('/tmp/%s' % filename) returns the error: OSError at /post/ MoviePy error: the file /tmp/testvideo.mp4 could not be found ! Please check that you entered the correct path. Full Traceback: Traceback: File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/Users/zorgan/Desktop/project/site/post/views.py" in post 50. generate_thumbnail(instance) File "/Users/zorgan/Desktop/project/site/functions/helper_functions.py" in generate_thumbnail 45. thumbnail = VideoFileClip('/tmp/%s' % filename) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/moviepy/video/io/VideoFileClip.py" in __init__ 81. fps_source=fps_source) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/moviepy/video/io/ffmpeg_reader.py" in __init__ 32. fps_source) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/moviepy/video/io/ffmpeg_reader.py" in ffmpeg_parse_infos 272. "path.")%filename) Exception Type: OSError at /post/ Exception Value: MoviePy error: the file /tmp/testvideo.mp4 could not be found ! Please check that you entered the correct path. Any idea what the problem is? -
Model object has no attribute HyperlinkedRelatedField
I've checked dozens of examples and I think I am doing it the right way, however I am getting this error message 'City' object has no attribute 'store', Please help, see my serializer enclosed. class CitySerializer(serializers.HyperlinkedModelSerializer): store = serializers.HyperlinkedRelatedField(view_name = 'store:listStoreByCity',read_only=True) class Meta: model = City read_only_fields = ['location'] fields = [ "city", "latitude", "longitude", "store", "state", "img", "location", ] -
Expecting None type value for PositiveSmallIntegerField
I have following model class class GroupstageTournamentModel(ClusterableModel): #Score of TEAM 1 team_1_first_halftime_score = models.PositiveSmallIntegerField(blank=True, default=None, verbose_name='Resultat 1. HZ') team_1_first_halftime_point = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Punkte 1. HZ') team_1_second_halftime_score = models.PositiveSmallIntegerField(blank=True, default=None, verbose_name='Resultat 2. HZ') team_1_second_halftime_point = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Punkte 2. HZ') team_1_shootout_score = models.PositiveSmallIntegerField(blank=True, default=None, verbose_name='Resultat Shootout') team_1_shootout_point = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Schootout Punkte') team_1_total_score = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Resultat Total') team_1_total_points = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Punkte Total') #Score of TEAM 2 team_2_first_halftime_score = models.PositiveSmallIntegerField(blank=True, default=None, verbose_name='Resultat 1. HZ') team_2_first_halftime_point = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Punkte 1. HZ') team_2_second_halftime_score = models.PositiveSmallIntegerField(blank=True, default=None, verbose_name='Resultat 2. HZ') team_2_second_halftime_point = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Punkte 2. HZ') team_2_shootout_score = models.PositiveSmallIntegerField(blank=True, default=None, verbose_name='Resultat Shootout') team_2_shootout_point = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Schootout Punkte') team_2_total_score = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Resultat Total') team_2_total_points = models.PositiveSmallIntegerField(blank=True, default=0, verbose_name='Punkte Total') And as you can see some of my PositiveSmallIntegerField's are deafult=None. And if I save this model I get an Error django.db.utils.IntegrityError: NOT NULL constraint failed: tournament_groupstagetournamentmodel.team_1_first_halftime_score Can I somehow ignore this error and save this model? I deliberately made the default value None -
Django admin site gives error on Djangae
I have a Django app that works perfectly on google app engine, using the datastore via djangae. However, the admin site throws an error: NotSupportedError at /admin/auth/user/5629499534213120/change/ Cross-join where filters are not supported on the Datastore This error only occurs when trying to edit the default Django user model. Not sure why this is happening but I need help ASAP! -
Filtering django REST results by SerializerMethodField
How would I filter results based on a computed field from a Serializer? I tried treating it like any other field, but django doesn't like it. Serializer class ImageSerializer(serializers.ModelSerializer): is_annotated = serializers.SerializerMethodField('has_annotation') class Meta: model = Image fields = '__all__' @staticmethod def has_annotation(image): return image.annotation_set.count() > 0 View class ImageViewSet(viewsets.ModelViewSet): serializer_class = ImageSerializer lookup_field = 'id' permission_classes = [ Or(IsAdmin), IsAuthenticated ] def get_queryset(self): queryset = Image.objects is_annotated_filter = self.request.query_params.get('is_annotated', None) if is_annotated_filter is not None: queryset = queryset.filter(is_annotated=is_annotated_filter) queryset_order = get_queryset_order(self.request) return queryset.order_by(queryset_order).all() http://www.django-rest-framework.org/api-guide/filtering/#filtering-against-query-parameters http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield -
How to set dynamic content in a javascript popover
I have a page showing a large number of words. For each word I can run a non-trivial database query (left joining a few tables, for example). I would like the result of that query to be shown in a popover when I click on the word. Running all the queries when the page is generated is not really an option as it would take a long time and be a bit wasteful. Ideally, I would have a setup where, when clicking on the word, I somehow send a query to the server which would respond with the query result. I would then display the query result in the popover. I am a beginner when it comes to webdev, but I imagine I am not the first person to have this use-case. What would be the easiest way of obtaining the effect I have described above? I am using popover.js (via Bootstrap 4). The server is written in Django, if it matters.