Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best way to convert a python ( Django + Wagtail ) website to an IOS app?
I built a website using Python ( Django + Wagtail ), and I need to convert it to an ios application. I have no prior experience on ios app development -
heroku logs --tail, unable to understand what follows
I am not being able to deploy my web app on Heroku. The error(I have listed them below) shows many things, of which I understand that psycopg2 = 2.7.2 and python 3.6 version is required. But in my requirement.txt file, when I pip freeze, psycopg2 = 2.8.3 comes, and for developing the web app I used python 3.7.4. Hence I enter python 3.7.4 version in the runtime.txt file. Now my question is, do the errors below suggest that I need to mention psycopg2=2.7.2 and python=3.6.(version)? But when I do that, psycopg2=2.7.2, and python=3.6.8, in the very first step, the push fails(git push Heroku master). What should I do? This my requirement.txt file Django==2.0.13 django-heroku==0.3.1 gunicorn==19.9.0 psycopg2==2.8.3 pytz==2019.2 whitenoise==4.1.4 This is my runtime.txt file python-3.7.4 This is my Procfile web: gunicorn mysite.wsgi --log-file - when I run heroku ps:scale web=1, it shows Scaling dynos... done, now running web at 1:Free but after runningheroku open, it shows errors. On getting the logs,heroku logs --tail`, when I follow the given link in the log history, I get the following errors. -----> Installing requirements with pip Collecting psycopg2==2.7.2 (from -r /tmp/build_323b8a662b13c10001fe839be236c115/requirements.txt (line 6)) Downloading https://files.pythonhosted.org/packages/d2/5a/6c2fe0b4671c81e7525c737d6600a5c82b7550a5f2dff8a01afb616dbbf4/psycopg2-2.7.2-cp36-cp36m-manylinux1_x86_64.whl (2.7MB) Installing collected packages: psycopg2 Found existing installation: psycopg2 … -
drango template webpage file utf-8 decoding error
bootstrap-examples-source-files have utf-8 decoding error in django render webpages. Internal Server Error: / Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response .............. File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb7 in position 471: invalid start byte -
Django loaddata command from docker container
I have a django app that I put inside of a docker container for deployment. I have some initial data that I want to load into the database via the dumpdata and loaddata commands. The initial data lives on my local hard drive. I choose a very naive approach and simply copied the data_backup.json file to the server via scp. Now, I want to load the data_backup.json file (the file sits on the server not in the docker container) by executing: sudo docker-compose exec restapi python manage.py loaddata --settings=rest.settings.production ./data_backup_20191004.json But Django only searches the internal directories for fixtures. I am looking for a way to populate the database with the data_backup.json file inside the docker container. Can someone help? Ultimately, I am looking for a way to dump data directly to S3 and load it from there if needed (for db backups). If you have any tips on how to achieve that, this would also be super helpful - I don't seem to be able to find material on that. -
How to get data from one Django model to query another model within a template loop?
My Django application has two Models 'Items' & 'Colors' representing database tables 'items' and 'colors'. A Django template 'mytemplate.html' renders data gathered from the database with a 'for' loop, printing out a list of items with their properties. One of the fields of 'items' table is a numeric id that correspond to a text field in 'colors' table. Currently I can display all the items with their names and their color numeric id 'cid' (see code below). But I need to print the color name of an item instead of its 'cid'/'id' within the template loop. What is the most efficient way to achieve this? Do I need an intermediary data structure, alter my database to define a foreign key (items(cid) --> colors(id)), ... ? I'm not sure that I want to use a foreign key (items(cid) --> colors(id)) because at the time of first insertion of items 'cid' could be undefined (NULL). Table 'items' +------+------+------+ | id | cid | name | +------+------+------+ | 1 | 3 | barZ | | 2 | 3 | barC | | 3 | 1 | barE | | 3 | 2 | barD | | 4 | 1 | barA | +------+------+------+ … -
Django MultiWidget and field labels
I have a requirement for a Django form that contains 3 forms.Textarea which are compressed into a single models.TextField compatible value. For this, I've subclassed both forms.MultiValueField and forms.MultiWidget. My problem is in trying to identify where and how to add labels to the widget's textarea inputs. What I am currently doing is passing in the label value as an attr to the widget's subwidgets: class ContentWidget(forms.MultiWidget): template_name = 'content_widget.html' def __init__(self, attrs=None): widgets = ( forms.Textarea({'label': 'A'}), forms.Textarea({'label': 'B'}), forms.Textarea({'label': 'C'}), ) super().__init__(widgets, attrs) This lets me keep the content_widget.html pretty concise: {% for subwidget in widget.subwidgets %} <label for="{{ subwidget.attrs.id }}">{{ subwidget.attrs.label }}</label> {% include subwidget.template_name with widget=subwidget %} <br /> {% endfor %} But this also adds the label attr to each html element, which feels a bit hacky: <textarea name="content_0" cols="40" rows="10" label="A" required="" id="id_content_0"></textarea> Another option is to explicitly include it in a more long-form version of the template: <label for="{{ widget.subwidgets.0.attrs.id }}">A</label> {% include widget.subwidgets.0.template_name with widget=subwidget %} ... However, for form elements in general, the label is assigned to the field, but I can't find a way for the widget to access them from the MultiValueField instance if I define them there: class … -
Django manage.py outside of project
Is there a method of having manage.py outside of the Django project directory without having to change all the imports to from backend.<app>.<module> import ...? ├── project │ ├── api │ ├── frontend │ ├── project │ ├── manage.py │ ├── Pipfile │ ├── Pipfile.lock ├── project │ ├── backend │ │ ├── api │ │ ├── project │ │ ├── __init__.py │ ├── frontend │ ├── manage.py │ ├── Pipfile │ ├── Pipfile.lock As expected after moving the Django project into the backend directory and modifying manage.py with the line below there's a ModuleNotFoundError when trying to run the server. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.project.settings') -
Django Project Template Error: django.template.exceptions.TemplateDoesNotExist
I tend to use the same project template for a majority of my Django projects. Till now, I have been using copy-paste to use the template in different projects. (Sorry! I was unware of --template option that comes with django-admin.) I got to know of --template option with django-admin a while back and I have a question regarding the same. The aforementioned template that I use for my projects has some common Django apps, namely, accounts to handle user authentication, pages to handle request to pages like 'About', 'Contact', etc and some generic Django templates like base.html, templates for account activation email and password reset email. Some of the generic Django templates (like the Sign In template) extend base.html in them. This is where the problem arises. I get an error django.template.exceptions.TemplateDoesNotExist: base.html when I try to use my project template with a new project. Traceback: $ django-admin startproject --template=/home/alfarhanzahedi/Projects/django-boilerplate/project_name --extension=py,html simpleqa Traceback (most recent call last): File "/home/alfarhanzahedi/Projects/temp/venv/bin/django-admin", line 10, in <module> sys.exit(execute_from_command_line()) File "/home/alfarhanzahedi/Projects/temp/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/alfarhanzahedi/Projects/temp/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/alfarhanzahedi/Projects/temp/venv/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/alfarhanzahedi/Projects/temp/venv/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/alfarhanzahedi/Projects/temp/venv/lib/python3.7/site-packages/django/core/management/commands/startproject.py", line 20, … -
Django test with setUpTestData doesn't keep changes between tests
classmethod TestCase.setUpTestData() The class-level atomic block described above allows the creation of initial data at the class level, once for the whole TestCase. [...] Be careful not to modify any objects created in setUpTestData() in your test methods. Modifications to in-memory objects from setup work done at the class level will persist between test methods. Cit. django.test.TestCase.setUpTestData Consider this example: class FoobarTest(TestCase): @classmethod def setUpTestData(cls): cls.post = Post() cls.post.stats = {} cls.post.save() def setUp(self): self.post.refresh_from_db() def test_foo(self): self.post.stats['foo'] = 1 self.post.save() self.assertEquals(self.post.stats, {'foo': 1}) # this should fail def test_bar(self): # this run first cause alphabetical order self.post.stats['bar'] = 1 self.post.save() self.assertEquals(self.post.stats, {'bar': 1}) Since Modifications to in-memory objects from setup work done at the class level will persist between test methods I expect one of the two test methods to fail cause the post object will have also a different property and the equality should fail. But this test pass without problem. If i force the execution order it actually behave like expected: class FoobarTest(TestCase): @classmethod def setUpTestData(cls): cls.post = Post() cls.post.stats = {} cls.post.save() def setUp(self): self.post.refresh_from_db() def _foo(self): self.post.stats['foo'] = 1 self.post.save() self.assertEquals(self.post.stats, {'foo': 1}) def _bar(self): self.post.stats['bar'] = 1 self.post.save() self.assertEquals(self.post.stats, {'bar': 1}) def test_foo_bar(self): self._foo() … -
POST list of dictionaries and update or create
Im trying to make my django-rest-framework to accept a list of dicts for updating or creating many objects in one api-call. My model: class Order(models.Model): internal_id = models.CharField(max_length=500, unique=True) external_id = models.CharField(max_length=500, blank=True, null=True, unique=True) status = models.CharField(max_length=500, verbose_name="Status", blank=True, null=True) My seriallizer: class SimpleOrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' My view: class CreateListMixin(): def get_serializer(self, *args, **kwargs): if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super().get_serializer(*args, **kwargs) class OrderViewSet(CreateListMixin, viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = SimpleOrderSerializer lookup_field = 'internal_id' When I try to pass a list with a value on internal_id that exists I want it to update the object. If the internal_id does not exists, I want to create a new objects. Is this possible with django rest framework? -
Django API: How to save/ save as project?
I am developing python backend for django web app. In the application when user clicks on Save or Save As button then I should give pop up for confirmation which can be handled by frontend. But in back end, when user opts to save the progress then I should save whatever progress they have made it on that application. Any ideas? -
How to implement Websockets on AWS using Django and boto3?
I'm planning to implement Websockets communication under Amazon Web Services for my Django project. The usual approach is to use Django Channels library but it's a bit tricky to implement on AWS. Recently it's been developed a native AWS WebSocket API. Python implementation for that is included in boto3 library. I suppose that the native AWS way is preferable but I'm not sure how. How to integrate AWS WebSocket API with a Django project using boto3? -
Migrate error after add new field use django-pgcrypto-fields
Migrate error after add new field use django-pgcrypto-fields My model (migrate okay in the first time) class Dkm(models.Model): name = fields.TextPGPSymmetricKeyField() value = fields.IntegerPGPSymmetricKeyField(default=0) I update model and migrate again: class Dkm(models.Model): name = fields.TextPGPSymmetricKeyField() value = fields.IntegerPGPSymmetricKeyField(default=0) value2 = fields.IntegerPGPSymmetricKeyField(default=0) Error occur Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\vu.tran\Desktop\kona-server\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\vu.tran\Desktop\kona-server\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\vu.tran\Desktop\kona-server\env\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\vu.tran\Desktop\kona-server\env\lib\site-packages\django\core\management\base.py", line 364, in execute cursor.execute(sql, params) File "C:\Users\vu.tran\Desktop\kona-server\env\lib\site-packages\django\db\backends\utils.py", line 99, in execute return super().execute(sql, params) File "C:\Users\vu.tran\Desktop\kona-server\env\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\vu.tran\Desktop\kona-server\env\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\vu.tran\Desktop\kona-server\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\vu.tran\Desktop\kona-server\env\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\vu.tran\Desktop\kona-server\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: column "value3" is of type bytea but default expression is of type integer HINT: You will need to rewrite or cast the expression. The error will not occur if set null=True -
Django + Ajax + dependent dropdown
In my Django project I need dependent dropdown input (registration form: date & timeslot). However, AJAX does not display the dependent dropdown menu correctly (timeslot). I have based everything on This example, but I can't find out what I am doing wrong. The variable (id_timeslots) that is passed to AJAX by load_timeslots() in view.py has the correct length throughout. The timeslot dropdown menu, however, is empty (not even a "---" and very small in size. Hope someone can point me in the right direction. models.py class Day(models.Model): day = models.CharField(max_length=30) def __str__(self): return self.day class TimeSlot(models.Model): day = models.ForeignKey(Day, on_delete=models.CASCADE) timeslot = models.CharField(max_length=30) reserved = models.BooleanField(default=False) def __str__(self): return self.timeslot class Person(models.Model): name = models.CharField(max_length=100) email = models.EmailField() day = models.ForeignKey(Day, on_delete=models.SET_NULL, null=True) timeslot = models.ForeignKey(TimeSlot, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name forms.py class TimeSlotForm(forms.ModelForm): class Meta: model = Person fields = ('name','email', 'day', 'timeslot') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['timeslot'].queryset = TimeSlot.objects.none() view.py class ExpSignup(TemplateView): template_name = 'thesis_scheduler/index.html' def get(self,request): timeslotdata = TimeSlotForm() return render(request, self.template_name, {'timeslotdata':timeslotdata}) def load_timeslots(request): day_id = request.GET.get('day') id_timeslots = TimeSlot.objects.filter(day=day_id, reserved=False) return render(request, 'thesis_scheduler/index.html', {'id_timeslot': id_timeslots}) url.py urlpatterns = [ path('', views.ExpSignup.as_view(), name='Registration'), path('ajax/load-timeslots/', views.load_timeslots, name='ajax_load_slots'), # <-- this one here ] index.html … -
How to add datetime format minute on each loop in pyhton django
This is my code. i want to add 25 minute on loop then save in DB, i try one solution but its just add 1 time add 25 minute. i want 1st time system enter actual datetime on second loop in datetime add 25 minute. service_obj = Service.objects.get(id=1) startingDate = datetime.strptime(startingDate, '%d-%m-%Y %I:%M %p').strftime("%Y-%m-%d %H:%M:00+00") service_fee = StaffServiceFee.objects.filter(service_id=service_obj.id).values_list('service_charges', 'staff_user').order_by('id') for service_fees in service_fee: obj = UserAppointments.objects.create(customer_id=1, staff_user_id=service_fees[1], service=service_obj, status="1") obj.date_time = startingDate obj.save() -
How to create Django-Rest-framework permission interface like django-admin provide | is there any library available for that?
How to create a User interface like django-admin provide for granting/revoking permissions for Django-Rest APIs. and automatically handle it. I mean I need a generic functionality, admin user can grant/revoke permissions or APIs to a particular group. I am searching from last 3 hours but found nothing Thanks -
allauth - enforce new user to provide mandatory fields
I'm trying to add django-allauth to a custom user model. class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True, help_text="A verification link will be sent to this email-id") name = models.CharField(max_length=254, null=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Please enter a valid phone number.") mobile = models.CharField(max_length=16,validators=[phone_regex],null=True,) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['mobile','name'] Here's my custom form class CustomUserCreationForm(UserCreationForm): password2=None def signup(self, request, user): user.mobile = self.cleaned_data['mobile'] user.name = self.cleaned_data['name'] user.save() return user class Meta(UserCreationForm): model = User fields = ('name','email','mobile') and in settings.py, I've ACCOUNT_FORMS = {'signup':'users.forms.CustomUserCreationForm'} When I open the /signup/ page, the custom form gets displayed and the additional values get saved. However, when I click on the Sign In and then click on the Google, and then provide the email and password of a user that is not in the system, after the redirect the user gets created without asking for additional fields. How can I enforce the new user to provide mandatory fields, after getting authenticated through social? (Please let me know if I need to provide additional settings or any any other code) Thanks -
Using a Textfield with JSON instead of a ForeignKey relationship?
I am working on a project where users can roll dice pools. A dice pool is, for example, a throw with 3 red dice, 2 blue and 1 green. A pool is composed of several dice rolls and modifiers. I have 3 models connected this way: class DicePool(models.Model): # some relevant fields class DiceRoll(models.Model): pool = models.ForeignKey(DicePool, on_delete=models.CASCADE) # plus a few more information fields with the type of die used, result, etc class Modifier(models.Model): pool = models.ForeignKey(DicePool, on_delete=models.CASCADE) # plus about 4 more information fields Now, when I load the DicePool history, I need to prefetch both the DiceRoll and Modifier. I am now considering replacing the model Modifier with a textfield containing some JSON in DicePool. Just to reduce the number of database queries. Is it common to use a json textfield instead of a database relationship? Or am I thinking this wrong and it's completely normal to do additional queries to prefetch_related everytime I load my pools? I personally find using a ForeignKey cleaner and it would let me do db-wise changes to data if needed. But my code is making too many db queries and I am trying to see where I can improve it. FYI: … -
Unsupported media type \"application/x-www-form-urlencoded\" in request
I am using ViewSets for Profile model but if I send request in Postman I am getting following error. Unsupported media type \"application/x-www-form-urlencoded\" in request But I do not have a idea What I am doing wrong. class ProfileView(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = ProfileSerializer parser_classes = (MultiPartParser,) permission_classes = (IsOwnerOrAdmin,) def get_queryset(self): return super(ProfileView, self).get_queryset().filter(user=self.request.user) def get_object(self): qs = Profile.objects.filter(user=self.request.user).first() return qs def put(self, request): file = request.data['file'] return Response(status=204) I have configured in settings.py file as well. But I cannot work this out. Any help would be appericated. Thanks in advance -
Setting up correct path using the package django-docs
I am trying to use django-docs (https://pypi.org/project/django-docs/) package to publish my documentation created with sphinx. But somehow I fail to set the correct path. I followed the documentation and I think this is where the problem is: DOCS_ROOT = os.path.join(PROJECT_PATH, '../docs/_build/html') The documentation says that for DOCS_ROOT I should use: Absolute path to the root directory of html docs generated by Sphinx (just like STATIC_ROOT / MEDIA_ROOT settings). So I tried with: DOCS_ROOT = os.path.join(BASE_DIR, '/doc/_build/html'), I also tried DOCS_ROOT = os.path.join(BASE_DIR, '/doc/_build/html'), And I also tried moving my doc folder out of the project and do ..'/doc/_build/html And I also hardcoded the absolute path but still no success. This is my folder structure: myproject manage.py doc (this is the doc folder where my sphinx doc is) ... ... I think it is something easy but I am simply stuck with this one.... Any help is of course very much appreciated. Thanks in advance! -
Trouble with joining tables together
I'm trying to join tables by using Django queryset, but for some reason it keeps throwing an error. Tables are structured as below. class Platform(models.Model): P_key = models.AutoField(primary_key=True) P_url = models.CharField(max_length=100) P_userkey = models.IntegerField(default=0) P_name = models.CharField(max_length=10) objects = models.Manager() class User_info(models.Model): U_key = models.AutoField(primary_key=True) U_name = models.CharField(max_length=20) U_img = models.CharField(max_length=100) U_info = models.CharField(max_length=100) U_sudate = models.CharField(max_length=20) P_key = models.ForeignKey(Platform, on_delete=models.CASCADE) objects = models.Manager() This is the code written to join two tables together. queryset = User_info.objects.all().prefetch_related("Platform") queryset = User_info.objects.all().select_related("Platform") queryset = Platform.objects.all().select_related("User_info") And the following is the error -> django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'Platform'. Choices are: P_key. I've tried a number of query sets but I wasn't able to get far. -
Django test, waiting for a modal
I'm trying to write a django test that clicks a button and then waits for a modal to open and check it is the right modal. I'm using selenium and firefox. This is my test class MySeleniumTests(LiveServerTestCase): #fixtures = ['user-data.json'] def setUp(self): self.admin = User.objects.create_user(username='JohnLennon', password = 'JohnLennon') self.admin.is_superuser = True self.admin.is_staff = True self.admin.save() self.researcher = User.objects.create_user(username='PaulMcCartney', password = 'PaulMcCartney') @classmethod def setUpClass(cls): super(MySeleniumTests, cls).setUpClass() chrome_options = Options() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") chromedriver_path = '/usr/local/bin/chromedriver' cls.selenium = webdriver.Chrome(chromedriver_path, chrome_options=chrome_options) cls.selenium.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.selenium.quit() super(MySeleniumTests, cls).tearDownClass() def researcher_login(self): self.selenium.get('%s%s' % (self.live_server_url, '/interface/')) username_input = self.selenium.find_element_by_name("username") username_input.send_keys(self.researcher.username) password_input = self.selenium.find_element_by_name("password") password_input.send_keys(self.researcher.password) self.selenium.find_element_by_id('id_log_in').click() def test_researcher_login_to_researchUI(self): self.researcher_login() url = self.selenium.current_url.split(':')[2][5:] self.assertEqual(u'/interface/', url) def test_new_study(self): self.researcher_login() # check new study opens WebDriverWait(self.selenium, 10).until(EC.element_to_be_clickable((By.XPATH, "//button[@id='id_new_study']"))).click() #self.selenium.find_element_by_id("id_new_study").click() WebDriverWait(self.selenium, 10).until(EC.presence_of_element_located((By.ID, "modal-title"))) self.assertEqual(u'New Study', self.selenium.find_element_by_id("modal-title")) This is the button in the html I'm trying to click <button id="id_new_study" type="button" style='width:100%;' class="btn btn-primary" onclick = "modal_form('/interface/add_study/')" >New Study</button> This is the error message I get Traceback (most recent call last): File "/home/henry/Documents/Sites/Development/web-cdi/webcdi/researcher_UI/tests.py", line 70, in test_new_study WebDriverWait(self.selenium, 10).until(EC.presence_of_element_located((By.ID, "modal-title"))) File "/home/henry/Documents/Sites/Development/web-cdi/env/lib/python3.6/site-packages/selenium/webdriver/support/wait.py", line 80, in until raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: I know the modal does open when I'm running the application, because I can use it. I cannot get … -
Django. Create custom object without save and return like a queryset
I need create empty objects without save in data base(like a custom object for a specific conditions) and add this object to queryset. I have wtritten code: # create empty queryset queryset = MajorMinor.objects.none() major_minor = MajorMinor.objects.model dealer = User.objects.model dealer.email = 'test@gmail.com' grower = User.objects.model grower.email = 'test@gmail.com' major_minor.major = dealer major_minor.minor = grower # add my obj to queryset queryset |= major_minor return queryset but i have had an error: type object 'MajorMinor' has no attribute 'model' -
Django custom count based on ORM filter
I am trying to gather additional information based on previously filtered data, like this count(distinct batch_id) as batches, sum(files) as files The result is influenced by the previous filtering eg. .filter(batch_id__gte=165) I tried to clone the QuerySet and annotate aboves SQL .annotate( batches=Count('batch_id', distinct=True), batch_files=Sum('files') ) but this doesn't work because then the SQL is appended to the existing SELECT query Is there an easy way of getting a second query with a custom SELECT part while keeping the WHERE part? -
[Python3][Django]how to get masklen from model
the model as below to store the ip address in postgres. from django.db import models from netfields import InetAddressField, CidrAddressField, NetManager class TestModel(models.Model): client_ip = InetAddressField(default='0.0.0.0/0', store_prefix_length=True) I want to get the IP masklength directly through the model. but I can't find a attribute correspondig to postgresql inet masklen https://www.postgresql.org/docs/9.4/functions-net.html