Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why can't I load index.html?
I got an error, TemplateDoesNotExist at /polls/ polls/index.html when I acsess http://localhost:8000/polls/ . Traceback said Traceback: File "/Users/XXX/django/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/Users/XXX/django/django/core/handlers/base.py" in _get_response 160. response = self.process_exception_by_middleware(e, request) File "/Users/XXX/django/django/core/handlers/base.py" in _get_response 158. response = response.render() File "/Users/XXX/django/django/template/response.py" in render 106. self.content = self.rendered_content File "/Users/XXX/django/django/template/response.py" in rendered_content 81. template = self.resolve_template(self.template_name) File "/Users/XXX/django/django/template/response.py" in resolve_template 63. return select_template(template, using=self.using) File "/Users/XXX/django/django/template/loader.py" in select_template 47. raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) Exception Type: TemplateDoesNotExist at /polls/ Exception Value: polls/index.html Traceback: File "/Users/XXX/django/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/Users/XXX/django/django/core/handlers/base.py" in _get_response 160. response = self.process_exception_by_middleware(e, request) File "/Users/XXX/django/django/core/handlers/base.py" in _get_response 158. response = response.render() File "/Users/XXX/django/django/template/response.py" in render 106. self.content = self.rendered_content File "/Users/XXX/django/django/template/response.py" in rendered_content 81. template = self.resolve_template(self.template_name) File "/Users/XXX/django/django/template/response.py" in resolve_template 63. return select_template(template, using=self.using) File "/Users/XXX/django/django/template/loader.py" in select_template 47. raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) Exception Type: TemplateDoesNotExist at /polls/ Exception Value: polls/index.html views.py is like from django.shortcuts import render from django.urls import reverse_lazy from django.utils.html import mark_safe from .models import Question from django.http import HttpResponse from django.shortcuts import Http404 from django.shortcuts import get_object_or_404,redirect from .models import Choice from django.views.generic import TemplateView from django.views.generic import DetailView from django.views.generic import ListView from .forms import MyForm … -
IMAPClient python - proper method of storing user authorization data
I am working on an email client powered by Django and IMAPClient library. On the client-side, users have interface for associating their mailboxes (like test1@gmail.com, test2@gmail.com, etc...) with their accounts in my app . And the goal is to store credentials info so that the user has to go through the procedure of inserting password and host name (like imap.gmail.com) only once unless he deliverately logs out from an account. The question is, where and how should the login/password/hostname data used for establishing IMAP connection be stored? Is it my server's DB? Or some sort of .ini files? I remember, reading a post about python/imap where they stored it in .ini files, but I can't find it now. Currently, I store credentials and IMAP hostname info in my local db. Thus, in each view that needs to fetch info from IMAP server, I query my server db to get the data and After this, I initialize IMAPClient variable for establishing connection with the IMAP server. And I have a terrible feeling that this is junk code: def show_mail(request, login): user_email_info = UserEmailInfo.objects.get(user_id = request.user.id, login = login) HOST = user_email_info.host #'imap.gmail.com' USERNAME = user_email_info.login PASSWORD = user_email_info.psw server = IMAPClient(HOST, … -
Can I simplify my django database where I have many similar views (i.e. create, list) for many different models
I have several models with similar views... Is there a way to write one list/create/detail view and apply that single view to all of my models? def modelalist(request): objects = ModelA.objects.all() context = { "objects": objects, } return render(request, "app/modelalist.html", context) def modelblist(request): objects = ModelB.objects.all() context = { "objects": objects, } return render(request, "app/modelblist.html", context) # and on and on.... What's best practice here? -
Komodo Edit Django API Catalog?
Where can you find a Django API catalog for Komodo Edit, version 10.2.3, build 17708, platform linux-x86_64? There is some Python code completion but no Django even given the correct python and django path. -
unique together in django doesn't work
Unique together doesn't work , it only set the unique constraints on the first field and ignore the second field . Is there any way to enforce unique constraints ? class BaseModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) deleted = models.DateTimeField(db_index=True, null=True, blank=True) last_modified_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Book(BaseModel): first_form_number = models.CharField(max_length=8) class Meta: unique_together = (("first_form_number", "deleted"),) -
NoReverseMatch at /polls/
I am making a web sit by seeing Django tutorial. I got an error,NoReverseMatch at /polls/ Reverse for 'index' with no arguments not found. 1 pattern(s) tried: ['$/']. error Traceback said Traceback: File "/Users/XXX/django/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/Users/XXX/django/django/core/handlers/base.py" in _get_response 130. response = self.process_exception_by_middleware(e, request) File "/Users/XXX/django/django/core/handlers/base.py" in _get_response 128. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/XXX/djangostudy/polls/views.py" in index 23. 'questions': Question.objects.all(), File "/Users/XXX/django/django/shortcuts.py" in render 36. content = loader.render_to_string(template_name, context, request, using=using) File "/Users/XXX/django/django/template/loader.py" in render_to_string 62. return template.render(context, request) File "/Users/XXX/django/django/template/backends/django.py" in render 61. return self.template.render(context) File "/Users/XXX/django/django/template/base.py" in render 175. return self._render(context) File "/Users/XXX/django/django/template/base.py" in _render 167. return self.nodelist.render(context) File "/Users/XXX/django/django/template/base.py" in render 943. bit = node.render_annotated(context) File "/Users/XXX/django/django/template/base.py" in render_annotated 910. return self.render(context) File "/Users/XXX/django/django/template/loader_tags.py" in render 155. return compiled_parent._render(context) File "/Users/XXX/django/django/template/base.py" in _render 167. return self.nodelist.render(context) File "/Users/XXX/django/django/template/base.py" in render 943. bit = node.render_annotated(context) File "/Users/XXX/django/django/template/base.py" in render_annotated 910. return self.render(context) File "/Users/XXX/django/django/template/loader_tags.py" in render 155. return compiled_parent._render(context) File "/Users/XXX/django/django/template/base.py" in _render 167. return self.nodelist.render(context) File "/Users/XXX/django/django/template/base.py" in render 943. bit = node.render_annotated(context) File "/Users/XXX/django/django/template/base.py" in render_annotated 910. return self.render(context) File "/Users/XXX/django/django/template/defaulttags.py" in render 447. url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "/Users/XXX/django/django/urls/base.py" in reverse 87. return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) … -
Django modelformset_factory save nothing
Created a set of forms for a simple model. When I am try to change the model object data in the form and save these changes in the database, the new data is not saved as a result, and a redirect to the form page with the same data occurs, although at least messages about the success or failure of the operation should be output. The terminal does not return any errors, it is written in the logs that the correct request was sent, the test server works without drops in normal mode. There is an opinion that the reason for this is a refusal to validate, but for what reason this happens and where exactly the error is hidden, it is not yet possible to understand. models.py (categories app) from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length = 30, db_index = True, unique = True, verbose_name = "Title") order = models.PositiveSmallIntegerField(default = 0, db_index = True, verbose_name = "Serial number") def __str__(self): return self.name class Meta: ordering = ["order", "name"] verbose_name = "category" verbose_name_plural = "categories" views.py (categories app) from django.views.generic.base import TemplateView from django.forms.models import modelformset_factory from django.shortcuts import redirect from django.contrib … -
Django css static not load
CSS not load!! I have read some similar questions but I can't solve this problem. Why I wrong? Static directory path: /project/static settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' base.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"> <title>title</title> </head> <body {% block content %} {% endblock content %} </body> </html> -
compare 2 date field in django
can any body suggest me any idea about how can i compare two date fields in django-admin i am the admin and i want to say whenever i update the date of a date field the other date field have to change too(plus 30 days than the first) and if the second date field changed i want to change another field just in django admin page ! thanks in advance STATUS_CHOICES = ( ('P', 'Paid'), ('U', 'UNPAID'), ) class Users(models.Model): status = models.CharField(max_length=1, choices=STATUS_CHOICES , default="U") updated = models.DateTimeField(default=now) expiry = models.DateTimeField(default=updated_plus_30_days()) # updated_plus_30_days(): # if updated = "12/8/2017" and expiry is equal to "12/09/2017" and then i changed # the updated field to be equal to "12/12/2017" then expiry have to equal to "12/1/2018" # if the updated field is >= than expiray then expiray have to increase one month and check # if status is == p: # status = u # else : # status = u -
Django ORM messes related objects with prefetch_related
I experience very weird behaviour of prefetch_related call. Here is the illustration: # First define two sketch models, just for convenience of the further talk. class Secondary(models.Model): pass class Primary(models.Model): secondaries = models.ManyToManyField(Secondary) # Just to make clear, EVERY Primary object in my system has at least one # related Secondary object. # Now prepare a query. primaries = Primary.objects.filter(...)\ .order_by(...)\ .prefetch_related('secondary') # Iterating: for primary in primaries: if not primary.secondaries.all(): # So we have found an object that is said to not have # any relatives. Re-query this particular object. # This part is hit in my code, although it should not. primary = Primary.objects.get(pk=primary.pk) for secondary in primary.secondaries.all(): # Voila, there are relatives! # This part was not hit for some objects until I added # the re-query part above. pass Just to make clear, there are no Primary objects in my system that do not have related Secondary objects, but still the code above hits the re-query part for some of them (always the same ones), and re-querying fetches the secondaries that were missing. And what is even more weird, I can see that some Primaries get repeating Secondaries in their secondaries.all()—the overall impression is that ORM … -
Django ajax follow and unfollow
I have a follower system in place and it is executed with ajax. The problem is the follower button doesnt work. it is not clicking and user number followers does not increase at the end of the day. I have my codes below template {% with objects=user.followers.count %} <span class="count"> <span class="total"> {{ objects }} </span> follower{{ objects|pluralize }} </span> <a href="#" data-id="{{ user.id }}" data-action="{% if request.user in user.followers.all %}un{% endif %}follow" class="follow button"> {% if request.user not in user.followers.all %} Follow {% else %} Unfollow {% endif %} </a> {% block quary %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src=" http://cdn.jsdelivr.net/jquery.cookie/1.4.1/jquery.cookie.min.js "></script> <script> var csrftoken = $.cookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $(document).ready(function(){ $('a.follow').click(function(e){ e.preventDefault(); $.post('{% url "user_follow" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $('a.follow').data('action'); // toggle data-action $('a.follow').data('action', previous_action == 'follow' ? 'unfollow' : 'follow'); // toggle link text $('a.follow').text( previous_action == 'follow' ? 'Unfollow' : 'Follow'); // update total followers var previous_followers = parseInt( $('span.count .total').text()); $('span.count .total').text(previous_action == 'follow' ? previous_followers + 1 … -
Dropbox Webhook for Business
Just install dropbox-psd-python (https://github.com/dropbox/dropbox-sdk-python). Business App integration process was ok. When I add file to my Dropbox Business { u'list_folder': { u'teams': { u'dbtid:AAB***': [ u'dbmid:AAA******', u'dbmid:AAC******' ] } }, u'delta': { u'teams': { u'dbtid:AAB***': [ u'dbmid:AAA******', u'dbmid:AAC******' ] } } } Now I want to call delta to get what exactly change with my dropbox, as I did it before client = dropbox.dropbox.DropboxTeam(token) client.delta(cursor) But there is not delta function call in last version? And I could not find anything substitute of delta How can I do it? Thanks. -
Django REST Framework JSON response on internal server error only for API calls
I'm working on a large Django app that contains a REST API through DRF on a /api/ url. I'd like to make errors respond as JSON for all views called from the API, but still respond with HTML for normal requests to all the other URLs. I'm aware you can use Middleware to handle all exceptions in the site, but is there a way to just use it for certain apps? Thanks -
where is the Django's migration listing (migrate -l)
I've just upgraded to Django 1.11.4 and I cannot use python manage.py migrate -l There is not listing option any more. Why? What is the replacement for? That listing was nice way to verify what is not migrated yet. From latest Django: usage: manage.py migrate [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--noinput] [--database DATABASE] [--fake] [--fake-initial] [--run-syncdb] [app_label] [migration_name] Updates database schema. Manages both apps with migrations and those without. positional arguments: app_label App label of an application to synchronize the state. migration_name Database state will be brought to the state after that migration. Use the name "zero" to unapply all migrations. optional arguments: -h, --help show this help message and exit --version show program's version number and exit -v {0,1,2,3}, --verbosity {0,1,2,3} Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output --settings SETTINGS The Python path to a settings module, e.g. "myproject.settings.main". If this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will be used. --pythonpath PYTHONPATH A directory to add to the Python path, e.g. "/home/djangoprojects/myproject". --traceback Raise on CommandError exceptions --no-color Don't colorize the command output. --noinput, --no-input Tells Django to NOT prompt the user for input of any kind. --database DATABASE Nominates … -
Exclude a field from search results
I've got a search index defined for a model which is returning results for a given query however I'd like to specify that haystack only searches on fields exposed to the frontend. For example, the index stores the pk of the object (which is great) and if you search for a number which matches a pk you'll get that result, but the information displayed might not match that which is a little confusing if, for example, you were hoping that the place column might match the number you'd searched. Is it possible to specify a Meta attribute to the ModelSearchForm perhaps that can define fields = [] which limits what haystack uses in it's search() method? The index is defined as; class ResultsIndex(indexes.SearchIndex, indexes.Indexable): """ Results indexes for elasticsearch engine """ text = indexes.CharField(document=True, use_template=True) # Model attributes - allows for filtering etc with db hits owner = indexes.IntegerField(model_attr='owner_id', null=True) event_year = indexes.IntegerField(model_attr='event_year__id') event = indexes.CharField(model_attr='event_year__event__title') place = indexes.IntegerField(model_attr='place', null=True) def get_model(self): return Results For the frontend this is queried using the following SearchForm subclass; class ResultsSearchForm(ModelSearchForm): """ Provide additional filtering on results """ event_year = forms.ChoiceField( label=_("Event/year"), required=False, ) def __init__(self, *args, **kwargs): super(ResultsSearchForm, self).__init__(*args, **kwargs) event_year_choices = list() … -
docker compose Django nginx
I've been following a tutorial for Django and docker using nginx here http://ruddra.com/2016/08/14/docker-django-nginx-postgres/. but I have another VM with an exposed port of 8000 so I changed it to 8100 but left the other at 8000 this is my compose file: version: '3' services: nginx: image: nginx:latest container_name: ngnix01 ports: - "8100:8000" volumes: - ./code:/code - ./config/nginx:/etc/nginx/conf.d depends_on: - web web: build: . container_name: django01 command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn mydjango.wsgi -b 0.0.0.0:8000" depends_on: - db volumes: - ./code:/code expose: - "8000" db: image: postgres:latest container_name: postgres01 nginx config: upstream web { ip_hash; server web:8000; } server { location /static/ { autoindex on; alias /static/; } location / { proxy_pass http://web/; } listen 8000; server_name localhost; } and I'm getting the error when I docker-compose up attaching to postgres01, django01, ngnix01 django01 | Traceback (most recent call last): django01 | File "manage.py", line 8, in <module> ngnix01 | 2017/08/25 10:25:01 [emerg] 1#1: host not found in upstream "web:8000" in /etc/nginx/conf.d/django.conf:3 django01 | from django.core.management import execute_from_command_line ngnix01 | nginx: [emerg] host not found in upstream "web:8000" in /etc/nginx/conf.d/django.conf:3 django01 | ModuleNotFoundError: No module named 'django.core' django01 exited with code 1 which makes me … -
MultipleChoiceField / CheckboxSelectMultiple values not restored on bound form
I'm building the 'edit' page of my form. This page is supposed to show form with the data that was saved, so the form is pre populated with saved data. It works fine for most if the fields, but I have a problem with MultipleChoiceField / CheckboxSelectMultiple values that don't get restored. So instead of having the corresponding checkboxes checked with data from the saved form, they are all unchecked. Why is that ? # forms.py class MemberForm( forms.ModelForm ): # ...... MODEL_CATEGORIES = ( ('advisor', 'advisor'), ('member', 'member'), ('admin', 'admin'), ) model_categories = forms.MultipleChoiceField( widget = forms.CheckboxSelectMultiple, choices = MODEL_CATEGORIES ) class Meta: model = Member fields = [ 'model_categories' ] # model class Member( models.Model ): model_categories = models.CharField( max_length = 255, null = True, blank = True ) # Controller def profile_edit_form( request ): user = request.user or None # Get user member profile instance instance = get_object_or_404( Member, author = user ) form = MemberForm( request.POST or None, instance = instance ) context = { "form" : form, "instance": instance } if form.is_valid(): # ... return redirect( 'profile_display' ) else: # Initial form display, and redisplay of invalid form return render( request, 'profile_edit_form_view.html', context ) # … -
why ImportError: No module named blog showing when trying to execute commannd from blog.models import Post in python shell?
ImportError: No module named blog Above error showing while trying to execute following command in python shell Command used : from blog.models import Post -
DATABASE_ROUTERS configuration setting not working
I'm trying to use multiple databases. I did everything as is explained in tutorials, but my project is not using the DATABASE_ROUTER classes. I searched in internet but noone had my problem first u.u I don't know what to do. My configurations are: DATABASES = { 'default': { "ENGINE": 'django.db.backends.mysql', [...] }, 'one': { "ENGINE": 'django.db.backends.mysql', [...] }, 'two': { "ENGINE": 'django.db.backends.mysql', [...] }, } DATABASES_ROUTERS = [ 'routers.FirstRouter', 'routers.SecondRouter' ] the file routers.py it's outside the app, where manage.py it's located. I moved it as someone advice in internet. I put a breakpoint inside routers.py but it never stop there. When I launch test with multi_db = True it creates tables searching in diferents aliases. -
Populate Django Drop Down List from another Drop Down List - Javascript
I have a Django + Python website, where user can request a access to a database. So in this form the user has these options. Environment: This is a drop down list with two values: Development and Production Permission: This is another drop down list with two values: Read and Read/Write What I am trying to achieve is: If Environment == Development AddToPermissionDropDownList: Database Owner else Permission So, as you can see, I want to populate one drop down list based in the selected value of another drop down. I know that I need to use JavaScript to achieve that, but I am stuck on how to do it. -
Set the fields `null=True`, why in the ModelForm I still get required error?
I get required error when I request the API by me. In my models.py: class User(models.Model): username = models.CharField(max_length=16) password = models.CharField(max_length=16) real_name = models.CharField(max_length=12, null=True) phone = models.CharField( max_length=11) email = models.EmailField(null=True) qq = models.CharField(max_length=10, null=True) address = models.CharField(max_length=64, null=True) id_card = models.CharField(null=True, max_length=18, validators=[RegexValidator(regex='^.{18}$', message='id card length:18', code='nomatch')]) id_card_img_front = models.CharField(max_length=256, null=True) id_card_img_back = models.CharField(max_length=256, null=True) nickname = models.CharField(max_length=16, null=True) profile = models.CharField(max_length=256, null=True, default='my profile') usertype = models.ForeignKey(to='UserType', default=1) ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) In my views.py, please pay attention I only send username, password, phone to the request: class UserMF(ModelForm): class Meta: model = models.User fields = '__all__' def register(request): ... obj = UserMF(request.POST) if obj.is_valid(): ... else: print (obj.errors.as_json()) # then printed the errors ... The error message: {"qq": [{"message": "This field is required.", "code": "required"}], "profile": [{"message": "This field is required.", "code": "required"}], "id_card_img_front": [{"message": "This field is required.", "code": "required"}], "id_card": [{"message": "This field is required.", "code": "required"}], "real_name": [{"message": "This field is required.", "code": "required"}], "usertype": [{"message": "This field is required.", "code": "required"}], "id_card_img_back": [{"message": "This field is required.", "code": "required"}], "address": [{"message": "This field is required.", "code": "required"}], "nickname": [{"message": "This field is required.", "code": "required"}], "email": [{"message": "This field … -
Django with cassandra - No schema for cassandra database
I'm trying to setup cassandra with django using the instructions here. Everything works fine. When I migrate, the table is getting created. But when I run the server using python manage.py runserver, it gives me the following error: Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by Traceback (most recent call last): File "/Users/gpallav/Env/tp/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/gpallav/Env/tp/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 128, in inner_run self.check_migrations() File "/Users/gpallav/Env/tp/lib/python2.7/site-packages/django/core/management/base.py", line 422, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/Users/gpallav/Env/tp/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in init self.loader = MigrationLoader(self.connection) File "/Users/gpallav/Env/tp/lib/python2.7/site-packages/django/db/migrations/loader.py", line 52, in init self.build_graph() File "/Users/gpallav/Env/tp/lib/python2.7/site-packages/django/db/migrations/loader.py", line 209, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Users/gpallav/Env/tp/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/Users/gpallav/Env/tp/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 57, in ensure_schema editor.create_model(self.Migration) File "/Users/gpallav/Env/tp/lib/python2.7/site-packages/django_cassandra_engine/base/schema.py", line 23, in create_model raise Exception('No schema for cassandra database') Plz help! -
Selenium: django tests stops when testing popup window
I have problem with testing popup window in my Django app, using python selenium. I want to test that user see main form, clicks button and popup form shows up. In popup window user fill new name form, submit, popup close and he sees created name in select input. Problem is when I start my selenium functional tests, tests runs normally to popup form submit, then popup close and nothing happens. Tests not going further nor breaks. Here is my tests code: def test_user_fill_form_with_multiple_names(self): # User goes to robject form page. self.browser.get(self.live_server_url + reverse("robject_create", args=(proj.name,))) # User wants to create new names. He clicks in plus button # next to name select input. plus_btn = self.browser.find_element_by_css_selector( ".related-widget-wrapper select#id_names + a") plus_btn.click() # Now, in popup he enter new name and clicks submit. self.switch_to_popup() name_input = self.browser.find_element_by_css_selector( "input[name='name']") name_input.send_keys("NAME1") self.browser.find_element_by_css_selector( "input[type='submit']").click() # User gets back to main window. He noticed new name in select input. self.switch_to_main() self.fail("Finish test!") # TEST NOT FAILS def setUp(self): self.browser = webdriver.Firefox() self.main_window = self.browser.current_window_handle def get_popup_window(self): popup_window = None while not popup_window: for handle in self.browser.window_handles: if handle != self.main_window: popup_window = handle break return popup_window def switch_to_popup(self): popup_window = self.get_popup_window() self.browser.switch_to.window(popup_window) def switch_to_main(self): self.browser.switch_to.window(self.main_window) … -
Django MultiValueField with non-required fields
I'm trying to make a MultiValueField for which the last field is not required. According to the docs, if I set require_all_fields to False, then I can set some fields to not be required, like this:- class MyMultiWidget(widgets.MultiWidget): def __init__(self, attrs=None): _widgets = ( widgets.TextInput(attrs=attrs), widgets.TextInput(attrs=attrs), widgets.TextInput(attrs=attrs), widgets.TextInput(attrs=attrs), ) super(MyMultiWidget, self).__init__(_widgets, attrs) def decompress(self, value): return [None, None, None, None] class MyMultiValueField(forms.MultiValueField): widget = MyMultiWidget def __init__(self, *args, **kwargs): fields = ( forms.CharField(), forms.CharField(), forms.CharField(), forms.CharField(required=False)) super(MyMultiValueField, self).__init__( require_all_fields=False, fields=fields, *args, **kwargs) def compress(self, data_list): return data_list But the HTML that this generates looks like this:- <input name="field_0" required="" class="textinput textInput form-control" id="id_field_0" autocomplete="off" type="text"> <input name="field_1" required="" class="textinput textInput form-control" id="id_field_1" type="text"> <input name="field_2" required="" class="textinput textInput form-control" id="id_field_2" type="text"> <input name="field_3" required="" class="textinput textInput form-control" id="id_field_3" type="text"> As you can see, all the fields are required. Any idea what I've done wrong here? -
How to pass data values from Views to Templates in Django?
Currently, I have two templates: no_results_tickets.html and results_tickets.html. The first template contains two drop-down menus that are used to select the year and the number of week, so once you hit the submit button, the web app looks for the tickets for the selected week and year from the Web API and then it displays the results in another Template. What I am missing right now is how to display these results in the second Template. This is what I have so far. forms.py class DropDownMenuForm(forms.Form): week = forms.ChoiceField(choices=[(x,x) for x in range (1,53)]) year = forms.ChoiceField(choices=[(x,x) for x in range (2016,2021)]) template no_results_tickets.html <h3>Please, select the year and week number to retrieve the data.</h3> <form id="search_dates" method="POST" action="/results_tickets/"> {% csrf_token %} <h6>Select year</h6> <div class="row"> <div class="col-sm-8"> <select name="select_year"> <option value = {{form.year}}></option> </select> </div> <div class="col-sm-8"> <h6>Select week</h6> <select name="select_week"> <option value= {{form.week}}></option> </select> <button type="submit">Search</button> </div> </div> </div> ulrs.py url(r'^no_results_tickets/$',views.tickets_results_test, name='no_results_tickets'), url(r'^results_tickets/$',views.tickets_results_test, name='results_tickets'), View @api_view(['GET','POST',]) def tickets_results_test(request): if request.method == "GET": ''' Template for displaying the dropdown menus.''' template_name = 'personal_website/no_results_tickets.html' form = DropDownMenuForm() return render(request, template_name, {'form': form}) elif request.method == "POST": template_name = 'personal_website/results_tickets.html' year = request.POST.get('select_year', None) week = request.POST.get('select_week', None) # ... do …