Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Scrapy don't run callback function for scrapy.Request
I'm creating an application on windows 10. And on this operating system everything works fine! But requests stopped returning the callback function after the migration to Google Cloud (Ubuntu 16.4). My Spider: class ExampleSpider(scrapy.Spider): name = 'examplespider' custom_settings = { 'COOKIES_ENABLED': True, } some_proxy = '80.211.179.205:3128' some_user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/530.5 (KHTML, like Gecko) Chrome/2.0.172.0 Safari/530.5' # 1. Begin def start_requests(self): print('Step 1. Setup') return self.create_queue() # 2. Preparation of queues for working def create_queue(self): try: # ...some code... queues = [{'id':1},{'id':2},{'id':3},{'id':4},{'id':5}] logging.info("Create queue") # Create products items and start parsing for item in queues: # Request yield self.request_to_page(item['id']) except Exception as e: print('E:' + str(e)) # 3. Request to page def request_to_page(self, item_id): listing_page_url = 'https://www.example.com/%s/' % 'page.html' print('Sending of request to listing page: %s' % listing_page_url) return scrapy.Request( listing_page_url, self.parse, meta={ 'item_id': item_id, 'proxy': 'http://' + self.some_proxy + '/' }, headers={ 'User-Agent': self.some_user_agent }, errback=self.error_callback, dont_filter=True ) # 4. Parse def parse(self, response): # Get item id from meta of request item_id = response.meta['item_id'] print('Success!' + item_id) # Error def error_callback(self, err): print('ERR:' + str(err)) Messages in console: Step 1. Setup Sending of request to listing page: https://www.example.com/page.html/ Sending of request to listing … -
'caching_sha2_password' plugin failing on Windows
I am currently trying to create a web application with Python's Django framework, while creating the databases through MySQL. I am running Windows 10, Django 2, Python3.6, and MySQL 8. I have tried many fixes but nothing seems to work. When I try to run test cases or run the server locally, I receive the same error: django.db.utils.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: The specified module could not be found.\r\n") Thanks in advanced! -
Why do Get and Filter give different results? (Django)
I am developing an app where students can evaluate their teachers. I have several models, but the important ones for this question are these: class Professor(models.Model): name = models.CharField(max_length=50,null=True) categories = models.ManyToManyField(Category, related_name='professors') def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=50,null=True) professors = models.ManyToManyField(Professor, related_name='students',through='Studentprofesor' ) def __str__(self): return self.name class Studentprofesor(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) professor = models.ForeignKey(Professor, on_delete=models.CASCADE) tested = models.BooleanField(default=False) As far as I knew the main difference between get and filter was that I couldn't use get when there were several objects with the features I was looking for. But apart from that, they worked in a similar way. get for a single object, filter for several objects. However, in this case I get different results when I run get and filter. if I use get: Student.objects.get(name="Mike").professors.all() I obtain: <QuerySet [<Professor: Tom>, <Professor: Jenn>]> But if I use filter: Student.objects.filter(name="Mike").professors.all() I obtain: AttributeError: 'QuerySet' object has no attribute 'professors' it's as if filter is not able to follow the manytomany relationship between the objects. Why is this happening? -
overrided delete() method not working on all part of django admin
I have two tables in my Django model, Category and Image. when I create a Category, an Image creates automatically, and when a Category deletes, The corresponding Image will be destroyed. I override the delete() method in Category. It works correctly when I click delete button in the details page of the model(it removes corresponding Image objece): But when I want to delete the Category object in the listed objects page: It doesn't remove the corresponding Image object. How can I fix this and delete every Category I selected and so that it removes every corresponding Image Objects? My models.py is like: from django.db.models import Q class Image(models.Model): image_id = models.IntegerField(unique=True, null=True) image = models.FileField(upload_to='all/', null=True, blank=True) def __str__(self): return '%s | %s' % (self.image_id, self.image) class Category(models.Model): category_id = models.IntegerField(primary_key=True, default=id_generator, unique=True, editable=False) title = models.CharField(max_length=50, null=False, blank=False) c_thumbnail = models.FileField(upload_to='img/thumbnailCategory/', null=False, blank=False) def delete(self, **kwargs): image = Image.objects.get(Q(image_id=self.category_id)) image.delete() super(Category, self).delete() def save(self, force_insert=False, force_update=False, *args, **kwargs): super(Category, self).save(force_insert, force_update, *args, **kwargs) # this will create or update an Image Image.objects.update_or_create(image_id=self.category_id, image=self.c_thumbnail) super(Category, self).save(force_insert, force_update, *args, **kwargs) def __str__(self): return '%s | %s' % (self.title, self.category_id) Thanks in advance. -
Django rest framework serializers field with read_only in extra_kwargs
I need to pass "pk" to update method while I getting "PUT" request, so I wrote explicit "pk" field in serializer, but I do not need this field to be read_only in other cases. Do I have to write another serializer? I've found this method, but it doesn't work with read_only "extra_kwargs". class HolidaySerializer(serializers.HyperlinkedModelSerializer): pk = serializers.IntegerField() start_date = serializers.DateField() end_date = serializers.DateField() class Meta: model = Holiday fields = ('pk', 'start_date', 'end_date') def get_extra_kwargs(self): extra_kwargs = super().get_extra_kwargs() action = self.context['view'].action if action in ['update', 'partial_update']: extra_kwargs = {'pk': {'read_only': False}} if action in ['create']: extra_kwargs = {'pk': {'read_only': True}} return extra_kwargs Note that, the HolidaySerializer is connected with TermSerializer in this way: class TernSerializer(serializers.ModelSerializer): holiday = HolidaySerializer(many=True, partial=True) Thank you in advance -
Proper replacement for CELERY_RESULT_BACKEND when upgrading to Celery 4.x for django 1.11
In trying to replace django-celery and upgrade celery to 4.x from an inherited project, I'm having hard time understanding the real changes to effect. Celery is already setup as the project uses 3.x, however in removing djcelery from the app, I come across this: CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend' CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' Reading the docs, I'm more confused about using result_backend or celery.backend.database or which: CELERY_RESULT_BACKEND = 'celery.backends.database' CELERYBEAT_SCHEDULER = 'beat_scheduler' OR CELERY_RESULT_BACKEND: result_backend CELERYBEAT_SCHEDULER: beat_scheduler I'm new to Celery, still getting familiar with the details. -
Django - Getting initial value before altering user input in generic UpdateView?
Say for example I have a model that stores Fruits as Apples, Bananas and Oranges inside a basket (every separate instance is going to be a basket). class Project(models.Model): apples = models.DecimalField('Apples!', decimal_places=2, max_digits=7) oranges = models.DecimalField('Oranges!', decimal_places=2, max_digits=7) bananas = models.DecimalField('Bananas!', decimal_places=2, max_digits=7) Use case: There are A, B and C Apples, Oranges and Bananas in the database in separate baskets. User presses on separate basket to update, gets his apples, oranges and bananas fields. He inputs X amount of Apples, Y amount of Oranges and Z amount of Bananas in the database. There are now A+X apples, Y+B oranges and C+Z bananas. In other words, instead of just updating the amount of fruit, user simply adds to them (without subtracting for the moment) The problem is, when trying to override the save() method in forms.py, I cannot seem to properly access the current instance of the basket and, therefore, the correct amount of currently-placed fruit in the basket. Updating with my programmatic additions works, but I cannot get the initial values. How do I do it? class BasketForm(ModelForm): class Meta: model = Basket fields = ['apples', 'oranges', 'bananas'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.add_input(Submit('submit', … -
Unable to create an integration test for Django's reset password flow
I'm trying to implement an integration test for the password reset flow, but I'm stuck at the "password_reset_confirm" view. I already tested the flow manually, and it works fine. Unfortunately, the Django unit test client seems unable to follow correctly the redirects required in this view. urls config from django.contrib.auth import views as auth_views url(r"^accounts/password_change/$", auth_views.PasswordChangeView.as_view(), name="password_change"), url(r"^accounts/password_change/done/$", auth_views.PasswordChangeDoneView.as_view(), name="password_change_done"), url(r"^accounts/password_reset/$", auth_views.PasswordResetView.as_view(email_template_name="app/email/accounts/password_reset_email.html", success_url=reverse_lazy("app:password_reset_done"), subject_template_name="app/email/accounts/password_reset_subject.html"), name="password_reset"), url(r"^accounts/password_reset/done/$", auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), url(r"^accounts/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$", auth_views.PasswordResetConfirmView.as_view( success_url=reverse_lazy("app:password_reset_complete"), form_class=CustomSetPasswordForm), name="password_reset_confirm"), url(r"^accounts/reset/complete/$", auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete"), Test code import re from django.urls import reverse, NoReverseMatch from django.test import TestCase, Client from django.core import mail from django.test.utils import override_settings from django.contrib.auth import authenticate VALID_USER_NAME = "username" USER_OLD_PSW = "oldpassword" USER_NEW_PSW = "newpassword" PASSWORD_RESET_URL = reverse("app:password_reset") def PASSWORD_RESET_CONFIRM_URL(uidb64, token): try: return reverse("app:password_reset_confirm", args=(uidb64, token)) except NoReverseMatch: return f"/accounts/reset/invaliduidb64/invalid-token/" def utils_extract_reset_tokens(full_url): return re.findall(r"/([\w\-]+)", re.search(r"^http\://.+$", full_url, flags=re.MULTILINE)[0])[3:5] @override_settings(EMAIL_BACKEND="anymail.backends.test.EmailBackend") class PasswordResetTestCase(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.myclient = Client() def test_password_reset_ok(self): # ask for password reset response = self.myclient.post(PASSWORD_RESET_URL, {"email": VALID_USER_NAME}, follow=True) # extract reset token from email self.assertEqual(len(mail.outbox), 1) msg = mail.outbox[0] uidb64, token = utils_extract_reset_tokens(msg.body) # change the password response = self.myclient.post(PASSWORD_RESET_CONFIRM_URL(uidb64, token), {"new_password1": USER_NEW_PSW, "new_password2": USER_NEW_PSW}, follow=True) self.assertIsNone(authenticate(username=VALID_USER_NAME,password=USER_OLD_PSW)) Now, the assert fails: the user is authenticated with the old password. From the log … -
Unexpected metaclass overriding for the DRF serializers
I'm using Django 1.11.12 and djangorestframework==3.7.7 and python3.6.3 I have several models inherited from one abstract model: class SoftDeleteModel(models.Model): deleted = models.DateTimeField(blank=True, null=True) class Meta: abstract=True And there are a dozens of models inherited from it. I need this deleted field to be shown only for the admin user. Trying not to repeat the same logic again and again I wrote a metaclass and abstract class to make things easier to handle in the serializers. Most parts of the custom metaclass are from serializers.SerializerMetaclass. class SoftDeletionMetaclass(serializers.SerializerMetaclass): @classmethod def _get_declared_fields(cls, bases, attrs): fields = [(field_name, attrs.pop(field_name)) for field_name, obj in list(attrs.items()) if isinstance(obj, Field)] fields.append(("deleted", serializers.SerializerMethodField(read_only=True))) fields.sort(key=lambda x: x[1]._creation_counter) # If this class is subclassing another Serializer, add that Serializer's # fields. Note that we loop over the bases in *reverse*. This is necessary # in order to maintain the correct order of fields. for base in reversed(bases): if hasattr(base, '_declared_fields'): fields = [ (field_name, obj) for field_name, obj in base._declared_fields.items() if field_name not in attrs ] + fields return OrderedDict(fields) def __new__(cls, name, bases, attrs): attrs['_declared_fields'] = cls._get_declared_fields(bases, attrs) meta = attrs.get('Meta') if meta: if isinstance(meta.fields, tuple): meta.fields += ("deleted", ) else: meta.fields.append("deleted") attrs["Meta"] = meta return super(serializers.SerializerMetaclass, cls).__new__(cls, name, … -
Django queryset permissions
I am building a quite complex Django application to be used on top of and email scanning service. The Django application is written using Python 3.5+ This application primarily uses Django Rest Framework to handle communication with the frontend in the browser. The issue that I am currently having is that I try to implement the concept of a System Administrator, Domain Administrator and Application User The System Administrator is basically the "normal" django superuser and is therefore capable of doing everything and see every record in the system. The Domain Administrator is user who manages one or more email domains. I keep track of this using a Many2Many relationship between the users and the domains. The idea would then be to predefine a filter, so that the log of messages processed, will be automatically filtered to show only messages where the sender domain or the recipient domain equal a domain in the list of domains that the given user is assigned to. The same would be true for blacklisting/whitelisting policies. If the Domain Administrator is not assigned to any domains, then no data is shown. The Application User is basically any authenticated user with one or more domains assigned … -
How to pass the dynamic column name in django ORM values
I have data = request.POST (i.e <QueryDict: {u'device': [u'Camera '], u'todate': [u'2018-05-18'], u'fromdate': [u'2018-04-19']}> ) and device = data.get('device', None) which is a column name in database table and a user selected value(which change based on user selection) Monitor.objects.values(device) Now I got the error like Cannot resolve keyword u'Camera ' into field. Choices are: Camera how can I convert column name stored in, device variable into a actual column -
DJANGO Different Timezone Display
Django Beginner here. I'm trying to display different timezones in my template but it's not displaying. HTML File {% load tz %} {% timezone "Europe/Paris" %} Paris time: {{ value }} {% endtimezone %} {% timezone None %} Server time: {{ value }} {% endtimezone %} OUTPUT No Display in HTML -
(1054, "Unknown column 'inventory_attributegroup_categories.xyzcategory_id' in 'where clause'")
I am working on p1 project and accessing the database of other project p2 to read data only. In p2 project the two table are named as AttributeGroup and Category. But in p1 I am using it as class XYZAttributeGroup(models.Model): user = models.ForeignKey('users.GMASUser') name = models.CharField(max_length=50) sort_order = models.PositiveSmallIntegerField(default=0, blank=True) # Deprecated category = models.ForeignKey(XYZCategory, null=True, blank=True) # This is the replacement for above. Will move to this slowly, because massive changes required in frontend # categories = models.ManyToManyField(XYZCategory, related_name='attribute_groups', through='XYZAttributeGroupCategories') categories = models.ManyToManyField(XYZCategory, related_name='attribute_groups') class Meta: unique_together = (('user', 'name', 'category',),) db_table = 'inventory_attributegroup' managed = False def __str__(self): return f"Name:- {self.name} | Gmas User:- {self.user.username}" class XYZCategory(models.Model): user = models.ForeignKey('users.XYZUser') name = models.CharField(max_length=255) products = models.ManyToManyField(XYZProduct, related_name='category', blank=True, through="CategoryProductMapping") parent_category = models.ForeignKey("XYZCategory", db_index=False, null=True, blank=True, default=None, on_delete=models.SET_NULL) image = models.ImageField(blank=True, null=True, upload_to='category') is_featured = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def natural_key(self): return self.user, self.name natural_key.dependencies = ['inventory.product'] def __str__(self): return self.name class Meta: unique_together = (('user', 'name'),) db_table = 'inventory_category' managed = False Fetching all the categories from the gmas_attr. gmas_attr = GMASAttributeGroup.objects.first() gmas_attr.categories.all() I am getting error (1054, "Unknown column 'inventory_attributegroup_categories.xyzcategory_id' in 'where clause'") inventory_attributegroup_categories is throgh table for the above mapping present in project … -
Can store and retrieve Object Django BinaryField in SQLite but not MySQL
I have some implementation that is best served by pickling a pandas dataframe and storing it in a DB. This works fine if the database is sqlite but fails with a load error when it is MySQL I have found other people with similar issues on stackoverflow and google but it seems that everybodys solution is to use sql to store the dataframe. As a last resort I would go down that route but it would be a shame for this use case to do that. Anybody got a solution to get the same behaviour from mysql as sqlite here? I simply dump the dataframe with pickledframe = pickle.dumps(frame) and store pickledframe as a BinaryField pickledframe = models.BinaryField(null=True) I load it in with unpickled = pickle.loads(pickledframe) with sqlite it works fine, with mysql I get Exception Type: UnpicklingError Exception Value: invalid load key, ','. upon trying to load it. Thanks -
How to execute code within SEPARATE transaction
Let we have the code: def some_function(): with transaction.atomic(): # some code which writes to DB try: call_method_which_may_raise_exception() except KnownException as e: save_some_data_about_exception_to_database(e) raise # other code which writes to DB The problem is when I re-raise the exception, my 'SOME DATA' will be lost too, because it's made within same transaction. Is there a context or something to execute code within SEPARATE transaction/connection? There is a point, that the code has bad architect. In a normal flow there should not be a neccessity to save_some_data... As proposed solution they said: def some_function(): exception_to_save = None try: with transaction.atomic(): # some code which writes to DB try: call_method_which_may_raise_exception() except KnownException as e: exception_to_save = e raise # other code which writes to DB except Exception as e: if exception_to_save: save_some_data_about_exception_to_database(exception_to_save) raise But dirty code gets once more dirty. I'd prefer if it was something like: def some_function(): with transaction.atomic(): # some code which writes to DB try: call_method_which_may_raise_exception() except KnownException as e: with transaction.separate_connection(): save_some_data_about_exception_to_database(e) raise # other code which writes to DB Any ideas are welcome! -
django and paypal how to refund using django-paypal package
I'll use django-paypal for processing payments in my site, but, I need the refund funcionality, wich I didnt find in the django-paypal docs. How can I achieve this, if django-paypal doesnt has this featured I'd to move to other package, in that case, any reccommendation? -
Django channels between different docker containers
I'm working with django channels and I have a problem about how to deal with sending a message using channels Context I have 2 containers: celery-worker and api, I want to send data via websockets from celery-worker container to the browser through api container using channels, here a picture: Question Do you know how to "initialize" channels in api container and use this channels inside celery-worker container? to after in celery-worker container call only to Group('pablo').send(message) and it automatically send to the browser. Any advice will be ok. Note: I tried to not post code because is very extensive and maybe It would result difficult to understand the question but if you want I can post some code that you need. -
Django : Dynamically create a database thanks to GUI
I Would like to implement a web page in Django which allow a user to dynamically create a Data Base. The Django model stored will always be the same. (a generic user) Scenario : The user fills up a form with fields like user.firstname, user.lastname .. Then after the submit, django creates a brand new DB on the DBMS. The model is then stored in this new DB. Django save/store this DB setting for further use. I find out Here that it's possible to set up multiple DB's in Django but that implies that they already have been created (Which is obviously not my case). To create my DB I can think of executing an custom SQL query directly on the DBMS like that from django.db import connection def createNewDB(self,id): with connection.cursort() as cursor: queryStr = "\"CREATE DATABASE " + id + "\"" cursor.execute(queryStr) But then I have no clues about : How to save the new DB settings in Django DB (see below). How to migrate and save the model user in the DB Migrate : from django.core.management import call_command call_command("migrate", interactive=False) Save model : user.save(using='db_id') I find this post talking about how to add a connection dynamically with … -
How to deal with django-graphene with UUID primary keys in django?
We use Django and django-graphene to provide GraphQL API. We have UUID primary keys in models. How to properly deal with it? -
CSS won't center list within parent div
This seems like a fairly straightforward issue, and there's certainly enough people asking about similar questions on the site, but after reading through like a dozen and trying a number of things, I'm still stuck. Why? I'm trying to simply center a nav list for pagination on my Django site. Here's my markup: {% if concerts.has_other_pages %} <div class="center"> <ul class="paginator"> {% if concerts.has_previous %} <li><a href="?page={{ concerts.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in concerts.paginator.page_range %} {% if concerts.number == i %} <li class="active"><span>{{ i }}</span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if concerts.has_next %} <li><a href="?page={{ concerts.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> </div> {% endif %} And here's my CSS: .center{ text-align: center; } .center .paginator{ width: 100%; margin: 1em 0; padding: 0; list-style-type: none; } .paginator li{ display: inline-block; float: left; padding: 8px 16px; border-radius: 5px; font-size: 1.3em; text-align: center; } .paginator li a{ padding: 8px 16px; border-radius: 5px; } .paginator li.active{ background-color: #444; } .paginator li a:hover{ background-color: #111; border-radius: 5px; transition: background-color .5s; } All these styles are applying except that no matter what … -
Django Rest Serializer returns empty
I'm following this tutorial (Django Rest Framework) and I'm facing a problem when I try to use serializers. It returns a empty result, instead the 49086 records that it should to return. My query it's ok because when I try to show the data without serializers it's shows these data. Please, what I'm doing wrong? models.py # coding=utf-8 from __future__ import unicode_literals from django.db import models class Workers(models.Model): chapa = models.IntegerField(primary_key=True) emp_cod = models.IntegerField(primary_key=False) class Meta: managed = False db_table = 'WORKERS' serializers.py from rest_framework import serializers from .models import Workers class WorkersSerializer(serializers.ModelSerializer): class Meta: model = Workers fields = '__all__' views.py ... @api_view(['GET']) @permission_classes((permissions.AllowAny,)) def get_all_workers(request): data = Workers.objects.using('rh').all().order_by('emp_cod') print(data.count()) # Returns 49086 serializer = WorkersSerializer(data) print(serializer.data) # Returns {} json = JSONRenderer().render(serializer.data) return Response(json) # Returns Django Rest standard page with "{}" data -
Migration error with wagtail 2.0
Hi i'm trying to upgrade to wagtail 2.0. I have dealt with a series of errors but I can't get past this one which occurs on migration: File "/Users/tim/wagtailcmsdemo/home/migrations/0001_initial.py", line 17, in Migration ('page_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='wagtailcore.Page')), TypeError: init() missing 1 required positional argument: 'on_delete' Any help greatly appreciated Thanks Tim Full console error: (wagtail-isa) MacBook-Air:wagtailcmsdemo tim$ ./manage.py makemigrations Traceback (most recent call last): File "./manage.py", line 10, in execute_from_command_line(sys.argv) File "/Users/tim/Virtualenvs/wagtail-isa/lib/python3.6/site-packages/django/core/management/init.py", line 371, in execute_from_command_line utility.execute() File "/Users/tim/Virtualenvs/wagtail-isa/lib/python3.6/site-packages/django/core/management/init.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/tim/Virtualenvs/wagtail-isa/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Users/tim/Virtualenvs/wagtail-isa/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/Users/tim/Virtualenvs/wagtail-isa/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 78, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/Users/tim/Virtualenvs/wagtail-isa/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in init self.build_graph() File "/Users/tim/Virtualenvs/wagtail-isa/lib/python3.6/site-packages/django/db/migrations/loader.py", line 200, in build_graph self.load_disk() File "/Users/tim/Virtualenvs/wagtail-isa/lib/python3.6/site-packages/django/db/migrations/loader.py", line 109, in load_disk migration_module = import_module("%s.%s" % (module_name, migration_name)) File "/Users/tim/Virtualenvs/wagtail-isa/lib/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 978, in _gcd_import File "", line 961, in _find_and_load File "", line 950, in _find_and_load_unlocked File "", line 655, in _load_unlocked File "", line 678, in exec_module File "", line 205, in _call_with_frames_removed File "/Users/tim/wagtailcmsdemo/home/migrations/0001_initial.py", line 7, in class Migration(migrations.Migration): File "/Users/tim/wagtailcmsdemo/home/migrations/0001_initial.py", line 17, in Migration ('page_ptr', … -
Django - Python: Get sum from 2 fields
In html template I have 3 fields (defined in models.py): A, B and C. It is a form. I want field C to have a sum of A + B when user types some value. Is that something I can do with python or it is necessary JavaScript? -
Python : selenium click on submit no redirect
I'm testing my django administration with Selenium. It's working fine until i want to submit my form. self.webdriver.find_element_by_name('_save').click() Here is the html : <input type="submit" value="Enregistrer" class="default" name="_save"> So it should redirect me to another page, or atleast refresh this page printing errors. But it doesn't. Do you know why submitting doesn't redirect me ? -
Issue versioning api calls
I am trying to create an updated version of an api call. urls.py router.register(r'categories', views.CategoryViewSet) router.register(r'categoriesv2', views.CategoryViewSetV2) However, when I run the internal server, the autogenerated api root is as follows: "categories": "http://10.0.5.119:8000/api/**categoriesv2**/", "categoriesv2": "http://10.0.5.119:8000/api/categoriesv2/", Why is "categories" also pointing to /categoriesv2/ and not /categories/? Any help would be appreciated please!