Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding testing stage into Jenkins file
I am trying to add Testing stage into my Jenkins file. I have docker installed in the Jenkins. I run my tests with this command: docker-compose run web python manage.py test This is my Jenkins file: node{ stage('Checkout'){ def dockerHome = tool 'docker' env.PATH = "${dockerHome}/bin" checkout scm } stage('Build image') { withEnv(['PATH+EXTRA=/usr/sbin:/usr/bin:/sbin:/bin']){ sh "docker login --username=mygituks --password=mdj1646MDJ" sh "docker build -t my_git_uks -f Dockerfile ." sh "docker tag my_git_uks gituks/uks-git-2019:second" } } stage('Run Tests') { withEnv(['PATH+EXTRA=/usr/sbin:/usr/bin:/sbin:/bin']){ def testsError = null try { sh "docker-compose run web python manage.py test" } catch(err) { testsError = err echo "Failure" } } } stage('Push image') { withEnv(['PATH+EXTRA=/usr/sbin:/usr/bin:/sbin:/bin']){ sh "docker push gituks/uks-git-2019:second" } } } And I get this error: docker-compose: command not found This is one of the things I also tried and I get this error: test.sh: line 3: python: command not found I added test.sh: #!/bin/bash python manage.py test And changed my Testing stage to: stage('Run Tests') { withEnv(['PATH+EXTRA=/usr/sbin:/usr/bin:/sbin:/bin']){ def testsError = null try { sh "bash test.sh" } catch(err) { testsError = err echo "Failure" } } Hope someone can help me to figure this out or give my any hints. -
Can I populate my arrays with values from API call using a for loop, through a function
I'm trying to populate 2 arrays with data that I have received from an API call. I have a loop but am not very good with javascript. Could I get some on on the loop and how to add the desired values to the array AJAX call below and arrays below var prevHour_endpoint = 'https://min-api.cryptocompare.com/data/histominute?fsym=BTC&tsym=EUR&limit=60' var prevHour_defaultData = [] var prevHour_labels =[] var graphData $.ajax({ method: "GET", url: prevHour_endpoint, success: function(data){ graphData = data populateData() }, error: function(error_data){ console.log("error") console.log(error_data) } }) populate function and loop I am trying to implement below function populateData(){ for (x in graphData.data) { prevHour_labels.push(data.high) prevHour_defaultData.push(data.close) } } -
How to return an object in jsx and use in immediately with out depending on setState as its Asynchronous
I am new to react and I am trying to do DRF (Django Rest Framework) with React so I am using the fetch() with required attributes to hit the API endpoint and getting some data. Now in my case, I need to hit two API endpoints. But I wanted to reuse the fetch() by putting it in a function which will return an object and I'll save using setState. My problem is the endpoint URL for the second API call is in the object returned by the first API call. Example: fetch(enpoint1, data) -> returns {name: 'something', url: 'endpoint2'} if I do setState here the object is not updated as setState is Asynchronous and so I cannot use it immediately. I might have a super silly mistake. Any advice on the "way I am doing it" or "on how to correct it" would be appreciated. componentDidMount() { let currentComponent = this; try { const data = {username: 'username', password: 'password'}; //gets me the token fetch(URL(Just example), { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(data) }).then(function(response) { return response.json(); }).then(function(data){ return data.token }).then(function(token){ var project_object = currentComponent.fetchFunction(currentComponent.props.endpoint, token) console.log(project_object) //This is UNDEFINED }) } catch (e) { … -
Django webpack doesn't render things from angular
I followed this: How to host Angular 6 application in Python Django?. But when I go to the browser, I can't see only "Loading...", there isn't any errors. But, when I go /dist/angular/index.html, page in browser is blank, and there are 6 "NET::ERROT RESOURCE NOT FOUND". Can someone help? -
django.template.library.InvalidTemplateLibrary: Invalid template library specified
I am trying to build a Blog application. Ran makemigrations and migrate and also created superuser. But I am getting below error while running the server. django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'blog.templatetags.blog_tags': cannot import name 'POST' from 'blog.models' Please help me.... My models.py file is from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.urls import reverse # Create your models here. class CustomManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') from taggit.managers import TaggableManager class Post(models.Model): STATUS_CHOICES=(('draft','Draft'),('published','Published')) title=models.CharField(max_length=256) slug=models.SlugField(max_length=264,unique_for_date='publish') author=models.ForeignKey(User,related_name='blog_posts',on_delete=models.DO_NOTHING) body=models.TextField() publish=models.DateTimeField(default=timezone.now) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) status=models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft') objects=CustomManager() tags=TaggableManager() class Meta: ordering=('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail',args=[self.publish.year,self.publish.strftime('%m'),self.publish.strftime('%d'),self.slug]) class Comment(models.Model): post=models.ForeignKey(Post,related_name='comments',on_delete=models.DO_NOTHING) name=models.CharField(max_length=40) email=models.EmailField() body=models.TextField() created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) active=models.BooleanField(default=True) class Meta: ordering=('-created',) def __str__(self): return 'Commented by {} on {}'.form(self.name,self.post) -
How can I start a command management when server is running?
I'm new in Django and I am creating a web application for uni project. I have to send emails periodically, and to do so I'm using a management command, but I don't know how to make it automatically run when I start the server. I'm working on Pycharm in Windows 8.1 from django.core.mail import send_mail from django.core.management.base import BaseCommand from ProgettoDinamici.settings import EMAIL_HOST_USER from products.models import Notification from users.models import User class Command(BaseCommand): help = 'Sends emails periodically' def handle(self, *args, **options): users = User.objects.all() for u in users: try: notify = Notification.objects.filter(receiver=u, read=False) count = notify.count() except: print("No notification found") try: if notify: send_mail( 'E-Commerce', 'You have ' + str(count) + ' notifications.', EMAIL_HOST_USER, [u.email], fail_silently=False, ) except: print("error") For now I tried to use schedule and cron to repeat the send_email every n minutes, but nothing worked and searching online I found out that cron (and cron based) ins't supported by Windows. But this is another problem... -
Dynamically create fields in Django Serializers
I am trying to get Django's Dynamic Field Serializer working. So far I've tried a few things: Dynamic Modifying Fields Here is my implementation: class DynamicFieldsModelSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) dd={} for i, h in enumerate(settings.LOCATION_HIERARCHY): dd[f'step_{i}'] = serializers.CharField(trim_whitespace=True) if dd is not None: self.data.update(dd) and then from the actual serializer (again in serializers.py): class LocationSerializer(DynamicFieldsModelSerializer): class Meta: model = Location exclude = ('some', 'fields', 'to', 'exclude',) From views.py: class LocationEntry(GenericAPIView): serializer_class = LocationSerializer SerializerMethod Adding it as a property to the actual model I don't get any errors, but when I look at it in the REST API view in the browser it doesn't seem like it's picking up the changes. It would be highly appreciated if someone can point me to what am I doing wrong. Thanks in advance -
How to troubleshoot django-allauth ‘get_access_token’ method when using django-rest-auth to retrieve Reddit token fails with 429 error
I'm setting up social authentication through Reddit for an application using django-rest-auth and django-allauth. My problem is that django-allauth returns a 429 error from Reddit when I attempt to retrieve the access token using the django-rest-auth endpoint. However, when I try to call the the Reddit api directly, using everything outlined in the Reddit api documentation, I am able to do it successfully. I'd like to be able to make this call through django-rest-auth so I can benefit from the way it integrates with Django. I have already quadruple-checked every setting outlined in the django-rest-auth documentation, including the usual culprits for Reddit returning a 429 error: redirect_uri and the User-Agent value in settings.py . I've even used a packet sniffer to intercept the HTTP request, although that didn't work out because it was encrypted, of course. Here are the rest-auth urls: path('rest-auth/',include('rest_auth.urls')), path('rest-auth/registration/',include('rest_auth.registration.urls')), path('rest-auth/reddit/', views.RedditLogin.as_view(),name='reddit_login'), ] Here's the relevant view in views.py: #imports for social authentication from allauth.socialaccount.providers.reddit.views import RedditAdapter from allauth.socialaccount.providers.oauth2.client import OAuth2Client from rest_auth.registration.views import SocialLoginView class RedditLogin(SocialLoginView): adapter_class = RedditAdapter callback_url = 'http://localhost:8080/register' client_class = OAuth2Client Here are relevant settings in settings.py: SOCIALACCOUNT_PROVIDERS = { 'reddit': { 'AUTH_PARAMS': {'duration':'permanent'}, 'SCOPE': [ 'identity','submit'], 'USER_AGENT': 'web:applicationnamehere:v1.0 (by /u/myusername)', } … -
How do I represent complex subqueries and calculated tables in Django ORM?
I have the following SQL that basically works. How would I represent this in Django ORM? I'd like to avoid running a full raw query I am not sure how to go about the subquery in Django ORM and how to properly execute the cartesian product (achieved by the CROSS JOIN) SELECT datum, alldata.worker_id, reporting_plan.project_id, SUM(effort::float)/60/60 FROM (SELECT DISTINCT datum, reporting_plan.worker_id AS worker_id FROM (SELECT datum::date FROM generate_series('2019-05-01', '2019-12-31', '1 day'::interval) datum) AS dates CROSS JOIN reporting_plan ORDER BY datum, worker_id) AS alldata LEFT OUTER JOIN reporting_plan ON alldata.worker_id = reporting_plan.worker_id AND datum <= reporting_plan.end AND datum >= reporting_plan.start GROUP BY datum, alldata.worker_id, reporting_plan.worker_id, reporting_plan.project_id ORDER BY datum, alldata.worker_id, reporting_plan.worker_id, reporting_plan.project_id The expected result is a list with all dates in the timeframe and all workers and matching planning information (projects and effort). Thanks! -
Handle invalid data when using Django UpdateView subclass for object duplication
I'm doing the following, which works nicely when the user proceeds down the golden path: class MyUpdate(UpdateView) # ... class MyDuplicate(MyUpdate): def get_context_data(self, **kwargs): context = super(MyDuplicate, self).get_context_data(**kwargs) context['action'] = "Duplicate" return context # where should I call Klass::duplicate? def form_valid(self, form): name = form.instance.full_name video_url = form.instance.video_url # This doesn't work because it can result in unhandled uniqueness # constraint violations. form.instance = Klass.duplicate( form.instance, name, video_url ) return super(MyDuplicate, self).form_valid(form) However, if the user attempts to submit an existing full_name (which must be unique), then the call to Klass.duplicate results in an unhandled uniqueness constraint violation. So, my question is: where should I make the call to Klass.duplicate (unsets pk, resets other values and then calls save -- elided for brevity) in the UpdateView lifecycle? -
Create two types of users
I want to create two types of Users (teacher and student as example) with different views & forms & templates and signals using Django framework 2.2 .I read the documentation but i didn't understand it well.How to do it in the same app ? ..I created (student) User -
Django Models design: many-to-many relationship with specific needs
I am in the process of designing a couple of new models for my django app and this is what I need: class Bookmaker(models.Model): name = models.CharField(max_length=50) accepted_countries = ? restricted_countries = ? class Country(models.Model): name = models.CharField(max_length=50) bookmakers = ? So I need a model Bookmaker and a model Country and they need to be related, BUT every bookmaker should have a list of countries that are accepted and a list of countries that are excluded. Not sure if I'm on the right path, but I'm thinking that I need a couple of many-to-many relationships and how can I use the same Country model (those will be different instances) in both accepted_countries and restricted_countries? Thanks. -
Page 404's depending on its position in 'urlpatterns' - why?
So I'm trying to render the page 'submit' which has a generic.CreateView which is correctly configured. This URL pattern renders fine: from django.contrib import admin from django.urls import include, path from curate import views urlpatterns = [ path('', views.SetListView.as_view(), name='set_list'), path('new/', views.ItemListView.as_view(), name='new_list'), path('<int:pk>/edit', views.ItemEditView.as_view(), name='item_edit'), path('<int:pk>/delete', views.ItemDeleteView.as_view(), name='item_delete'), path('submit/', views.SubmitItem.as_view(), name='submit_item'), path('<slug>/', views.ItemDetailView.as_view(), name='item_detail'), path('<int:pk>/', views.ItemDeleteView.as_view(), name='item_detailPK'), path('<slug>/', views.SetDetailView.as_view(), name='set_detail'), ] But for some reason, if the Submit view is elsewhere in the list, ie like below, as in it's below the ItemDetailView.as_view() url, then it won't render, it just 404's. from django.contrib import admin from django.urls import include, path from curate import views urlpatterns = [ path('', views.SetListView.as_view(), name='set_list'), path('new/', views.ItemListView.as_view(), name='new_list'), path('<int:pk>/edit', views.ItemEditView.as_view(), name='item_edit'), path('<int:pk>/delete', views.ItemDeleteView.as_view(), name='item_delete'), path('<slug>/', views.ItemDetailView.as_view(), name='item_detail'), path('submit/', views.SubmitItem.as_view(), name='submit_item'), path('<int:pk>/', views.ItemDeleteView.as_view(), name='item_detailPK'), path('<slug>/', views.SetDetailView.as_view(), name='set_detail'), ] The weird thing is, the ItemDetailView is rendering fine - this powers all of the items on my page? -
unable to update reverse relation fields in update UpdateAPIView django rest
I have profile models related to user class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) stream_name = models.CharField(max_length=30, blank=True) serializerr.py class ProfileSerializer(serializers.ModelSerializer): first_name = serializers.SerializerMethodField() last_name = serializers.SerializerMethodField() def get_first_name(self, profile): return profile.user.first_name def get_last_name(self, profile): return profile.user.last_name class Meta: model = vtu_models.Profile exclude = ('id', 'user') view.py class UserProfileChangeAPIView(generics.RetrieveAPIView, generics.UpdateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = api_serializers.ProfileSerializer # parser_classes = (MultiPartParser, FormParser,) def get_object(self): obj = get_object_or_404(User, email=self.request.user.email) return obj.profile # def put(self, request, *args, **kwargs): # return self.update(request, *args, **kwargs) def update(self, request, *args, **kwargs): instance = self.get_object() instance.user.first_name = request.data.get("first_name") instance.user.last_name = request.data.get("last_name") instance.save() serializer = self.get_serializer(instance, data=request.data) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) this my code get the profile details and user first name and last name but put request only updating profile details but not user first name and last name (this reverse relation) -
Change the format of DateTimePicker dynamically for Django form
The format changes when I change the site language. '%d/%m/%Y' changes to '%m/%d/%Y'. So I can't save the information in the form to the database. Example: '%d/%m/%Y'(24.11.2003) as save in Turkish. But I get an error when I want to update in English. Because format changes as '%m/%d/%Y'(11.24.2003). It is my forms. forms.py 'date1': DatePickerInput(format='%d/%m/%Y'), 'date2': DatePickerInput(format='%d/%m/%Y'), -
Filter drafts and future posts with a view
I've defined drafts and future posts into my models.py and whit the follow snippet I can see that my changes works fine for a generic list of posts: def index(request): post_list_full = MyPost.objects.filter(draft=False).filter(publishing_date__lte=timezone.now()) paginator = Paginator(post_list_full, 9) page = request.GET.get("pagina") post_list = paginator.get_page(page) context = {"post_list": post_list} return render(request, "personalblog/mylist_posts.html", context) I've a couple of posts as draft and they are not present in the list of all the posts. But the same thing don't happen if I try to see the list of posts by category using this: def mysingleCategory_postList(request, slug_category): category = get_object_or_404(MyCategory, slug_category=slug_category) blogpost = MyPost.objects.filter(category=category).filter(draft=False).filter(publishing_date__lte=timezone.now()) print(blogpost) context = { "category": category, "blogpost": blogpost, } print(context) return render(request, "personalblog/mysingle_category.html", context) The other strange thing is that the print function shown me all the posts of the specific category except the draft posts. I'm a newbie of Django, what I've wrong? -
ListView queryset Can not pass context data to Template
I am having trouble with my Search API. Results of the queryset could not get through my template even though the query set fetched data from the model. If the search is empty the queryset should return all the Models associated to the current project, otherwise, it should return models that qualify the criteria in the query. I have tested the result of the query and it returns records from the model but could not display the instances into the template. My SEARCH ListView: class ModelSearchListView(ListView): model = Model template_name = 'predictions/model_listview.html' context_object_name = 'models' paginate_by = 2 def get_queryset(self): query = self.request.GET.get('q') proj_pk = self.kwargs.get('pk') proj = get_object_or_404(Project, id=proj_pk) if query: result = Model.objects.filter(Q(project=proj.id) & (Q(name__contains=query) | Q(algorithm_type__contains=query) | Q(predictors__contains=query) | Q(target_column__contains=query))).order_by('-date_created') # print('result: ', result) else: result = Model.objects.filter(project=proj.id).order_by('-date_created') print('result: ', result) return result def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) project = Project.objects.filter(id=self.kwargs.get('pk')).first() context['current_project'] = project.id MY SEARCH FORM: <form class="form my-2 my-lg-0" method="GET" action="{% if current_project %} {% url 'model-search-listview' current_project %} {% else %} {% url 'model-search-listview' object.project.id %} {% endif %}"> <div class="input-group"> <input class="form-control " type="text" name="q" value="{{ request.GET.q }}" aria-label="Search" placeholder="Search"> <span class="input-group-btn"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit" value="Search"> Search </button> </span> … -
How to integrate Chart.js in Django?
So first of all, I am a bloody beginner at Django and Chart.js. What I want to do: I want to display a pie chart. I know that with the syntax {{content}} a .html template can get dynamic data but it doesn't work for my piechart template. What I have: I have my pie chart ready as a .html template for my app. It already works perfectly fine when I directly code the data into the template. my view: def index(request): return render( request, "mep/chart.html", { labels: ['F', 'M'], data: [52, 82], colors: ["#FF4136", "#0074D9"] } ) my template: <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" <title>Geschlechtsverteilung Patientendaten </title> </head> <body> <div class="container"> <canvas id="myChart"></canvas> </div> <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'pie',// bar, horizontalBar, pie, line, doughnut, radar, polarArea data: { labels: {{labels}}, datasets: [{ data: {{data}}, backgroundColor: {{colors}} }] }, options: { title: { display: true, text: 'Geschlechtsverteilung Patientendaten', }, legend: { disblay: true, position: 'right', labels: { fontColor: '#000' } } } }); </script> </body> </html> So as you can see I am TRYING to pass the data for the template in my views.py … -
Trying to out the data but doesn't show up in the template
I am trying to pass the data to the template but doesn't show up ` <table id="table_id"> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> {% for key, value in users.items %} <tr> <td>{{ key }}{{ value }}</td> </tr> {% endfor %} </tbody> </table> </div>` and this is the view `@login_required def event_detail(request, pk): messages = Chat.objects.filter(room=pk) users = Chat.objects.filter(room=pk).values('user__username').distinct() event_users = Event.objects.filter(id=pk) response_data = { 'messages': messages, 'pk': pk, 'users': users } return render(request, 'chat/event_detail.html', response_data)` I my table it shows no data to output -
Django (REST Framework) to JSON. How to fetch the Data via my API in JavaScript?
I am still in the process of learning Django. My Main Question is how to fetch the Data with JavaScript from my API? My goal is to visualize my Model Data as charts or graphs. For the visualizing part I would like to choose Charts.js. So far I am able to display a chart in my template with a given default data. Now I would like to send my model data to my template and to integrate it in chart.js . Chart.js needs a JSON Format, as I understand. So I set up a API with the Django REST Framework and I got an Output. Folder Structure visual # -- my project ├── cars # -- API │ ├── templates │ │ └── cars │ │ └── cars_home.html │ ├── <...> │ ├── urls.py │ ├── serializers.py │ └── views.py ├── charts ├── static │ ├── css │ ├── img │ └── js │ ├── chart_2.js │ └── <...> ├── templates │ ├── base │ │ └── base.html │ └── includes ├── visual │ ├── settings.py │ ├── urls.py │ └── views.py *db.sqlite3 └── manage.py ../ cars / urls.py from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from cars import … -
Dokuwiki APIs not accessible
I installed dokuwiki on my machine successfully. Setup initial settings, enable xml-rpc to call dokuwiki APIs by third party via xml-rpc. Still I am getting forbidden error message on calling any API. My python code: def get_namespaces(request): try: with dokuwiki.DokuWiki("dokuwiki url", "username","password") as wiki: pages = wiki.send('dokuwiki.getPagelist') print(pages) except Exception as inst: LOGGER.exception('Exception "%s" occurred while fetching tree for dokuwiki acls' % inst) And my log file: Traceback (most recent call last): File "file/path/", line 52, in get_namespaces pages = wiki.send('dokuwiki.getPagelist') File "/opt/myvirtual/iampenv/lib/python3.5/site-packages/dokuwiki.py", line 116, in send print(method(*args)) File "/usr/lib/python3.5/xmlrpc/client.py", line 1092, in __call__ return self.__send(self.__name, args) File "/usr/lib/python3.5/xmlrpc/client.py", line 1432, in __request verbose=self.__verbose File "/usr/lib/python3.5/xmlrpc/client.py", line 1134, in request return self.single_request(host, handler, request_body, verbose) File "/usr/lib/python3.5/xmlrpc/client.py", line 1167, in single_request dict(resp.getheaders()) xmlrpc.client.ProtocolError: <ProtocolError for username:password@localhost:81/lib/exe/xmlrpc.php: 403 Forbidden> Does anyone know what I am missing. What authentication needs to be set? -
how to iterate on two subclass models with same for loop?
i want to create a photo sharing website, but i don not how to iterate over this code "all_post = Images.objects.all().order_by('-created').select_subclasses()" ? my models.py class Images(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, null=True, blank=True) objects = InheritanceManager() class Postimg(Images): user_img= models.ImageField(upload_to='images/%Y/%m/%d', null=True, blank=True) class Postsms(Images): user_message = models.CharField(max_length=500,blank=True) views.py @login_required def home(request): all_post = Images.objects.all().order_by('-created').select_subclasses() return render(request, 'copybook/home.html',{ 'all_post':all_post}) home.html {% for foo in all_post %} <hr> <br> SMS by: <p>{{ foo.user}} __ {{ foo.created }}</p> <br> <h2>{{ foo.user_message }}</h2> <hr> <br> IMAGE by: <p>{{ foo.user}} __ {{ foo.created }}</p> <br> <img src="{{ foo.user_img.url }}"width="250"> {% endfor %} how i iterate in home.html -
Not able to resolve AttributeError: 'module' object has no attribute 'SSL_ST_INIT' while installing django dependencies
Using MacOS Sierra 10.12.6 Installing Django project dependencies from requirement.txt file sudo pip install --user -r requirement.txt I have looked over internet for the similar issues but none of them helped. I even have tried uninstalling pyOpenSSL using command: pip uninstall pyOpenSSL even this command is giving an error: Traceback (most recent call last): File "/Users/RitZz/Desktop/work/bin/pip", line 11, in <module> load_entry_point('pip==19.1', 'console_scripts', 'pip')() File "/Users/RitZz/Desktop/work/lib/python2.7/site-packages/pkg_resources/__init__.py", line 489, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/Users/RitZz/Desktop/work/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2843, in load_entry_point return ep.load() File "/Users/RitZz/Desktop/work/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2434, in load return self.resolve() File "/Users/RitZz/Desktop/work/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2440, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "/Users/RitZz/Desktop/work/lib/python2.7/site-packages/pip/_internal/__init__.py", line 40, in <module> from pip._internal.cli.autocompletion import autocomplete File "/Users/RitZz/Desktop/work/lib/python2.7/site-packages/pip/_internal/cli/autocompletion.py", line 8, in <module> from pip._internal.cli.main_parser import create_main_parser File "/Users/RitZz/Desktop/work/lib/python2.7/site-packages/pip/_internal/cli/main_parser.py", line 12, in <module> from pip._internal.commands import ( File "/Users/RitZz/Desktop/work/lib/python2.7/site-packages/pip/_internal/commands/__init__.py", line 6, in <module> from pip._internal.commands.completion import CompletionCommand File "/Users/RitZz/Desktop/work/lib/python2.7/site-packages/pip/_internal/commands/completion.py", line 6, in <module> from pip._internal.cli.base_command import Command File "/Users/RitZz/Desktop/work/lib/python2.7/site-packages/pip/_internal/cli/base_command.py", line 20, in <module> from pip._internal.download import PipSession File "/Users/RitZz/Desktop/work/lib/python2.7/site-packages/pip/_internal/download.py", line 15, in <module> from pip._vendor import requests, six, urllib3 File "/Users/RitZz/Desktop/work/lib/python2.7/site-packages/pip/_vendor/requests/__init__.py", line 97, in <module> from pip._vendor.urllib3.contrib import pyopenssl File "/Users/RitZz/Desktop/work/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.py", line 46, in <module> import OpenSSL.SSL File "/Users/RitZz/Desktop/work/lib/python2.7/site-packages/OpenSSL/__init__.py", line 8, in <module> from OpenSSL import rand, crypto, … -
Unable to start pipenv with python 3.7
I am following the examples in DjangoForBeginners by William S. Vincent and attempted to start a virtual environment in python 3.7 for django==2.7 but it seems that only Python 3.6 is required for starting the pipenv. Jamess-MacBook-Pro:ch04 otomes$ pipenv install django==2.1 Warning: Your Pipfile requires python_version 3.6, but you are using None (/Users/otomes/.local/share/v/o/bin/python). $ pipenv --rm and rebuilding the virtual environment may resolve the issue. $ pipenv check will surely fail. Installing django==2.1… Adding django to Pipfile's [packages]… ✔ Installation Succeeded Installing dependencies from Pipfile.lock (e222e2)… An error occurred while installing django==2.1 --hash=sha256:7f246078d5a546f63c28fc03ce71f4d7a23677ce42109219c24c9ffb28416137 --hash=sha256:ea50d85709708621d956187c6b61d9f9ce155007b496dd914fdb35db8d790aec! Will try again. An error occurred while installing pytz==2019.1 --hash=sha256:303879e36b721603cc54604edcac9d20401bdbe31e1e4fdee5b9f98d5d31dfda --hash=sha256:d747dd3d23d77ef44c6a3526e274af6efeb0a6f1afd5a69ba4d5be4098c8e141! Will try again. 🐍 ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 2/2 — 00:00:00 Installing initially failed dependencies… ☤ ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 2/2 — 00:00:00 pipenv.exceptions.InstallError: File "/usr/local/lib/python3.7/site-packages/pipenv/cli/command.py", line 254, in install pipenv.exceptions.InstallError: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 1992, in do_install pipenv.exceptions.InstallError: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 1253, in do_init pipenv.exceptions.InstallError: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 862, in do_install_dependencies pipenv.exceptions.InstallError: _cleanup_procs(procs, False, failed_deps_queue, retry=False) pipenv.exceptions.InstallError: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 681, in _cleanup_procs pipenv.exceptions.InstallError: raise exceptions.InstallError(c.dep.name, extra=err_lines) pipenv.exceptions.InstallError: ['dyld: Library not loaded: @executable_path/../.Python', ' Referenced from: /Users/otomes/.local/share/virtualenvs/otomes-cBliFOGJ/bin/python3.6', ' Reason: image not found'] ERROR: ERROR: Package installation failed... I just need to know how I can reinstall my pipenv. -
Run Django on remote server, how can I view in my browser
I have tried to run my django project on a remote server and it runs perfectly fine. Just wondering how can I view it in my local browser. I have tried python manage.py runserver 0.0.0.0:8000 and then access the website through the.remote.server:8000 but it doesn't work and keeps saying 'This site can’t be reached'