Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to install packages with pip
I've been unable to download any package with pip and I keep getting the same error about a problem confirming the ssl certificate. I'm currently on my universities network and I also have Anaconda installed on my laptop. I'm not sure if those two factors have anything to do with this issue. My python version is 3.7.0 Pip version 9.0.1 Pip3 version 10.0.1 When I put pip install django in the terminal I get this result: Collecting django Could not fetch URL https://pypi.python.org/simple/django/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749) - skipping Could not find a version that satisfies the requirement django (from versions: ) No matching distribution found for django I've read several other threads. I've tried commands such as these without success: curl https://bootstrap.pypa.io/get-pip.py | python3 pip install --upgrade pip pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org django -
Check User is registered or not in Django 2.0
Currently, the admin(superuser) is creating the users and sending the details along with reset password link to the users through email. The user will click on the reset password link and change there password. Now the admin must know whether the user has logged in to the system after resetting the password. The Admin must be notified as user active(user logged in) or inactive(user not logged in yet). I am new to Django and don't know how to determine whether the user has logged in or not. -
Django Microsoft Office 365 Login
I am currently working with a team to develop a web application for my college using the Django framework. We primarily use Office 365, so I have been looking for a solution to use Office 365 authentication to authenticate users of our application. I have not found anything that can achieve this. Note: I have used social-auth to allow users to login with Google, but this is only temporary until I find a way to use Office 365. Any suggestions will be wonderful! -
Django fetch result of latest related object by condition
I have two models class Customer(models.Model): created = models.DateTimeField(auto_now_add=True) # some other fields, which don't matter class ActivityStatus(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=5) class Activities(models.Model): created = models.DateTimeField(auto_now_add=True) status = models.ForeignKey(ActivityStatus) planned_execution_date = models.DateField() also I have them in admin class CustomerAdmin(admin.ModelAdmin): fields = () # doesn't matter really list_display() # doesn't matter really class ActivityAdmin(admin.ModelAdmin): fields = () # doesn't matter really list_display() # doesn't matter really I want to add custom field (last_activity_planned_date) to be displayed on changelist_view of CustomerAdmin. Here is the condition: - show planned execution date of latest activity of Customer but only if this activity has status_id = 2. Otherwise show nothing Example 1 Customer 1 has 2 activities - the latest has status_id = 2 and planned_execution_date = 2017-09-17 changelist_view: |id|last_activity_planned_date| |1|2017-09-17| Example 2 Customer 1 has 2 activities - the latest has status_id = 3 and planned_execution_date = 2017-09-27 |id|last_activity_planned_date| |1|null| -
Django iframe: sessionkey being created every request
I have a shopify app built in Django that was working fine up until recently. The sessions are not persisting across each request and as a result an exception is being raised because the session for that given key that was set in the previous request does not exist. Trying the app endpoints outside of Shopify works fine, the sessions persist perfectly between requests so it definitely is an issue within Shopify. Looking at the sessions table in our database we see multiple sessionkeys with the same data, this indicates another session is being created per request. How do we persist sessions across requests in an iframe? -
Django-local variable error referenced before assignment python2.7
i have write web with Django This is my code: from __future__ import unicode_literals from end.models import Author , Book from django.shortcuts import render , render_to_response # Create views here. def searching(request): if 'TexBox' in request.GET and request.GET['TexBox']: q = request.GET['TexBox'] book = Book.objects.filter(Name=q) return render_to_response("index.html" , {"album" , book}) when i runserver that's get me this error: local variable 'book' referenced before assignment -
Template localization on background
I'm using Django-background-tasks to sending emails asynchronously. When I'm sending email in view, localization work perfect, but when I'm trying to send same email from background, Django rendering template with default locale. Here is code which I'm using to sending emails : Function that I'm calling from views.py tasks.py @background() def send_email_async(email, json): send_email_(email, json) email_utils.py def send_email(context_dict, email_template_name, email_header_data, user_email): subject = ''.join(email_header_data['subject'].splitlines()) email_render = loader.render_to_string(email_template_name, context_dict) email = EmailMessage(subject=subject, body=email_render, from_email=settings.EMAIL_HOST_USER, to=[user_email]) email.content_subtype = "html" email.send() return How to make Django-rest-framework render template according to the language specified in header Accept-Language? -
1 Django site with 3 differents domains how to host that?
I have one Django project, one website, but each translation is represented by a domains, drenglish.com for english, drspanish.com for spanish and drportuguese.com for portuguese. There is only one admin, one database i see with most host for django (2.0 and python 3.7) y your need to host throught ssh linux(putty). but how can i make the 3 domains work at the same time ? sorry for the noob question its my first time putting a website up if any help that is the middleware i use to detect the domain and offer the right language class SetLanguageToDomain: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): current_site = get_current_site(request).domain if current_site == 'www.drportuguese.com': user_language = 'pt_BR' elif current_site == 'www.drspanish.com': user_language = 'es_ES' else: user_language = 'en' translation.activate(user_language) request.session[translation.LANGUAGE_SESSION_KEY] = user_language response = self.get_response(request) return response -
Open IE browser window using python when link is clicked
I need a url to be opened in a IE browser specifically. I know the following code is wrong but I don't know what else to try. How can I achieve that through python? template <a href="{% url 'browser:ie' %}" target="_blank"> Open in IE </a> urls.py url(r'^open-ie$', views.open_in_ie, name='ie'), views.py import webbrowser def open_in_ie(request): ie = webbrowser.get(webbrowser.iexplore) return ie.open('https://some-link.com') Again, I know this is wrong and it tries to open the ie browser at a server level. Any advices? Thank you! -
How to use the instantaneous request controller pattern in Django REST Framework?
I'm trying to use this pattern to write reproducible tests which check that the date given by the user is in the future, but I can't quite fit my head around how it would work in Django. What I'm trying to do is as follows: I have a model with a DateTimeField, which when created must verify that the field value is in the future. That is, if the value is in the past, it should throw a ValidationError. Obviously, when running in production the code should use the actual current time. The tests should call something to trigger this validation error. The tests must inject the current time into whatever they are calling to ensure that the test is reproducible. What would be an idiomatic way of doing this using the Django REST Framework? I've come up with a couple possibilities, neither of which work: Create a plain subclass of the model with instant = models.DateTimeField(). This of course would result in another table and column, which is obviously unacceptable. Create a proxy subclass of the model with instant = models.DateTimeField(). It's not possible to add fields to proxy models, so that's out. -
Django problem with access to the file while using the .delete() method
I'm struggling with the following problem. In my application I have a model containing an InputFile() field. In this field, it stores .mat files, which then I open in the view using methods from the scipy library. I have also implemented a mechanism to delete records from the database, along with files uploaded to the server. It works until I try to open the file from InputFile() and load data from it. Then, when I try to delete a record with this file, I get a message that this .mat file is being used by another process. How to do it so that the 'connection' to the file will end after saving its contents in the variable in the view? I will be grateful for any help. -
Generate PDF from HTML using Python with multiple orientation(Portrait and Landscape)
I designed the PDF(template) in HTML and converting/using it in Python. I need both orientation in my PDF output(Portrait and Landscape)? -
$group returning empty rows when I use aggregate
I want DISTINCT rows with my query. I am getting total instead of distinct rows. I tried $group but that is returning empty rows Query: pipeline = mycol.aggregate([ { '$lookup': {'from': "theUL", 'localField': "data.rID", 'foreignField': "aR", 'as': "yo"} }, { '$unwind': "$yo"}, {"$unwind":"$tags"},{'$match': {'tags.tag.name':'A A', 'url': {'$regex': 'abc.com'}}}, {'$group':{ '_id' : {'aR': "$aR"}} }, { '$project': {"aR":1, "yo.user_email":1, "_id":0} } ]) for doc in pipeline: pprint (doc) Result: { } { } { } Expected Result: Distinct rows I am new to MongoDB. Please help -
Deploying Django app with Channels on a Shared Linux Hosting
I have developed a simple django application using channels & deployed it in a shared linux hosting service(mochahost.com - Webhosting: mocha package). It serves django app with help of Passenger. The wsgi is working without any issue but the ASGI layer seems to be non responsive. When trying to connect, I am getting the following error message: Error during WebSocket handshake: Unexpected response code: 404 I don't know how to resolve this. Is there any extra setup steps I need to follow or any other settings I need to do? Any help would be very much appreciated. Package versions used: Python: 3.6.6 Django: 2.1.1 Channels: 2.1.3 Channels_redis: 2.3.0 -
Reuse Cache if Function Returns Blank in Django
I am hoping to use Django's cache to keep track of a list of companies returned by an external API call. However, on weekends the server I am calling from returns a blank list. Is there a way to use the last cache if the API call returns a blank list? Thanks. -
why is django 1.11 form working in debug mode only
I am trying to edit a form with django 1.11 when i try to execute normally. i get this error. Request Method: GET Request URL:https://laisdev.goslnet.gov.lc/parcelmanager/1221B11/editParcelInfo/ Django Version: 1.11 Exception Type: TypeError Exception Value: build_attrs() takes from 1 to 2 positional arguments but 3 were given Exception Location: /home/lais/laisvenv/lib/python3.6/sitepackages/django/forms/widgets.py in get_context, line 211 Python Executable: /usr/local/bin/python3 Python Version: 3.6.1 Python Path: ['/home/lais/laisy', '/home/lais/laisvenv/lib/python3.6/site-packages', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages'] Server time: Wed, 3 Oct 2018 14:11:03 -0500 but when i run in debug mode page displays fine -
Django + Plesk + Apache - Forbidden 403 on certain urls but 404's show application is running...?
Disclaimer: this may well be a duplicated answer. However, I'm very tried, frustrated and lost on this. Happy for anyone to point me in the right direction! :) Issue: Using Plesk Onyx, I'm trying to deploy my Django application via Apache. I'm seeing Forbidden 403 on certain urls but 404's on others that throw a 404. So, the Django application is "working" - but somewhere my permissions have hit a brick wall... So - navigating to https://api.winduplordvexxos.com/admin/ or https://api.winduplordvexxos.com hits a complete 403 brick wall. However, when navigating to any 404 I see the Django 404 url lookup error page: This is progress - the wsgi process is there working somewhere. My http and https directives are as follows, along with blank nginx directives: The above configuration works fine for manual deployment to a server without nginx installed... Seeing this page gives me so much hope! :D I'm almost there... N.B.: mod_wsgi is installed. I'm running Ubuntu 16.04. My server has Plesk Onyx installed. Nginx is getting in the way, etc etc So, my theoretical solution is somehow maybe involving nginx? Turning it off? :D Or perhaps giving it permission to work in conjunction with Apache...? -
Django Queryset .save() is slow
I'm trying to perform some operations over a queryset and then use the .save() on each model instance, but it seems to be slow. for clock in Clocks.objects.filter(status=True): # actions here clock.save() Is this correct or is there any other method to be used when updating a model instance within a queryset. Do you think DRF can perform this any better? -
Selenium - python. how to capture network traffic's response
I am using python Django to create a web app. i am using selenium to launch a headless browser(phantomjs) and making some clicks till i reach a particular page. I wish to capture network traffic and get the response of a particular network call. This network call actually holds a html doc as it's response. Any way to achieve this ? -
Get Content of Template Block to Use in IF Statement
Currently I have a block setup for my page titles in my base.html. It takes a unique value from each template page, and adds the website name to the end. For example: ABOUT US - My Site Name. The "ABOUT US" is passed by template and " - My Site Name" appears on every page regardless. However, I want to use the same base.html on my index page, but only show "My Site Name." I was hoping to use an if statement by parsing the block each template passes to look for a unique value, signifying I am on the index page. So far my code looks like this: <title> {% if {% block title %}{% endblock %} == "index_pg" %} TEST {% else %} {% block title %}{% endblock %} - The Stock Column</title> {% endif %} obviously this doesn't work. Anyone ideas on how I can accomplish this? Thanks. -
How to show Python print() in html div
I am using Django to write my website. During writing my Python code I have many print functions. They all are shown in standard console. I would like to show (live without refreshing a page) all my prints in div in my HTML code not only in console. How to do that? My code do: You press button then selenium starts using ajax without refreshing page and during that I would like to show progress on a page using div. For example, my code: views.py bot = Instagram() class InstabotFormView(AjaxFormMixin, FormView): form_class = LoginInstagramForm template_name = 'instabot.html' success_url = 'runinstabot.html' def form_invalid(self, form): response = super(InstabotFormView, self).form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): response = super(InstabotFormView, self).form_valid(form) login = form.cleaned_data.get('login') password = form.cleaned_data.get('password') tagi = form.cleaned_data.get('tags') func = form.cleaned_data.get('function') tags = [] tagi = tagi.split(',') tags.extend(tagi) if self.request.is_ajax(): print('It is AJAX') bot.login(login,password) bot.search(tags) if func == '1': bot.downloadPhoto(tags) elif func == '2': bot.doCalculation(tags) print(tags) data = { 'message': "Succesfully opened Selenium." } return JsonResponse(data) else: return response Instagram() def downloadPhoto(self): i = 0 time.sleep(2) self.driver.find_element_by_xpath('/html/body/span/section/main/div/header/section/ul/li[2]/a').click() print('Start function downloadPhoto') print(self.myCurrentList) for photo in self.myCurrentList: followerPhoto = self.myCurrentList.index(photo) + 1 print(followerPhoto) How to show all prints from … -
Django loading json objects to templates
I am getting data from firebase views.py def posts (request): _posts= ref.child('posts').get(); #getting data from firebase[enter image description here][1] return render(request, 'post.html', {'postList': _posts}) index.html {% for item in postList %} {{ item.title}}</br> {% endfor %} my firebase data -
How to input data into different objects in the same database through forms on same html page?
The html page consists if two forms of similar type and refers to same database. The form should take input details of a family of two. However after inputting and submitting the form, the older written objects in the database are erased and overwritten by the newly created objects. I want the objects to be created seperately. This is my index.html <h1>Fill the form below</h1> <form method="post"> {% csrf_token %} <h1>Enter name</h1> {{ form.name }}<br><br> <h1>Enter age</h1> {{ form.age }}<br><br> <h1>Enter phone number</h1> {{ form.phone }}<br><br> <h1>Enter name</h1> {{ form.name }}<br><br> <h1>Enter age</h1> {{ form.age }}<br><br> <h1>Enter phone number</h1> {{ form.phone }}<br><br> <input type="submit" value="Submit file1"/> </form> -
Django forms choicefield is empty after render
For some reason I can't get this to work so please help me out.. I have a choicefield that have 3 choices in a dropdown. I can choose them the first time, and then submit. However after I hit submit, I want to choose again but my dropdown become empty...and I would have to refresh the page for it to appear again. Why? views.py: I put forms inside because it's short def home(request): class My_form(forms.Form): my_choices = [('TEST', 'TEST'), ('ABC', 'ACB'), ('XZY', 'XZY')] symbol=forms.ChoiceField(choices=my_choices) if request.method == 'POST': test_form = My_form(request.POST) if test_form.is_valid(): symbol = test_form.cleaned_data['symbol'] return render(request, 'blog/home.html',{'symbol':symbol}) else: messages.error(request, "Error") else: test_form = My_form() return render(request, 'blog/home.html', {'test_form':test_form} ) template: {% extends "blog/base.html" %} {% block content %} <form width="600px" action="." method="post" >{% csrf_token %} <div class="row align-items-start"> <div class="col-sm-5"> <label for="symbol">Stocks</label> <select class="form-control" id="symbol" name ="symbol"> {% for key in test_form.symbol %} <option >{{key}}</option> {% endfor%} </select> {{ test_form.errors }} {{ test_form.non_field_errors }} </div> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> {% endblock content %} -
Convert Python instance-based program to Django database
My Python knowledge is primarily in back-end, non-GUI/non-web programming. I have a program that simulates a fuel storage and transfer system. The primary program uses instances of valves, pumps, etc. to track system parameters (a database would probably make more sense, but classes for physics modeling made more sense at the time). Below is an example of the Valve class: class Valve: def __init__(self, name="", sys_flow_in=0.0, sys_flow_out=0.0, drop=0.0, position=0, flow_coeff=0.0, press_in=0.0): self.name = name self.__position = int(position) # Truncate float values for ease of calculations self.Cv = float(flow_coeff) self.flow_in = float(sys_flow_in) self.deltaP = float(drop) self.flow_out = float(sys_flow_out) self.press_out = 0.0 self.press_in = press_in def calc_coeff(self, diameter): self.Cv = 15 * math.pow(diameter, 2) def press_drop(self, flow_out, spec_grav=1.0): try: x = (flow_out / self.Cv) self.deltaP = math.pow(x, 2) * spec_grav except ZeroDivisionError: return "The valve coefficient must be > 0." def valve_flow_out(self, flow_coeff, press_drop, spec_grav=1.0): try: if flow_coeff <= 0 or press_drop <= 0: raise ValueError("Input values must be > 0.") else: x = spec_grav / press_drop self.flow_out = flow_coeff / math.sqrt(x) return self.flow_out except ValueError: raise # Re-raise error for testing def get_press_out(self, press_in): if press_in: self.press_in = press_in # In case the valve initialization didn't include it, or the value …