Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create download link file in django
I create file in project, generation pdf from html. For this i have method: def generation_html_to_pdf(self): path_pdf = None with NamedTemporaryFile(delete=False, suffix=".pdf", dir='pdf_files') as tf: path_pdf = tf.name pdfkit.from_file('templates/first_page.html', tf.name) return path_pdf then in folder pdf_files i have pdf file. I want get download link for this file: my view path_to_pdf = generation_html_to_pdf() download_link = 'http://' + request.get_host() + path_to_pdf json_inf_pdf = {'download_link': download_link} return JsonResponse(json_inf_pdf, status=200) i have json like this: {"download_link": "http://127.0.0.1:8000/home/alex/projects/test_project/pdf_files/tmpe0nqbn01.pdf"}" when i click in this link i have error: Page not found (404) -
Django Middleware and threading to catch the current user
I'm trying to use catch the Django user in the Middleware but without success. Using Python 3.6 and Django 1.11. from threading import local _user = local() class CurrentUserMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): _user.value = request.user return self.get_response(request) def get_current_user(): return _user.value I need to save the request.user outside the class, in the get_current_user(), but it is not working. Can someone give me a clue why I can't have the _user.value in the get_current_user() ? Thanks, -
How do I allow multiple selects for my template forms?
I have two models: a Course model which has a many-to-many field to the Student model. I made an enroll and a disenroll forms for the student, problem is, I had to change how they are rendered and so, now I cannot do multiple select. Right now a button and a checkbox appear near each student name. Problem is, if I move the button outside of the loop, it will work, but only for the last student selected, and not for all selected.. So I need to change the template in order to work with multiple select but keep the rendering behaviour. {%with crs_stud=course.student.all %} {% for student in students %} {% if student in crs_stud %} <form action="." method="POST"> {% csrf_token %} <label for="id_{{ student.id }}"> <p>{{ student.name.upper }} is already enrolled.</p></label> <input type="checkbox" id="id_{{ student_id }}" value="{{ student.id }}" name="student_ids2"> <input type="submit" value="Disenroll"> </form> {% else %} <form action="." method="POST"> {% csrf_token %} <label for="id_{{ student.id }}">{{ student.name }}</label> <input type="checkbox" id="id_{{ student_id }}" value="{{ student.id }}" name="student_ids"> <input type="submit"> </form> {% endif %} {% endfor %} {% endwith %} course = Course.objects.get(slug=slug) if request.method == 'POST': course.student.add(*request.POST.getlist('student_ids')) course.student.remove(*request.POST.getlist('student_ids2')) return redirect('classroom') -
Gridster widgets appearing vertically in django webpage
In my app which uses django I am displaying gridster widgets.When I run the HTML/Javascript page directly the widgets are arranged as written in HTML code.But when I use same webpage in my django app by placing it in template and keeping static files(gridster.js and some css) in corresponding folders all the widgets just load in a single line Following is my HTML Code <!doctype html> <html> <head> <title>Demo &raquo; Add Delete Widget &raquo; gridster.js</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/demo.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'js/jquery.gridster.min.css' %}"> <script src="{% static 'js/jquery.min.js' %}"></script> <script src="{% static 'js/jquery.gridster.min.js' %}" type="text/javascript" charset="utf-8"></script> </head> <body> <h1>Add and Remove Widget Dynamically</h1> <p>When you remove a widget,the widget below it will always remain in the same column.Widget from next column wont come in place of widget removed.Gridster is designed that way</p> <a href="https://github.com/ducksboard/gridster.js/issues/338" target="_blank"> Click to know more</a> <div class="gridster"> <ul> <li data-row="1" data-col="1" data-sizex="1" data-sizey="1"><button class="delete-button" style="float: right;">-</button><h3>1</h3></li> <li data-row="1" data-col="2" data-sizex="1" data-sizey="1"><button class="delete-button" style="float: right;">-</button><h3>2</h3></li> <li data-row="1" data-col="3" data-sizex="1" data-sizey="1"><button class="delete-button" style="float: right;">-</button><h3>3</h3></li> <li data-row="1" data-col="4" data-sizex="1" data-sizey="1"><button class="delete-button" style="float: right;">-</button><h3>4</h3></li> <li data-row="2" data-col="1" data-sizex="1" data-sizey="1"><button class="delete-button" style="float: right;">-</button><h3>5</h3></li> <li data-row="2" data-col="2" data-sizex="1" data-sizey="1"><button class="delete-button" style="float: right;">-</button><h3>6</h3></li> <li … -
javascript/jquery dropdown menu selection not passing GET request
In my page I have a dropdown menu, and upon selection I want to pass a GET request. This GET request should (ideally) trigger a function from my views.py file and return some data (based on the selection) from my database. However, it doesn't seem like anything actually happens upon dropdown menu selection. Here is my script that I wrote to trigger the GET request when a selection was made: <!-- AJAX Call for dropdown menu selection --> <script type="text/javascript"> var url = $('.dropdown-menu').attr('action'); $('.dropdown-menu-option').click(function(e){ e.preventDefault(); $.ajax({ type: "GET", url: url, data: { class: $('.dropdown-menu-option').val() }, success: function(result) { alert ('pass'); }, error: function(result) { alert('fail'); } }); }); </script> Here is the code for my dropdown menu in my template: <!-- Query based content for dropdown menu --> <select class="dropdown-content"> {% if current_user_properties %} {% for property in current_user_properties %} <option class="dropdown-menu-option" value="{{property.id}}">{{property.name}}</option> {% endfor %} {% else %} <option>You don't have any properties</option> {% endif %} </select> Lastly, here is the code for the function I wanna run in my views.py def property_selected(request): if request.method == 'GET': selection = request.GET.get('class', None) if selection: selected_data = MeterData.objects.filter(property=selection).order_by(date) return selected_data If anyone can help identify what I'm missing/doing wrong, that'd … -
Django form field validation error
I'm trying to validate if form field is None when user submits the form and raise a ValidationError exception: def clean_street_number(self): if self.cleaned_data['street_number'] is None: raise ValidationError( ('You forgot to write your street number') ) else: return self.cleaned_data['street_number'] When I fill the form and submit without street number, Django crashes with message: The view core.decorators.add_location didn't return an HttpResponse object. It returned None instead. -
Generate fields for a ManyToMany field with data inside the through model Django
I am here cause have no idea how to create a form for a specific case in my Django app. I'll try to explain the best I can. My site is about rentals for a kayak club. We have people that rent boats for a desired period. I want to be able to check the stock of boats before to rent them. A club can have many different boat types that it wants to rent, and a club may have some types of boats that another don't have. When I create a rental, I would like to be able to choose a number of boat for each BoatType. Let's take an exemple : I have a club A that have three BoatType it rents : C1, C2, C3. In the form, I need to have these three fields : C1 : Number Input / C2 : Number Input / C3 : Number Input I have a club B that have two BoatType in rents : K1, K2. In the form, I need to have these two fields : K1 : Number Input / K2 : Number Input So I have those models : class Club(models.Model): name =models.CharField(max_length=100) class BoatType(models.Model): club … -
Deploying django on Heroku : Requested setting LOGGING_CONFIG, but settings are not configured
I have a django app that runs perfectly locally, but when I try to deploy it on heroku I continue to run into this error, django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. This is my settings file, import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ***** # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['0.0.0.0', 'localhost', '127.0.0.1', '.herokuapp.com', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'phonenumber_field', 'aggregator', 'bouncer', ] AUTH_USER_MODEL = 'bouncer.User' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'verification@sampleapp.com' EMAIL_HOST_PASSWORD = '####' EMAIL_PORT = 587 EMAIL_BACKEND = 'django.ftb_core_api.mail.backends.smtp.EmailBackend' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'sampleapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'sampleapp.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases … -
Pagination with JsonResponse
I'd like to add pagination to my JsonResponse. I'm currently using the django.http.JsonResponse to generate json from an elastic search API. I'd like to add a pagination feature to be included. My code is as follows: class ResultQueryView(View): def get(self, request): resource_meta = request.GET.getlist("resource_meta") locations = request.GET.getlist("location") page = request.GET.get("page") print page logger.info("Got search query where resource_meta: {} and locations: {}".format(resource_meta, locations)) results = resource_query(resource_meta, locations) # print type(results['hits']['hits'][0]['_id']) resource_ids = [r["_id"] for r in results['hits']['hits']] # print type(resource_ids[0]) # print request.user resources = get_enriched_resources(request.user, Resource.objects.filter(internal_id__in=resource_ids)) serialized = ResourceSerializer(resources, many=True) return JsonResponse({"resources": serialized.data}) -
How to set Instance of models to make a confirmation form in Django
I need to save the info of these models with foreign keys, so I created a view for Candidato, InfoPersonal and InfoAcademica, and finally I created a confirm view to save Solicitud but that page shows me: TypeError at /solicitud/confirmacion/2/ 'instance' is an invalid keyword argument for this function My models. project/apps/solicitud/models.py class Candidato(models.Model): nombre = models.CharField(max_length=50) apellidos = models.CharField(max_length=70) email = models.EmailField(unique=True) def __unicode__(self): return u'{} {}'.format(self.nombre, self.apellidos) class InfoPersonal(models.Model): candidato = models.ForeignKey(Candidato, null=False, blank=False, on_delete=models.CASCADE) sexo = models.CharField(max_length=9, choices=SEXO_CHOICES) fecha_nacimiento = models.DateField() curp = models.CharField(max_length=18, unique=True) pais_origen = models.CharField(max_length=30, default="México") lugar_nacimiento = models.CharField(max_length=100) domicilio = models.CharField(max_length=120) codigo_postal = models.CharField(max_length=5) telefono = models.CharField(max_length=20) def __unicode__(self): return u'{}'.format(self.curp) class InfoAcademica(models.Model): persona = models.ForeignKey(Candidato, null=True, blank=True, on_delete=models.CASCADE) escuela_procedencia = models.CharField(max_length=50) programa_solicitado = models.CharField(max_length=50, choices=PROGRAMA_SOLICITADO_CHOICES, default=MAS_ADMIN) titulado = models.CharField(max_length=10, choices=ESTADO_TITULACION_CHOICES, default=YA_TITULADO) titulacion_creditos = models.CharField(max_length=2, choices= TITULACION_CREDITOS_CHOICES, default=NO) def __unicode__(self): return u'{}'.format(self.programa_solicitado) class Solicitud(models.Model): candidato = models.ForeignKey(Candidato, null=True, blank=True) academica = models.ForeignKey(InfoAcademica, null=False, blank=False) Personal = models.ForeignKey(InfoPersonal, null=False, blank=False) def __unicode__(self): return u'Solicitud id: {}'.format(self.id) My URLS, here I send a pk for every model to link them in Solicitud # -*- coding: utf-8 -*- from django.conf.urls import url import views app_name = 'solicitud' urlpatterns = [ url(r'^datos_candidato/$', views.AddDatosCandidato.as_view(), name='datos_candidato'), url(r'^datos_personales/$', views.AddDatosPersonales.as_view(), name='datos_personales'), … -
Django+uwsgi+nginx+Lets encrypt can't access https
I'm using Django/uwsgi/nginx. And to access ssl, installed Lets encrypt. Below source is nginx and uwsgi confirue file. [project_rest.conf] upstream django {t server 127.0.0.1:8001; } server { listen 8000; server_name .mysitedomain.com; charset utf-8; client_max_body_size 75M; # adjust to taste # Django media location /media { alias /home/app/project_rest/media; # your Django project's media files - amend as required } location /static { alias /home/app/project_rest/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/app/project_rest/uwsgi_params; # the uwsgi_params file you installed } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/mysitedomain.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/mysitedomain.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } (I created project_rest.conf and link to /etc/nginx/sites-enabled/ [uwsgi.ini] [uwsgi] # the base directory (full path) chdir=/home/app/project_rest # Django's wsgi file module=project_rest.wsgi:application master=true # maximum number of worker processes processes=10 # the socket (use the full path to be safe socket=127.0.0.1:8001 chmod-socket=664 chown-socket=app:app pidfile=/tmp/project_rest.pid # clear environment on exit vacuum=true max-requests=5000 daemonize=project_rest.uwsgi.log after entered "uwsgi --ini uwsgi.ini", I can access to mysitedomain.com:8000 to my django's site. But I can't access to … -
Godaddy domain name, DtDNS dynamicDNS, Django app, blank page
I have a weird problem at hand and I don't seem to understand the problem or find anyone who is having the same problem. I have bought a domain name on godaddy, and I want to host my personal website on my raspberry pi. I built my website using Django, and everything works well. I use Apache2 on my raspberry with mod_wsgi. Now I connected my raspberry pi to my router and registered a name on DtDNS and connected my router to it so my dynamic IP is updated automatically. When I access my website (from home or from my workplace - so I know my website is available from everywhere and not just my local network) it works as expected and I have full access to all the webpages I built. Now comes the problem. I redirected (301) my domain name on godaddy to my name on DtDNS. When I comment the part deploying my django website in /etc/apache2/sites-available/000-default.conf , and I connect to my domain name on godaddy, I see the apache page "it works !", so I know the redirection works. BUT, when I deploy my django app, and connect to my domain name on godaddy, I … -
Django Programming as
i am a novice at django development. i am using Visual Studio Code(Anaconda) as my editor. The problem is when i have installed 'django', created my sample Web file and i try to read and edit, it is not being read as a python file and giving me error messages: #!/usr/bin/env python import os import sys if name == "main": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) i need help, am abit confused on what to do next. i have installed the virtual environment!! -
Django show ImageField
I have extended the base User from Django with the OneToOne method. class Employee(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) floor = models.CharField(max_length = 100) avatar = models.ImageField(upload_to='app/static/userimages') The image is uploaded to the correct path. Now, when I try to show the avatar, I am trying this way, but it doesn't show anything. <img src="{{ user.employee.avatar.url }}" alt=""> If I run the same in the manage.py shell I get this: 'app/static/userimages/name.jpg' I really can't figure out why it doesn't work. Any help is appreciated. -
Obfuscate URLs in Django 2.0
I used to work with django-unfriendly to obfuscate URLs in django 1.9, I am now migrating to Django 2 but this library does not work with Django 2 nor python 3.6. Any other alternative or suggestion? -
Model can have a ForeignKey with one of the two models
I need some help with an issue that I am not able to resolve on my own. So in this model, a tenancy document can either have a ForeignKey with Building or Property. We may have a tenancy agreement on the whole building or on a single property within that building. In the former case the tenancy documents are applied to the building, and in the latter case they only apply to a property. I used content_types to add a generic foreign key but now I can’t figure out how to add autocomplete fields to contenttype and in the dropdown, I just see building and property in admin form. I want to see building names and property names. I learned about autocomplete fields in Django 2.0, it’s awesome but I don’t know how can I use something like that in this particular case or if there is a better way to do this? Models.py: class TenancyDocument(models.Model): KINDS = Choices('Tenancy Agreement', 'Stamp Duty', 'Inventory List') id = FlaxId(primary_key=True) kind = StatusField(choices_name='KINDS') start_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) content_type_limit = Q( app_label='properties', model='building') | Q( app_label='properties', model='property') content_type = models.ForeignKey( ContentType, limit_choices_to=content_type_limit, on_delete=models.CASCADE, verbose_name='Lease … -
no module named search after adding project url
I've had the pleasure to work with somebody yesterday on the issue with my urls here Adding an additional template to an existing project errors out, but after trying everything suggested i'm still in the same situation. My project is named mysite and my application is search. It was suggested to add the following to my project urls.py url(r'^search/', include('search.urls')), When doing so I'm given the error ModuleNotFoundError: No module named 'search'. My project urls.py is the following: from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django_filters.views import FilterView from mysite.search.filters import UserFilter urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'), url(r'^search/$', FilterView.as_view(filterset_class=UserFilter, template_name='search/user_list.html'), name='search'), url(r'^admin/', include(admin.site.urls)), url(r'^search/', include('search.urls')), ] I'm attempting to add the following to my app urls.py from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django_filters.views import FilterView from mysite.search.filters import UserFilter from . import views urlpatterns = [ url(r'^results/$', views.results, name='results'), ] I have an empty view for results defined as def results(request): return render(request, 'results.html') When I try to add the following POST to my form for the results it gives me the error in the first post. When I have the results url in … -
Loading Javascript in Django using the the static template tag
I'm trying to following the instructions on https://docs.djangoproject.com/en/2.0/howto/static-files/, but I'm running into unexpected results. I have a Django project with an app dashboard like so: . ├── dashboard │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0002_auto_20180227_2103.py │ │ ├── 0003_auto_20180227_2304.py │ │ └── __init__.py │ ├── models.py │ ├── static │ │ └── dashboard │ │ └── dashboard.js │ ├── templates │ │ └── dashboard │ │ ├── checkin_detail.html │ │ ├── checkin_form.html │ │ └── checkin_list.html │ ├── tests.py │ └── views.py ├── db.sqlite3 ├── manage.py └── my_project ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py In my project's settings.py, the STATIC_URL is as it was created by django-admin startproject: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' The dashboard.js file is a simple test script: alert("Hello, world!"); I'm trying to use the Javascript in the checkin_form.html template like so: {% load static %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src={% static "dashboard/dashboard.js" %}></script> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Send message" /> </form> My views inherit from Django's generic view classes: from django.views import generic from .models import CheckIn class CheckInCreate(generic.CreateView): model … -
How to get values of m2m fields before saving in database?
I want to get values of m2m fields when I changi this fields in my model. I tried to use m2m_changed signal, but I get None values in action, pk_set,instance. What am I doing wrong? @receiver(m2m_changed, sender=UserProfile) def m_2_m_changed(sender, **kwargs): action = kwargs.pop('action', None) pk_set = kwargs.pop('pk_set', None) instance = kwargs.pop('instance', None) if action == "pre_save": for f_old in instance._meta.many_to_many: mm_old = sorted(getattr(instance, f_old.name).values_list('pk', flat=True)) return mm_old -
Override a function call within a Django View for Testing
Something I've been unable to find despite searching high and low... Is it possible to override a variable or function call within a Django view? We have some code that calls back-end C code and writes to the database. Obviously, I would want my to prevent this call from occuring within the view. However - when I try to do a @patch... It is simply ignored and the call will occur anyway. Is it possible to over-write this within a Django view so that I can have a return value? Example code of what I've tried: @patch('clibs.api.create_dispute') def test_create_dispute(self, cfunc): f = cfunc() f.return_value = 123456 post_data = { 'dispute_amt': ['1'], 'id': ['12'], } request = self.factory.post(reverse('dispute:dispute_creation', args=[12]), data=post_data,HTTP_X_REQUESTED_WITH='XMLHttpRequest') request.user = self.user response = dispute_creation(request, id=12) -
Django Form Automatically select first option if only one choice available
Is there an easy way to select the first option of a dropdown in a Django form, in cases where there is only one option available? With easy I mean a solution that doesn't require defining an own widget, which would be quite repetitive to change in all our (model) forms. -
Pillow error when using get_rendition with CMYK JPEGs
We have a custom endpoint in our Wagtail site which makes image renditions to be used in another site/admin. it uses this line rendition = the_image.get_rendition(filter + "|format-jpeg|jpegquality-80") Locally With Wagtail 1.13.1 and pillow 5.0.0 it's fine, the error only happens in production where pillow is at 2.8.2. If Wagtail manages the pillow dependency, should it be enforcing a minimum version? Is this a bug/issue or is Wagtail not suppose to manage dependencies in that way? I can just add a pillow>=5.0.0 in my production requirements file to fix it, so maybe that's fine? The error is : IOError: encoder error -2 when writing image file django/core/handlers/exception.py in inner at line 41 response = get_response(request) django/core/handlers/base.py in _legacy_get_response at line 249 response = self._get_response(request) django/core/handlers/base.py in _get_response at line 187 response = self.process_exception_by_middleware(e, request) django/core/handlers/base.py in _get_response at line 185 response = wrapped_callback(request, *callback_args, **callback_kwargs) foxsite/views/views.py in get_image_filename at line 32 rendition = the_image.get_rendition(filter + "|format- jpeg|jpegquality-80") wagtail/wagtailimages/models.py in get_rendition at line 271 generated_image = filter.run(self, BytesIO()) wagtail/wagtailimages/models.py in run at line 404 return willow.save_as_jpeg(output, quality=quality, progressive=True, optimize=True) willow/plugins/pillow.py in save_as_jpeg at line 74 image.save(f, 'JPEG', quality=quality, **kwargs) PIL/Image.py in save at line 1693 save_handler(self, fp, filename) PIL/JpegImagePlugin.py in _save … -
Update Page on Database Change
What is the best way to update UI element depending on a change in Database? Like whenever some comment on a post, Facebook automatically update the element for every user? how is this done? I know pulling is one way to do it but is there any better procedure? I want know how this can be done in python(Django) but any other generic solution is also welcome. -
Django security risk url parameters
I am trying to find a way to prevent users changing url parameters and messing around with the system. I know you can restrict users to only have access to the right content, but still if the url is www.site.com/something/10 And I change 10 to 9 in the address bar, i can access something the work flow is not designed to give access to. I can restrict the person not to view 9, but it still provide the opportunity to mess around with something, I might have overlooked. By using POST method and hiding the parameters it will cause problems as django is not designed to handle many forms in one view. Is there a way to let django rather display www.site.com/something/<Encrypted> or <Not recognisable so I can mess around> There must be some way of limiting users only to access, whatever the links provide on the current page, instead of a clever user trying to cause harm. -
Make 'Enter' key default to a certain button in a Django crispy form?
I have a form that subclasses PhoneNumberForm from the django-two-factor-auth-library. It renders a text box in which to enter phone number, and a Back button and Next button beneath it. The issue is that when the form is filled out and the user hits the 'Enter' key on their keyboard, the Back button is triggered. I have tried swapping the two buttons, which gives me the behavior I want, but not the correct layout. But I do see that whichever button is defined first in FormActions gets selected on hitting Enter. I have also tried adding an 'autofocus' field to my Next button, but that only focuses on the button when the page loads, not after I've switched focus to the text box and typed in a number. I would like to maintain the order I currently have (Back button on the left, Next on the right), but have the Enter key trigger the Next button. How do I do this? from crispy_forms.helper import FormHelper from crispy_forms import layout as crispy from crispy_forms import bootstrap as twbscrispy def __init__(self, **kwargs): super(PhoneNumberForm, self).__init__(**kwargs) self.helper = FormHelper() self.helper.form_class = 'form form-horizontal' self.helper.label_class = 'col-sm-3 col-md-4 col-lg-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.layout …