Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django post_save: how to insert and update all related record from another table
class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE, null=True,blank=True) @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, *args, **kwargs): teachers = SubjectSectionTeacher.objects.filter(Sections=instance.Section, Education_Levels=instance.Education_Levels, Courses=instance.Courses) for each in teachers: if created or teachers.exists(): StudentsEnrolledSubject.objects.update_or_create( Students_Enrollment_Records= instance, defaults={'Subject_Section_Teacher':each} ) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, class SubjectSectionTeacher(models.Model): Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Employee_Users = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True) almost a week i tried to solve this problem but till now i didnt solve it, my problem is when i insert data(picture 1), it will get the related record from picture 2 but in my case only 1 save related record in picture 3, picture 1 picture 2 picture 3 -
How to execute a python script after clicking a button in HTML (Django)?
I want to execute a python script after a user (registered user) clicks on a button in HTML using Django. How can this be achieved? Can someone give me a hint on how to create the logic in the views.py along with the Html code in the template? Before executing the button code, I want to check whether if the user.id exists in the model. If not, the button doesn't do anything. Currently, this is basic understanding: views.py: def button(request): #python script return render(request, 'users/home.html') home.html: {% if user.id %} <button class="btn btn-outline-info" onclick="location.href={% url 'button' %}"> Manual Index </button> FYI, I am new to Django and am still exploring its potential. -
How to solve the access token error for Microsoft graph API?
I am trying to get mails from Outlook from Microsoft graph API by following https://docs.microsoft.com/en-us/outlook/rest/python-tutorial But on Django I am having following error: python3.6 manage.py runserver Performing system checks... System check identified no issues (0 silenced). November 07, 2019 - 05:06:46 Django version 2.0.2, using settings 'python_demo.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: /tutorial/gettoken/ Traceback (most recent call last): File "/usr/local/lib/python3.6/dist- packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist- packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist- packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/komal/python_demo/tutorial/views.py", line 22, in gettoken access_token = token['access_token'] KeyError: 'access_token' [07/Nov/2019 05:06:54] "GET /tutorial/gettoken/?code=M596caf0d- 2dae-0da1-e124-a6ab92ffded9 HTTP/1.1" 500 71248 How to solve it? -
Django: Problem with Adding Clickable Link in the Second Template
I am a beginner in Django. I am building a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models. I have already created models and views. I have also managed to add clickable link in the first template (brandlist.html). In the first template, when you click on the brand name, like Samsung, you will be taken to the page of the phone model, like Galaxy S10. Here is the screenshot of the first template: When you click the link, you will be taken to the second template (phonemodel.html). But now, I am facing an issue. There is no clickable link on the phone model ("Galaxy S10") that will direct you to details.html. Here is the screenshot. Here are the codes of models.py inside the "PhoneReview" folder: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Brand(models.Model): brand_name = models.CharField(max_length=100) origin = models.CharField(max_length=100) manufacturing_since = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.brand_name def save(self, *args, **kwargs): self.slug = slugify(self.brand_name) super().save(*args, **kwargs) class PhoneModel(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) model_name = models.CharField(max_length=100) launch_date = models.CharField(max_length=100) platform = models.CharField(max_length=100) def __str__(self): return … -
How do I link models together using foreign key with Django?
I am trying to update three models in django with a task function and link them together using a foreign key. Event, Market & Runner I would like to be able to query the data in my views and display the data. A single event has multiple markets and in each market there's multiple runners. I'm getting an error when I try to use foreign keys to link the three models together. django.db.utils.ProgrammingError: relation "apimb_event" does not exist STATEMENT: SELECT "apimb_event"."event_id", "apimb_event"."event_name", "apimb_event"."start_time", "apimb_event"."status" FROM "apimb_event" ORDER BY "apimb_event"."event_id" DESC LIMIT 21 I don't think I'm using foreign key's correctly. Each model has a id as a primary key. I can update and create this data fine without using foreign keys but, How can I update the model and then query the data to show as below? Event Market Runner event_name_1 market_name_1 runner_name_1 runner_name_2 runner_name_3 event_name_1 market_name_2 runner_name_1 runner_name_2 runner_name_3 runner_name_4 task_function @shared_task(bind=True) def get_events(self): api = get_client() events = api.market_data.get_events(sport_ids=[9],states=MarketStates.All, per_page=200, offset=0, include_event_participants=Boolean.T, category_ids=None, price_depth=3, side=Side.All, session=None) for event in events: event_name = event["name"] event_id = event['id'] start_time = event['start'] status = event["status"] ev, created = Event.objects.update_or_create(event_id=event_id) ev.event_name = event_name ev.start_time = start_time ev.status = status ev.save() markets = … -
Issue while returning the errors list
Below is code in views.py file. class login(View): def get(self, request): return render(request, 'login.html') def post(self, request): form = LoginForm(request.POST) if form.is_valid(): username = request.POST.get('username') password = request.POST.get('password') return HttpResponse("ok") else: form = LoginForm() return HttpResponse(form) Below code is in template file. <form method="post" action="{% url 'authapp:login' %}"> {% csrf_token %} <input type="text" name="username" class="form-control"> <input type="password" name="password" class="form-control"> <button type="submit" class="btn btn-primary"> Login </button> </form> below code is in forms.py file from django import forms class LoginForm(forms.Form): username = forms.CharField(max_length = 50, required = True), password = forms.CharField(max_length = 50, required = True) Issue Details When i submit the form with both username and password empty, it returns just a textfield of password. I was expecting a list of errors for required username and password. As both are required in forms file. Can you please suggest something? -
Django Middleware - 'AnonymousUser' object is not iterable
Related question for context/code: My Django Middleware Isn't Working The Way It Should So I just got help and got my other question related to this one answered but after I added the code I found out now every time a user who isn't signed in views the site they see the error below so any help with be appreciated. Thanks Error: 'AnonymousUser' object is not iterable middleware.py: from .models import UserBanning from django.shortcuts import render, redirect class BanManagement(): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if(UserBanning.objects.filter(ban=True, user=request.user)): context = { 'banned': banned[0], } return render(request, "account/banned.html", context) else: response = self.get_response(request) return response models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings class UserBanning(models.Model): user = models.ForeignKey(User, verbose_name="Username", help_text="Choose Username", on_delete=models.CASCADE) ban = models.BooleanField(default=True, verbose_name="Ban", help_text="Users Bans") reason = models.CharField(max_length=500, blank=True) class Meta: verbose_name_plural = "User Banning" ordering = ('user',) def __str__(self): return f"{self.user}" -
write way of getting user ip address
I got this code from stack overflow answers. Getting user ip address def get_client_ip(request): x_forwarded_for =request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip= x_forwarded_for.split(",")[0] else: ip=request.META.get('REMOTE_ADDR',None) return ip This works well when i am running my webapp on local environment,but when i launched the website online, it does not get the right ip address allocated to me by ISP. And my ip the code gets keep on changing when ever i reload . What is the correct way to go about solving this problem thank you -
How to use update_or_create on django post_save?
class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE, null=True,blank=True) @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, *args, **kwargs): teachers = SubjectSectionTeacher.objects.filter(Sections=instance.Section, Education_Levels=instance.Education_Levels, Courses=instance.Courses) for each in teachers: if created or teachers.exists(): print("if") StudentsEnrolledSubject.objects.create_or_update( pk=each.id, Students_Enrollment_Records=instance, Subject_Section_Teacher=each ) Inserting data is working perfectly but when I update the existing data it creates another record not update -
unknown field specified error for drop down list in django forms
I am working on a web application. The application consists of a drop down list. I created a new model and migrated the model. But when I try to create a form with django forms.py I get the following error message django.core.exceptions.FieldError: Unknown field(s) (fruits) specified for Fruits models.py class Fruits(models.Model): FRUIT_CHOICE = ( ('apple', 'Apple'), ('mango', 'Mango'), ('banana', 'Banana'), ) firstName = models.CharField(max_length=50) lastName = models.CharField(max_length=50) email = models.EmailField(max_length=100) fruits = models.CharField(max_length=100, choices=FRUIT_CHOICE) def publish(self): self.save() def __str__(self): return self.firstName forms.py from .models import Fruits class Fruits(forms.ModelForm): class Meta: model = Fruits widgets = { 'firstName': forms.TextInput(attrs={'placeholder': 'First Name'}), 'lastName': forms.TextInput(attrs={'placeholder': 'Last Name'}), 'email': forms.TextInput(attrs={'placeholder': 'Email'}), 'fruits': forms.ChoiceField() } fields = ('firstName', 'lastName', 'email', 'fruits') What am i doing wrong? -
Djngo REST API: KeyError at /api/update
i was trying to perform bulk update using django-bulk-update https://github.com/aykut/django-bulk-update But it throws KeyError at /api/update 'id' views class CartUpdatesView(ListBulkCreateUpdateDestroyAPIView): queryset=models.Cart.objects.all() serializer_class=serializers.CartUpdatesSerializer serializers class CartUpdatesSerializer(BulkSerializerMixin,serializers.ModelSerializer): class Meta(object): model = models.Cart fields = '__all__' list_serializer_class=BulkListSerializer models class Cart(models.Model): cart_id=models.AutoField(primary_key=True) product_qty=models.IntegerField() customer_id=models.IntegerField() product_id=models.ForeignKey('Products',db_column='product_id',on_delete=models.CASCADE) Does this happens because of 2 primary keys while joiing tables?. I dont have any idea on bulk update. By searching I figure out official doc provide only very little information on bulk update and everyone refers to use this package. GET HTTP 200 OK Allow: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "cart_id": 1, "product_qty": 4, "customer_id": 1, "product_id": 1 } ] PUT [ { "cart_id": 1, "product_qty": 9, "customer_id": 1, "product_id": 1 } ] Traceback Environment: Request Method: PUT Request URL: http://localhost:8000/api/update Django Version: 2.2.5 Python Version: 3.6.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shoppingcart', 'rest_framework', 'rest_framework.authtoken'] Installed 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'] Traceback: File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, … -
forms module not found inside the child app
I have already checked this answer on stackoverflow but did not get any suggestion in this context. There is root app and then created another app in root. Inside the view.py of child app, I wrote below code. from forms import MyForm I got an ModuleNotFoundError No module named forms Also tried with .forms and with myapp.forms and .myapp.forms But no luck. Can you please suggest? -
how to loop insert data from database to select form with django
so i want to make a dependent select box , but im still beginner and want to try with the old way The point is , the first dropdown is the database name (schema in dbeaver) and the second dropdown is list of table name that the database has html code <div class="form-group"> <label class="control-label col-md-3">Table Name</label> <div class="col-md-4"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> <!-- <li><a href="#"></a></li> --> {% for table_name in obj %} <option>{{ table_name.table_name }} {% endfor %} <!-- <li><a href="#">Dropdown link</a></li> --> </option> </select> </div> </div> </div> </div> <div class="form-group"> <label class="control-label col-md-3">Column Name</label> <div class="col-md-4"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> <!-- <li><a href="#"></a></li> --> *here where i want to put the data after i select the first select above* <!-- <li><a href="#">Dropdown link</a></li> --> </option> </select> </div> </div> </div> </div> Havent put the post and get for the first select dropdown to send the parameter *dont know where views.py #for the first dropdown def list_all_table(request): obj = TableAll.objects.all() context = { 'obj' : obj } return render(request,'define_segment.html',context) #for the second dropdown form after you select the first dropdown def list_all_table2(request): #need to get parameter first but how dsn_tns = cx_Oracle.makedsn('IP', 'PORT', sid) … -
Mock import to test class method
I have a class that is a Django model: from django.db import models class User(models.Model): The class has a few methods unrelated to the DB side (helpers/static methods, etc). However, when I import it, because it calls django.db.models, it also tries to use the Django settings to connect to the DB. I'm not sure how to properly mock this so it's workable but I can write unit tests for the extra methods. -
How could I update mysql database information if my update button is on a modal?
{% for employee in employees %} <div class="modal fade" id="employee.employee_id_{{ employee.employee_id }}" tabindex="-1" role="dialog" style="display: none; overflow: auto;" aria-hidden="true" data-backdrop="static"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" >Employee</h5> <button type="button" class="close" modalid="referral_modal" id="close_referral" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body" style="overflow: auto"> <div class="col-md-15"> <div class="card"> <div class="card-body"> <div class="row"> <div class="col-md-12"> <h4>Your Profile</h4> <hr> </div> </div> <div class="form-group row"> <label for="name" class="col-4 col-form-label">First Name</label> <div class="col-8"> <input id="name" name="name" placeholder="First Name" value="{{ employee.first_name }}" class="form-control here" type="text" readonly> </div> </div> <div class="form-group row"> <label for="lastname" class="col-4 col-form-label">Last Name</label> <div class="col-8"> <input id="lastname" name="lastname" placeholder="Last Name" value="{{ employee.last_name}}" class="form-control here" type="text" readonly> </div> </div> <div class="modal-footer"> <button onclick="" name="submit" type="submit" class="btn btn-primary">Edit</button> <button type="button" class="btn btn-secondary" data-dismiss="modal" onclick="">Cancel</button> </div> Modal Code: Model.py class Employee(models.Model): first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'employee' Views.py (nothing) For now I don't have a view.py for the update button since i don't know how to start on that, asking for recommendation regarding that, I'm still new to Django. Thanks -
DRF: cannot convert URL to instance using HyperlinkedIdentityField
How can I use a HyperlinkedIdentifyField to convert a url to an instance? I have a couple of nested HyperlinkedModelSerializer: class ChildSerializer(HyperlinkedModelSerializer): class Meta: model = Child fields = ('url', 'name') extra_kwargs = { 'name': {'required': False} } class ParentSerializer(HyperlinkedModelSerializer): class Meta: model = Parent fields = ('url', 'child') But this doesn't work: >>> s = ParentSerializer(data={'child': {'url': '<valid url>'}}) >>> s.is_valid() True >>> s.validated_data() OrderedDict([('child', OrderedDict())]) For whatever reason, to_instance_value from HyperlinkedModelSerializer doesn't retrieve the actual object. So the obvious solution is to override this, but I cannot work out how to get the HyperlinkedIdentityField for ChildSerializer to return an internal value. I have a kludge that is working for now: class ChildSerializer(HyperlinkedModelSerializer): ... def to_internal_value(self, data): pk = parse_pk_from_url(data['url']) return self.Meta.model.objects.filter(pk=pk).get() But I feel like there must be a mechanism for retrieving objects from valid URLs that I'm missing here... -
Crystal Report with Django Python
Now I am working with Django Rest Framework and my requirement is to generate the report by using crystal reports or other tools but first will use crystal report. My project used DRF as backend and React as frontend. I think React cant do like that kind of job so I am trying to do generate report as pdf from DRF and I will respond to react. Now I am stuck how can I connect to crystal report from DRF? Please Help. -
django post_save: create_or_update not working
@receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, *args, **kwargs): teachers = SubjectSectionTeacher.objects.filter(Sections=instance.Section,Education_Levels=instance.Education_Levels,Courses=instance.Courses) for each in teachers: if created and teachers.exists(): StudentsEnrolledSubject.objects.update_or_create( pk=each.id, Students_Enrollment_Records=instance, Subject_Section_Teacher=each ) else: StudentsEnrolledSubject.objects.get( Students_Enrollment_Records=instance, Subject_Section_Teacher=each ) Inserting data is working perfectly but when I update the existing data it insert another data but not update, the update_or_create is not working -
Django: Cannot Add Clickable Link in the Template
I am a beginner in Django. I am building a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models. I have already created models for: Brand – details on brand, such as, name, origin, manufacturing since, etc Model – details on model, such as, model name, launch date, platform, etc Review – review article on the mobile phone and date published, etc Many-to-many relationship between Review and Model. I also have created views for the following: a. An index page that display all Brands available for mobile phone in the database b. A phone model page that display model when a brand is selected. c. A detail page when a model is selected that contain reviews and newslink Now, I am facing a problem. I cannot put any clickable link that will redirect the phone brands, like Apple and Samsung, of brandlist.html web page, to their respective phone model page (phonemodel.html). Here is the screenshot: Here are the codes of models.py inside "PhoneReview" folder. from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Brand(models.Model): brand_name = models.CharField(max_length=100) origin … -
Testing That File Was Uploaded in Django
I am writing some unit-tests for an app. One of the features of this app is that it allows the user to upload videos to the server (or S3, depending on the configuration). The difficulty I am having is coming up with a meaningful unit-test for this. So, the question is two-fold. First, what is a solid way to test this functionality? Second, the following test fails because videofile entry in the dictionary is a string. Having done prints, I can see that in a real upload it is actually of type <class django.db.models.fields.files.FieldFile>. How should one go about creating this in a test to make the types similar to the real upload via the browser? class VideoFormTest(TestCase): def test_upload_form_valid(self): form = VideoForm(data={'title':"Test Video Title", 'videofile':"videos/navigator.mp4"}) self.assertTrue(form.is_valid()) -
How to deploy django project on docker?
I am deploying the Django project on Docker. I have no any knowledge about Django and dokcer, so please help me with example. -
Issue while trying to convert into class
This was my original code from django.shortcuts import render def login(request): if(request.method == "POST"): return render(request, 'login1.html') else: return render(request, 'login.html') Converted above code to class below. class login(View): def loginForm(self, request): return render(request, 'login.html') def authenticate(self, request): return HttpResponse("Inside Post") New Url.py file from django.urls import path from .import views app_name = 'authapp' urlpatterns = [ path('', views.login.loginForm(), name='loginForm'), path('', views.login.authenticate(), name='authenticate') ] I got an error loginForm() is missing 2 required positional arguments: self and request. Can you please suggest something? I was actually trying to convert the code into class. Everything was fine without class. -
Django filter listview by url parameter not working
I'm trying to filter the result of a ListView through a URL parameter but it is not working. What the webapp does is that in a session, many pictures can be saved, so the idea is through a search bar you can filter the sessions and see its pictures. I have tried using in the ListView which uses two models that are linked through a foreign key, the postgresql search lookup but it does not filter views.py class SessionPictures(generic.ListView): model = PostSession template_name = 'photoadmin/gallery.html' def get_context_data(self, **kwargs): context = super(SessionPictures, self).get_context_data(**kwargs) context['picture'] = Images.objects.filter( name__session_name__search='search') return context urls.py urlpatterns = [ path('', views.index, name='index'), path('upload', views.UploadView.as_view(), name='upload'), path('gallery/<search>/', views.SessionPictures.as_view(), name='gallery') ] models.py class PostSession(models.Model): session_name = models.CharField(max_length=25) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.session_name) class Images(models.Model): name = models.ForeignKey( PostSession, related_name='images', on_delete=models.CASCADE, null=True, blank=True) picture = models.ImageField(upload_to='pictures') The idea is to filter the sessions. I don't get an error, it just don´t filter. -
How To Fix Django Heroku Requirements Deploy Failure
I'm trying to deploy a staging version of my Django app to Heroku, and I'm receiving an error. The reason I mention that it's a staging app is that my production app is running fine, but I think maybe some packages updated since I set it up? The error is referencing python-http-client==3.1.0 which I don't understand, since my requirements.txt has python-http-client==3.2.1 I think I used Pipenv originally a long time ago but ended up switching back to not using it, and to be honest I'm a bit confused about it. I don't currently have a pipfile or pipfile.lock, yet Heroku says Installing dependencies from Pipfile.lock during deployment, so I'm at a loss. Here is the error: remote: -----> Installing python-3.6.5 remote: -----> Installing pip remote: -----> Installing dependencies with Pipenv 2018.5.18… remote: Installing dependencies from Pipfile.lock (d4a1e0)… remote: An error occurred while installing python-http-client==3.1.0! Will try again. remote: Installing initially–failed dependencies… remote: Collecting python-http-client==3.1.0 remote: Using cached https://files.pythonhosted.org/packages/5c/5c/9e0cde562757bdb385a3644235e7c4da6f76c8a43d573eb76384ef461d40/python_http_client-3.1.0-py3-none-any.whl remote: remote: THESE PACKAGES DO NOT MATCH THE HASHES FROM Pipfile.lock!. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them. remote: python-http-client==3.1.0 from https://files.pythonhosted.org/packages/5c/5c/9e0cde562757bdb385a3644235e7c4da6f76c8a43d573eb76384ef461d40/python_http_client-3.1.0-py3-none-any.whl#sha256=84267d8dcb7bcdf4c5cef321a533cc584c5b52159d4a4d3d4139bfed347b8006 (from -r /tmp/pipenv-6k8jlqu1-requirements/pipenv-73gxws2n-requirement.txt (line … -
How to block an ip address in httpd.conf [duplicate]
This question already has an answer here: Apache block an ip address from accessing the website 2 answers Blocking multiple ip ranges using mod access in htaccess 1 answer My website was hit by a few ip's continuously sending bad requests with some garbled parameters causing a large amount of error output in log file. At a peak the attack could reach 6000-7000 hits an hour. I am trying to block these ip's in httpd.config file. Here is what I have. But these ip's are still coming through. Note: I also loaded authz_host_module and tried to use directive with no success. ServerRoot "/home/myapp/apache2" LoadModule authz_host_module modules/mod_authz_host.so LoadModule authz_core_module modules/mod_authz_core.so LoadModule dir_module modules/mod_dir.so LoadModule env_module modules/mod_env.so LoadModule log_config_module modules/mod_log_config.so LoadModule mime_module modules/mod_mime.so LoadModule rewrite_module modules/mod_rewrite.so LoadModule setenvif_module modules/mod_setenvif.so LoadModule wsgi_module modules/mod_wsgi.so LoadModule unixd_module modules/mod_unixd.so LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined CustomLog /home/myapp/logs/access_orchidroots.log combined ErrorLog /home/myall/logs/error_orchidroots.log Listen 28277 KeepAlive Off SetEnvIf X-Forwarded-SSL on HTTPS=1 ServerLimit 1 StartServers 1 MaxRequestWorkers 5 MinSpareThreads 1 MaxSpareThreads 3 ThreadsPerChild 5 SetEnvIf X-Forwarded-For 185\.166\.240\.100 blocked SetEnvIf X-Forwarded-For 46\.229\.168 blocked SetEnvIf X-Forwarded-For 176\.214\.210\.197 blocked SetEnvIf X-Forwarded-For 91\.102\.75\.95 blocked SetEnvIf X-Forwarded-For 91\.242\.162\.7 blocked WSGIDaemonProcess orchidroots processes=2 threads=12 python-path=/home/myapp:/home/myapp/myproject:/home/myapp/lib/python3.7 WSGIProcessGroup myapp WSGIRestrictEmbedded On WSGILazyInitialization On …