Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Static variable across processes in django
Is there any way to maintain a variable that is accessible and mutable across processes? Example User A made a request to a view called make_foo and the operation within that view takes time. We want to have a flag variable that says making_foo = True that is viewable by User B that will make a request and by any other user or service within that django app and be able to set it to False when done Don't take the example too seriously, I know about task queues but what I am trying to understand is the idea of having a shared mutable variable across processes without the need to use a database. Is there any best practice to achieve that? -
Django connecting to SQLSERVER with django-pyodbc-azure
I'm trying to connect to a SQLSERVER from my CentOS 7 web server running Django. I'm using Django 1.11.1, pyodbc 4.0.16, and django-pyodbc-azure 1.11.0.0. I know pyodbc is working correctly because if I run the following I get data from the database: import pyodbc cnxn = pyodbc.connect('DSN=MySQLServerDatabase;DATABASE=dbname;UID=myusername;PWD=mypwd') cursor = cnxn.cursor() cursor.execute("SELECT * FROM tablename WHERE pk='1'") for row in cursor.fetchall(): print(row) From my settings.py: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'dbname', 'USER': 'myusername', 'PASSWORD': 'mypwd', 'DSN': 'MySQLServerDatabase', 'OPTIONS': { 'driver': 'ODBC Driver 11 for SQL Server', }, }, } When I run python3 manage.py inspectdb I get: django.db.utils.OperationalError: ('HYT00', '[HYT00] [unixODBC][Microsoft][ODBC Driver 11 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') Any ideas how to get Django to connect to the database? -
javascript/jquery element slideshow
I have this elements in my template: <button class="back">Back</button> <button class="forward">forward</button> <ul class="exam-ul"> {% for file in exam.examfile_set.all %} <li class="exam-li-img" src="{{ file.exam_file.url }}" alt="Slika Testa" width="60" height="60" class="img-resposive exam-img">Slika Testa {{ forloop.counter }}</li> {% endfor %} </ul> As you may see, there are many ul`s named exam-ul on the template. I want to make a slideshow that shows list elements within "exam-ul" when button is pressed. So if the back button is pressed it should show previous list element, and if forward is pressed, the next element should appear. How could i achieve that? -
ImportError: No module named allauth error
I'm a starter in python django. I've used social authentication in my application and now when i had to switch my laptop, I run my application it says ImportError: No module named allauth. I've tried the solutions available already on this site but the problem is it gives this error on each and every command i try to run. "C:\Program Files\JetBrains\PyCharm 2017.1.2\bin\runnerw.exe" C:\Python27\python.exe D:/maryam/storefront/storefront/manage.py runserver 8000 Unhandled exception in thread started by <function wrapper at 0x03EBD530> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site- packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Python27\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) ImportError: No module named allauth a -
I cant access the form "name" or "value" in request.POST in Django
My template contents multiple forms with multiple buttons. I've read these topics: Proper way to handle multiple forms on one page in Django How can I build multiple submit buttons django form? How can I access the form submit button value in Django? and I did exactly the same, included "name" and "value" in form's input (tried with button tag too) but the "name" attribute doesn't exist in POST request. What am i doing wrong? template: <div class="container" align="center" style="border: solid 3px red"> <h3>Form 1</h3> <form id="form_step_1" method="post" action="{% url 'ajax_order_data' %}" align="center"> {% csrf_token %} {{ FormStep1 }} <button type="submit" name="step_1" value="step_1">button_step1</button> </form> </div> <br> <div class="container" align="center" style="border: solid 3px red"> <h3>Form 2</h3> <form id="form_step_2" method="post" action="{% url 'ajax_order_data' %}" align="center"> {% csrf_token %} {{ FormStep2 }} <button type="submit" name="step_2" value="step_2">button_step2</button> </form> </div> view: def somefunc(request): if request.method == 'POST': if 'step_1' in request.POST: -
How to get improved quality of image returned by ebay api
I am currently working in django and getting some data from ebay api. ebay api gives me image url. but the problem is that quality of image is 70px, which is lower quality. is there any method where i can get image of higher quality. i need images with high quality minimum 200px. ebay has higher quality images (same image with high quality which they gives in their api). i am using getTopSellingProducts API of ebay. have anyone solution about this problem.? thanks in advance. -
Changes to HTML template not reflected in Django after several steps taken
I have made major revisions to an HTML template on my dev Django server, but those changes are not reflected. Here are troubleshooting steps I've tried: Clear the browser cache Close and reopen the browser after clearing all history Try a different browser Restart the server (runserver) python manage.py collectstatic --noinput --clear Check urls.py and settings.py to make sure everything is as it should be Make sure you're editing the correct template -
Django equivalent to Flask g? flask.g necessary?
As far as I understand, flask.g offers temporary storage for the current request context (even though it's technically the application context as described here). Accessing g.my_data during a request handler will ensure that my_data is for the current request. Does Django have something equivalent to this? In my experimentation, Django's request object, which is passed into view functions, can be used the same as flask.g. I can simply use request.my_data and be ensured that my_data is for the current request. Noticing, this I tried using flask.request similar to how I used flask.g, with equivalent results. This begs the question what does flask.g provide over flask.request, just peace of mind that flask.request attributes will not be overwritten? FYI on use case, I'm sharing data between the actual request handler (flask) or view functions (django), and the middleware (django) or @before_request (flask) handlers. TLDR: Can Django request be used equivalently to flask.g? Can flask.request be used equivalently to flask.g? -
JSON object is not being rendered in charts js: Django
I have implemented chart JS 2.5 into my django application version 1.11 but I am able to see only the canvas but not any bar chart, besides,the web browser console does not display any error, so this is becoming quite difficult for me to trace the mistake. statistics.html and views.py are my main files where I am currently trying to debug this problem. The urls.py and header.html files were not touched recently and I put them at the end. statistics.html file: Graph implementation and retrieval of the JSON object {% extends "personal_website/header.html"%} <script> {% block jquery %} var endpoint = '/statistics/data' var defaultData = [] var labels = [] $.ajax({ method: "GET", url: endpoint, dataType: 'json', success: function(data){ labels = data.labels defaultData = data.default var ctx = document.getElementById("myChart") var myChart = new Chart(ctx, { type:'bar', data: { labels: labels, datasets : [{ label: '# of votes', data: defaultData, }] } }) }, error: function(error_data){ console.log("error on data") console.log(error_data) } }) {% endblock %} </script> {% block content %} <div class ='row'> <div class="col-sm-12" url-endpoint='{% url "get_data" %}'> <h1>Statistics for week 21</h1> <canvas id="myChart" width="400" height="400"></canvas> </div> </div> {% endblock content %} Views.py get_data() was used to test if I could … -
TypeError: int() argument must be a string or a number, not 'list' Django [on hold]
I am having this problem, since I am learning from the lists and I have a little cost, in this question first get the values entered in the text with the variable "cantidad", then I get the id of each object def ListEspeci(request, id_especialidad): especialidad = Especialidad.objects.get(id=id_especialidad) pedido = Pedido.objects.filter(especialidad=especialidad) if request.method == "POST": cantidad = request.POST.getlist("cantidad") pedido_list = Pedido.objects.filter(especialidad=especialidad).values_list('id', flat=True) Then the varibales throw: cantidad : ['8', '7', '5'] pedido_list : < QuerySet [2479, 2480, 2481]> What is required is that once these lists are obtained, it is necessary to insert the quantities ['8', '7', '5'] ] into the corresponding ids in the list < QuerySet [2479, 2480, 2481]> I am using this code to save the lists by filtering by id: pedido = Pedido.objects.filter(id=pedido_list).update(cantidad=cantidad) And throws the error: TypeError: int() argument must be a string or a number, not 'list' But throws that mistake and I don't know what to do, Please help, thank you beforehand! -
It's possible get current admin site from template
I have default AdminSite and custom AdminSite on my app. How to now what is the current admin-site from admin template. The only way is create a custom Mixin Class with custom method def each_context() and add current site in context variable ? -
Django CRUD operation on dynamic inline_formset
I have followed the tutorial from Nicole Harris Implementing Django Formsets as well as Daniel Chen's example Django Inline formsets example: mybook. Both use the Django Dynamic Formsets jquery plugin. I have tried to implement my own dynamic form, but the data does not delete from the model. The forms are marked for deletion when I call deleted_forms, and do not appear when I initially save changes and I receive a success message, but when I reload the page the data returns. I have implemented this two ways first: views.py def edit_case(request, case_slug): user = request.user cases = Case.objects.filter(user=user).order_by('date_due') try: filtered_case = Case.objects.get(slug = case_slug) except Case.DoesNotExist: filtered_case = None case_claims = Claim.objects.filter(case = filtered_case) claim_data = [{'claim':c.claim} for c in case_claims] extra_length = len(claim_data) + 1 ClaimFormset = inlineformset_factory(Case, Claim, fields= ('claim',), can_delete = True, extra = extra_length) if request.method =='POST': form = CaseForm(request.POST, instance =filtered_case) claim_formset = ClaimFormset(request.POST, instance =filtered_case,initial=claim_data) if form.is_valid() and claim_formset.is_valid(): form.save() claim_formset.save() else: form = CaseForm(instance = filtered_case) claim_formset = ClaimFormset(initial=claim_data) return render(request, 'cases/edit_case.html', {'form':form, 'claim_formset':claim_formset, 'cases':cases}) second: views.py def edit_case(request, case_slug): user = request.user cases = Case.objects.filter(user=user).order_by('date_due') try: filtered_case = Case.objects.get(slug = case_slug) except Case.DoesNotExist: filtered_case = None case_claims = Claim.objects.filter(case = filtered_case) … -
How to remove decimals from python django code
this is the code: def adprice(self): return self.get_ad().attr["price_net"] price_net has 2 decimals, but I don't want them to show. How can i remove them. -
Django redirect to view that is not in the same app
I have an app in my Django project called users. After logging into users/login.html, I want it to go to the URL /home.html My template structure is: --> users | .....-->login.html --> base.html --> home.html For some reason, it cannot find home.html though. Here are my views.py and urls.py in the users app: views.py urls.py -
Django unable to connect to database.
I am attempting to create a dev environment for my company's app using docker. For some reason I am able to connect to the database if I use docker run web "bash" then run mysql from the shell, but Django wont connect. The Dockerfile for the web/worker nodes looks like: FROM python:2.7 ENV PYTHONUNBUFFERED 1 ENV DOCKER 1 ENV REDIS_HOST "redis" ENV CASSANDRA_HOST "cassandra" RUN mkdir /code WORKDIR /code ADD . /code/ RUN pip install --default-timeout=100 numpy==1.9.1 RUN pip install --default-timeout=100 scipy==0.15.1 RUN pip install --default-timeout=100 -r requirements_docker.txt #RUN python /code/app/manage.py migrate And the docker-compose file looks like this: version: "2" services: cassandra: image: cassandra:latest redis: image: redis:latest db: image: mysql environment: MYSQL_DATABASE: appdb MYSQL_USER: dbuser MYSQL_PASSWORD: dbpass web: build: . command: python app/manage.py runserver 0.0.0.0:8000 environment: DOCKER: 1 DATABASE_HOST: db DATABASE_NAME: appdb DATABASE_USER: dbuser DATABASE_PASSWORD: dbpass REDIS_HOST: redis CASSANDRA_HOST: cassandra volumes: - .:/code ports: - "8000:8000" depends_on: - db - redis - cassandra worker: build: . environment: DOCKER: 1 DATABASE_HOST: db DATABASE_NAME: appdb DATABASE_USER: dbuser DATABASE_PASSWORD: dbpass REDIS_HOST: redis CASSANDRA_HOST: cassandra command: python /code/app/manage.py celery worker -Q celery,offline,periodic --broker=redis://redis:6379/4 depends_on: - db - redis - cassandra Finally the database settings are (consolidated from multiple settings files): if not os.environ.has_key('DOCKER'): … -
Why _set.all dont work in tempale?
I have 3 connected with each other models. GroupRequirementType --> GroupRequirement --> Requirement. I am tring to show all requirements in template. Next code show me only GroupRequirementType objects. It seems like I have problems with _set.all. Whats wrong? models.py: class GroupRequirementType(models.Model): name = models.CharField(_('Name'), max_length=250) class GroupRequirement(models.Model): group_requirement_type = models.ForeignKey(GroupRequirementType, on_delete=models.CASCADE) name = models.CharField(_('Name'), max_length=250) class Requirement(models.Model): group_requirement = models.ForeignKey(GroupRequirement, on_delete=models.CASCADE) name = models.CharField(_('Name'), max_length=250) template: {% for group_requirement_type in group_requirement_types %} {{ group_requirement_type }} {% for group_requirement in group_requirement_type.group_requirement_set.all %} <!--DONT WORK. WHY?--> {{ group_requirement }} {% for requirement in group_requirement.requirement_set.all %} {{ requirement }} {% endfor %} {% endfor %} {% endfor %} -
How can i set selected value after submit form
I have a form with month and year to select. I want to save selected values after page reload. I have project in django and i don't have any idea to do it. <form class="form-horizontal" method="post" action="show_incomes">{% csrf_token %}{{form}} <div class="form-group "> <label class="control-label col-sm-5" for="miesiac">Wybierz miesiąc</label> <div class="col-sm-3"> <select class="select form-control" id="miesiac" name="miesiac"> <option value="01" >Styczeń</option> <option value="02" >Luty</option> <option value="03" >Marzec</option> <option value="04" >Kwiecień</option> <option value="05" >Maj</option> <option value="06" >Czerwiec</option> <option value="07" >Lipiec</option> <option value="08" >Sierpień</option> <option value="09" >Wrzesień</option> <option value="10" >Październik</option> <option value="11" >Listopad</option> <option value="12" >Grudzień</option> </select> </div> </div> <label class="control-label col-sm-5" for="rok">Wybierz rok</label> <div class="col-sm-2"> <select class="select form-control" id="rok" name="rok" > <option value="2017" >2017</option> <option value="2018" >2018</option> <option value="2019" >2019</option> <option value="2020" >2020</option> <option value="2021" >2021</option> <option value="2022" >2022</option> <option value="2023" >2023</option> <option value="2024" >2024</option> <option value="2025" >2025</option> </select><br> <button type="submit" class="btn btn-large btn-info">Pokaż przychody</button> </div> </form> -
Django form with conditions for multiple models
I'm new to Django, and I've been fighting with this form for over a week now. I started this first because it is the core of my project. What I ultimately want is a single form that has a condition that the user can set, to add data to a second form when they check a radio box (will do that in jquery). I want to give admins the ability to register users, but I have a special subclass of users called operators that need additional information in a separate model. I almost have it working right now, but all users get added to the special subclass. Please help! Here is my code. NOTE: I messed up the password registration in this code, but I'll fix that later. Just working on this core functionality right now. Models class UserProfile(AbstractUser): bio = models.TextField(max_length=500, blank=True) birth_date = models.DateField(null=True, blank=True) profile_pic = models.ImageField(null=True, blank=True) notes = models.TextField(null=True, blank=True) def __str__(self): return self.first_name + ' ' + self.last_name class OperatorProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) cdl = models.ManyToManyField('CDL', blank=True) endorsement = models.ManyToManyField('Endorsement', blank=True) cdl_expiration = models.DateField(blank=True, null=True) def __str__(self): return str(self.user) Views class OperatorCreateView(CreateView): model = OperatorProfile template_name = 'pages/operatorprofile_form.html' form_class = UserCreationMultiForm success_url = … -
GeoDjango on Windows:
I've done this a dozen times before, but something isn't working this time.. Following the docs: https://docs.djangoproject.com/en/1.11/ref/contrib/gis/install/#windows I'm trying to set up GeoDjango on a Windows machine (this one is a virtual windows 10 set up on paperspace.com). There seems to be a problem with my PATH settings, but I can't figure out what it is. I've run the commands highlighted in the instructions. I've checked my PATH variables and everything seems ok. I've tried pointing them to both the 32-bit and 64-bit versions of OSGeo4Win. Regardless, I get the following output every time: C:\Python\lib\site-packages\floppyforms\__init__.py:21: UserWarning: Unable to import floppyforms.gis, geometry widgets not available "Unable to import floppyforms.gis, geometry widgets not available") Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Python\lib\site-packages\django\core\management\__init__.py", line 337, in execute django.setup() File "C:\Python\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Python\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Python\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File … -
Index Oracle XMLTYPE column with Django Haystack and ElasticSearch
I need to build an index in elasticsearch 2.4 and haystack 2.6. The model I'm working with has a field that maps to an XMLTYPE column in an Oracle 12c database. In my model_name_text.txt file I have {{object.xmltype_field}}. After I run manage.py rebuild_indexand try a search for something I know is in the XML I get no results. Can anybody help? Is haystack able to index XMLTYPE documents? Thanks! -
Django: triggering a change on template
I have an event app written in Django / uwsgi / nginx. A user makes a reservation, and it shows up in his "my reservations" page. For each event he can click on a check-in button, which checks him in. The event organizer also has a "my events" page that lists who has registered for the event and whether or not they've checked in. What I want is as follows, The user clicks on "check-in" The system records the check-in When the event organizer is LOOKING at his "my events" page, just as the check-in happens, his page updates to show that a particular user has checked in. How do I make this happen? How do I tell the organizer's "my events" template to update just after the user checks-in on his reservation? Seems like I need something on the template that's "listening" to some kind of a database update (say the check-in table)? How would I do this? Is this even possible? Thanks!! -
Handle connections to user defined DB in Django
I have pretty simple model. User defines url and database name for his own Postgres server. My django backend fetches some info from client DB to make some calculations, analytics and draw some graphs. How to handle connections? Create new one when client opens a page, or keep connections alive all the time?(about 250-300 possible clients) Can I use Django ORM or smth like SQLAlchemy? Or even psycopg library? Does anyone tackle such a problem before? Thanks -
Django MongoDB engine
I want to develop a project with django and mongodb. but according to below link mongoengine is not developed and is not stable version. mongoengine django So I found pymongo but I want to use model in django. please help me and give a suggestion. -
sending email using authtools for django - invatation
I have found authtools which seems to offer nice solutions for User model in django. From their documentation: (LINK) This is a nice piece of code, which helps me to set custom USER, however my question is how to apply email sending with this package. Meaning: when new User is saved, send him an email. As you can see from code, there is no documentation on how to setup outgoing email and how to apply it in the code. Please note, I am not a django developer and I would really appreciate if you could help me with this. -
Django: return form data on the same page
How can I add "headers" to context so it's accessible in templates. I guess it needs to be pass to get request somehow? What would be the pythonic way to pass this variable to a get method in FormView class? views.py class IndexView(FormView): template_name = 'index.html' form_class = CheckForm success_url = reverse_lazy('index') def form_valid(self, form, **kwargs): context = self.get_context_data(**kwargs) context['headers'] = form.result() return super(IndexView, self).form_valid(form) index.html <form action="." method="post" name="url" id="url" novalidate> {{ form.as_p }} {% csrf_token %} <button type="submit">Check</button> {% if headers %} {% for k,v in headers %} {{ k }}: {{ v }}<br> {% endfor %} {% else %} <br>No data {% endif %} forms.py from django import forms import requests class CheckForm(forms.Form): url = forms.URLField(max_length=255, label='') def result(self): cd = self.cleaned_data url = cd['url'] r = requests.get(url) r.headers return r urls.py urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), ]