Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why am I getting a CSRF token missing or incorrect error?
why am I getting a CSRF token missing or incorrect error? I did put the {% csrf_token %} in my html, and the rest of my pages works well, only the delete not working. I am trying to delete a user from my database when the admin click on the delete button. allstaff.html {% extends "home.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, th { border-left:solid black 1px; border-top:solid black 1px; } th { border-top: none; } td:first-child, th:first-child { border-left: none; } </style> <div style="padding-left:16px"> <br> <div class="form-block"> <table> <tr> <th>Staff Name</th> <th>Staff Username</th> <th>Email</th> <th>Date Joined</th> <th>Action</th> </tr> {% for user in allusername %} {% csrf_token %} <tr> <td>{{user.first_name}} {{user.last_name}}</td> <td>{{user.username}}</td> <td>{{user.email}}</td> <td>{{user.date_joined}}</td> <td><a class="btn btn-sm btn-info" href="{}">Update</a></td> <td> <form action="{% url 'delete' user.id %}" method="post"> <button type="submit" class="btn btn-sm btn-danger">Delete</button> </form> </td> </tr> {% endfor %} </table> <br> <h6>*Note: You are 8 hours ahead of the server time.</h6> </div> </div> {% endblock %} urls.py urlpatterns = [ #path('', views.index, name='index'), #path('login/', views.login_view, name='login_view'), path('register/', views.register, name='register'), path('adminpage/', views.admin, name='adminpage'), path('customer/', views.customer, name='customer'), path('logistic/', views.logistic, name='logistic'), path('forget/', views.forget, name='forget'), path('newblock/', views.newblock, name='newblock'), path('quote/', views.quote, name='quote'), path('profile/', views.profile, name='profile'), path('adminprofile/', … -
IntegrityError, NOT NULL constraint failed: contest_contestant.contest_id while updating record
I Have two models Contest and Contestant, users can start a contest, and other users can register as a contestant under any contest… models.py class Contest(models.Model): contest_title = models.CharField(max_length=30) contest_post = models.CharField(max_length=100) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Contestant(models.Model): contest = models.ForeignKey(Contest, on_delete=models.CASCADE, related_name='participating_contest') contestant_name = models.CharField(max_length=10, blank=True, null=True) votes = models.IntegerField(default=0) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) Fans of any contestant can cast an unlimited amount of vote for their favourite contestant, anytime a fan votes i want to increment the Contestant.votes with the amount of votes being casted, i have tried using FBV but it is too complicated for my level of django, i am now using CBV, but i am getting an IntegrityError saying IntegrityError at /contests/contestant/2/ NOT NULL constraint failed: contest_contestant.contest_id this error doesn’t make sense to me because contest_id has already being assigned to contestant upon creation, and i can even confirm it from the database view.py class ContestantCreateView(CreateView): model = Contestant fields = ['contestant_name'] def form_valid(self, form): form.instance.contest_id = self.kwargs.get('pk') return super().form_valid(form) the voting logic is in side contestant detailView, which is being triggered by a POST request from a form views.py class ContestantDetail(DetailView, FormMixin): model = Contestant context_object_name = 'contestants' template_name = … -
django-rest-framework ignores fields from model mixin
I have the following configuration of django models with base classes and a mixin for additional fields, but django-rest-framework is ignoring the fields from the mixin class. Models from django.db import models class Base(models.Model): a = CharField() class Meta: abstract = True class Mixin(object): b = CharField() class Concrete(Base, Mixin): c = CharField() class Meta(Base.Meta): abstract = False Serializers from rest_framework import serializers class BaseSerializer(serializers.Serializer): class Meta: fields = ('a',) abstract = True class ConcreteSerializer(BaseSerializer): class Meta(BaseSerializer.Meta): model = Concrete fields = ('b', 'c',) View sets from rest_framework import viewsets class BaseViewSet(viewsets.ModelViewSet): # Some common @actions here. class Meta: abstract = True class ConcreteViewSet(BaseViewSet): serializer_class = ConcreteSerializer class Meta(EquipmentItemEditProposalViewSet.Meta): abstract = False URLS from rest_framework import routers router = routers.DefaultRouter() router.register(r'concrete', ConcreteViewSet, basename='concrete') However, when I browese to http://localhost/api/concrete/ I get the django-rest-framework form with the a and c fields, but not the b field from the mixin. NOTE: if I make the Mixin class inherig from django.db.models.Model instead of object, then I do get the field, but I that won't work because applying a django migration results in a diamond inheritance problem: TypeError: Cannot create a consistent method resolution order (MRO) for bases Model, Mixin Is there a solution … -
How to set for image in VersatileImageField
I am using VersatileImageField for my image field in Django models. I want to set a default image like we do normally in an ImageField. I have tried using default='' in VersatileImageField but it doesn't work. Following is my models.py from django.db import models from django.contrib.auth.models import User from versatileimagefield.fields import VersatileImageField, PPOIField class Image(models.Model): image = VersatileImageField( 'Image', upload_to='images/', default='default.jpg', ppoi_field='image_ppoi' ) image_ppoi = PPOIField() class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Post(models.Model): class PostObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') options = ( ('published', 'Published'), ('draft', 'Draft') ) category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1) title = models.CharField(max_length=100) excerpt = models.TextField(null=True) content = models.TextField() published = models.DateField(auto_now_add=True, editable=False) modified_on = models.DateField(auto_now_add=True) image = models.ManyToManyField(Image, related_name='products') author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blog_posts', default=1) status = models.CharField( max_length=10, choices=options, default='published') objects = models.Manager() postobjects = PostObjects() class Meta: ordering = ('-published',) def __str__(self): return self.title -
Return nested/related models with manyToMany relationship through model
I have a ManyToMany relationship between Recipe and Product. If I request Recipes, I am able to query also the relating products, but when I request Product, there is no related model data. I think this is because the relationship is defined on the Recipe model. How can I query the Recipes related to Product (with the through model info!)? models.py class Recipe(models.Model): ... products_input = models.ManyToManyField(Product, through='RecipeInput', related_name='products_input') ... class Product(models.Model): ... class RecipeInput(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) amount = models.IntegerField() ... serializers.py class RecipeInputSerializer(serializers.HyperlinkedModelSerializer): product_key = serializers.ReadOnlyField(source='product.key') product_name = serializers.ReadOnlyField(source='product.name') class Meta: model = RecipeInput fields = ("product_name", 'amount', 'product_key', ) class RecipeSerializer(serializers.ModelSerializer): products_in = RecipeInputSerializer(source='recipeinput_set', many=True) class Meta: model = Recipe fields = "__all__" depth = 3 class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = "__all__" depth = 3 -
I have this error delete() missing 1 required positional argument: 'id' when I click on the delete button
when I click on the delete button, I am supposed to make it delete from my database, but instead I got this error: delete() missing 1 required positional argument: 'id' as shown in the picture below: urls.py urlpatterns = [ path('', views.login_user, name='login'), path('home/', views.home, name='home'), path('allstaff/', views.allstaff, name='allstaff'), #path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"), path('delete', views.delete, name='delete'), path('logout/', views.logout_view, name='logout'), path('register/', views.register_view, name='register'), path('edit-register/', views.edit_register_view, name='edit_register'), ] views.py def delete(request, id): context = {} user = get_object_or_404(User, id=id) if request.method == "POST": user.delete(id) return HttpResponseRedirect("/home") return render(request, 'delete.html', context) allstaff.py {% extends "home.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, th { border-left:solid black 1px; border-top:solid black 1px; } th { border-top: none; } td:first-child, th:first-child { border-left: none; } </style> <div style="padding-left:16px"> <br> <div class="form-block"> <table> <tr> <th>Staff Name</th> <th>Staff Username</th> <th>Email</th> <th>Date Joined</th> <th>Action</th> </tr> {% for user in allusername %} <tr> <td>{{user.first_name}} {{user.last_name}}</td><td>{{user.username}}</td><td>{{user.email}}</td><td>{{user.date_joined}}</td><td><a class="btn btn-sm btn-info" href="{}">Update</a></td><td><a class="btn btn-sm btn-danger" href="/delete">Delete</a></td> </tr> {% endfor %} </table> <br> </div> </div> {% endblock %} What did I miss out? How do I get it to work so that when I click on the delete button, it will auto delete from my database? -
Disabling an duplicate database entries || Django
I currently have a settings form that enters their entries into the Django SQLite database. I obviously don't want the user to enter 2 settings with the same name. I have tried to use a for loop to check if the data exist, but just can't get it right. Here is my current code for this form: Views.py: def newSetting(request): form = SettingsForm() if request.method == 'POST': form = SettingsForm(request.POST) if form.is_valid(): form.save() return render(request , 'main/newSetting.html' , {'form':form}) newSetting.html: {% extends "main/base.html"%} <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous"> <style > .row_container{ line-height: 500%; } </style> {% block content %} <form class="form-group mt-4" action="" method="post"> {% csrf_token %} {{ form.Complex }} <br> <br> <div class="row_container" name='TRB-YTD'> <div class="row mb-.1"> <div class="col" style="left-align"> {{ form.Trial_balance_Year_to_date }} </div> <div class="col-11"> <p> Trial balance YTD</p> </div> </div> </div> <div class="row_container" name="TRB-MONTH"> <div class="row "> <div class="col" style="left-align"> {{ form.Trial_balance_Monthly }} </div> <div class="col-11"> <p> Trial balance Monthly</p> </div> </div> </div> <div class="row_container" name="IS-YTD"> <div class="row "> <div class="col" style="left-align"> {{ form.Income_Statement_Year_to_date }} </div> <div class="col-11"> <p> Income Statement YTD</p> </div> </div> </div> <div class="row_container" name="IS-MONTHLY"> <div class="row "> <div class="col" style="left-align"> {{ form.Income_Statement_Monthly }} </div> <div class="col-11"> <p> Income Statement Monthly</p> </div> </div> </div> … -
Can Django select_for_update be used to acquire a read lock?
I'm working on a project similar to ecommerce in which I have models that represent a product with a certain amount in the storage, and users can buy some quantity of the product as long as it doesn't exceed the stored amount. I want to avoid a race condition taking place when the server receives multiple requests to buy the same product. class Product(models.Model): amount_in_storage = models.PositiveIntegerField() # for design reasons, this amount is unchangeable, it must be only evaluated once during initialization like constants in C++ @property def amount_available_for_purchase(self): return self.amount_in_storage - Purchase.objects.filter(product=self.id).aggregate(models.Sum('amount'))["sum__amount"] class Purchase(models.Model): product = models.ForeignKey(Product, ...) amount = models.PositiveIntegerField() payment_method = ... Let's assume that this is the block of code that's responsible for creating a purchase. @atomic_transaction def func(product_id, amount_to_purchase): product = Product.objects.get(...) if product.amount_available_for_purchase > amount_to_purchase: # do payment related stuff Purchase.objects.create(product=product, amount=amount_to_purchase) # do more stuff I would like to restrict concurrent access to this block of code, Ideally I would like to obtain a read lock access at the if condition, so that if multiple threads try to see if the amount available is greater than the amount to purchase, one of the threads will have to wait until the transaction is … -
Django Running Slow while working with Mediafiles and Pytesseract
I am working on Django where I am preprocessing some data and images, having pytesseract, opencv and some other libraries. For some reason sometimes after uploading images for extracting data. The program loads up quickly but sometimes it's taking way too long and I have to manually restart the server. After restarting the server, module loads quickly again. I am unsure if it's because of pytesseract or because of the Media files. One of the part of the code: adhar.py: from django.conf import settings import pytesseract import cv2 import re import cv2 import ftfy from PIL import Image from scipy.ndimage import rotate import numpy as np face_classifier = cv2.CascadeClassifier("/home/arijitsen/Downloads/haarcascade_frontalface_default.xml") def adhar(filename): """ This function will handle the core OCR processing of images. """ i = cv2.imread(filename) newdata=pytesseract.image_to_osd(i) angle = re.search('(?<=Rotate: )\d+', newdata).group(0) angle = int(angle) i = Image.open(filename) if angle != 0: #with Image.open("ro2.jpg") as i: rot_angle = 360 - angle i = i.rotate(rot_angle, expand="True") i.save(filename) i = cv2.imread(filename) # Convert to gray i = cv2.cvtColor(i, cv2.COLOR_BGR2GRAY) # Apply dilation and erosion to remove some noise kernel = np.ones((1, 1), np.uint8) i = cv2.dilate(i, kernel, iterations=1) i = cv2.erode(i, kernel, iterations=1) text = pytesseract.image_to_string(i) #return text # Arijit Code Added … -
Need to removed url when printing the value of href in django
I am attempting to print the href value but its occuring along with the url HTML <style> a.printable:link:after, a.printable:visited:after { content:" [" attr(href) "] "; } </style> <table> <tr> <td height="40" valign="right" style="width:150px; font-size: 4.2mm; padding:4pt 0pt 0.5pt 0pt; text-align:center; background:#006400;"><a href="{{ request.scheme|safe|escape }}://{{ request.get_host }}/crm/orders/accepting/{{client.id}}/{{invoice.id}}/" class="printable" style="color:#fff; text-decoration:none;">Accept this Order</a></td> </tr> </table> Here what actually i need is Accept this order But i am getting Accept this order[http:http://127.0.0.1:8000/crm/orders/accepting/13/647/] -
Django: 3-level base class and Meta class ignored?
I'm having the following setup in a Django 2 app: class Base1(models.Model): # ... some fields here... class Meta: abstract = True unique_together = [ 'brand', 'name' ] class Base2(Base1): # ... some more fields here... class Meta: abstract = True class Concrete(Base2): pass The Concrete class doesn't seem to have the unique_together requirement that's present in Base1. Is this expected? If it is, how can I make sure that Concrete has the constraint while keeping things DRY? Thanks! -
Filtering data for multiple conditions in DRF
Django newbie here and having a hard time implementing a simple filter operation. I have an Order model which has two fields - order_id and zipcode. The users are going to pass the above two parameters in the request body and I have to return an order that matches the combination. API endpoint: POST https://myapi.com/orders/ { "order_id": "A123", "zipcode": 10001 } My solution: # views.py from rest_framework.response import Response from django.shortcuts import get_object_or_404 from rest_framework.viewsets import ViewSet from ..models import Order from ..serializers import OrderSerializer class OrderViewSet(ViewSet): def create(self, request): queryset = Order.objects.all() order = get_object_or_404( queryset.filter(order_id=request.data["order_id"]).filter( zipcode=request.data["zipcode"] ) ) serializer = OrderSerializer(order) return Response(serializer.data) Questions Is ViewSet the right way to go here or should I use generics? Not sure which one to use when. Is there a better way to apply multiple filters than chaining them like I have done above? -
ImportError: cannot import name 'MealSerializer' from partially initialized module 'delivery_api.main.serializers'
When I insert this line cart = CartSerializer() into my serializer to get detailed information, I get an error ImportError: cannot import name 'MealSerializer' from partially initialized module 'delivery_api.main.serializers' (most likely due to a circular import). What is the reason for this and how to solve it? cart/serializers.py class CartMealSerializer(serializers.ModelSerializer): meal = MealSerializer() class Meta: model = CartMeal fields = ['id', 'meal', 'qty', 'final_price'] class CartSerializer(serializers.ModelSerializer): meals = CartMealSerializer(many=True) owner = CustomerSerializer() class Meta: model = Cart fields = '__all__' main/serializers.py class OrderSerializer(serializers.ModelSerializer): cart = CartSerializer() *<--- This line causes an error* class Meta: model = Order fields = ['first_name', 'last_name', 'cart', 'phone', 'address', 'status', 'created_at'] Please help me solve this problem -
Best Web Framework [closed]
I wanted to ask that which web framework takes the least time and builds the best web apps , django vs mean vs others. -
How to send notifications to users of my website when I add a new article?
I’m creating a news website. I want send notifications to users when I add a new article to it. If anybody know how to do it please help me! nejansenarathne@gmai.com -
How to change cell types from one form to another text field in excel dynamically using python
I wanted to change from cell dropdown to normal text cell based on condition in excel and I am using python and Django as tech stack -
How to change the size of a Django form label
I have the following form: forms.py: from django.forms import ModelForm, HiddenInput, CharField from django.core.exceptions import ValidationError import re from django import forms from cal.models import Event from project.models import Project class EventForm(ModelForm): def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) class Meta: model = Event widgets = { 'event_type': forms.Select( attrs={ 'size': '4', 'style': 'font-size:13px;' } ), } labels = { 'equipments': 'Equipment', 'event_type': 'Type', } fields = '__all__' And in my template.html I render the content of the form like this: {% bootstrap_field event_form.title layout='horizontal' size='small' %} {% bootstrap_field event_form.description layout='horizontal' size='small' %} {% bootstrap_field event_form.event_type layout='horizontal' size='small' %} I would like the label font size to be 13px; Apparently 'style': 'font-size:13px;' works only for the content of the field, not for the label. Is there a way to add styles only to label or label and field (both)? I have been reading the documentation here but it is not clear to me how to change the style, it seems like only classes can be changed...? Any help will be highly appreciated -
how to run multiple postgresql queries in github actions
I'm writing python code test on github actions and i deined workflow. but now, i don't know how to run multiple queries to build DB, user, GRANT etc... . here is my workflow: name: lint_python on: [pull_request, push] jobs: lint_python: runs-on: ubuntu-latest services: postgres: image: postgres:latest env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: postgres POSTGRES_PORT: 5432 ports: - 5432:5432 # needed because the postgres container does not provide a healthcheck options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - name: Install PostgreSQL client run: | apt-get update apt-get install --yes postgresql-client - name: Query database run: psql -h postgres -d postgres_db -U postgres_user -c "SELECT 'CREATE DATABASE redteam_toolkit_db' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'redteam_toolkit_db');" run: psql -h postgres -d postgres_db -U postgres_user -c "CREATE ROLE redteamuser with SUPERUSER CREATEDB LOGIN ENCRYPTED PASSWORD '147r258r';" run: psql -h postgres -d postgres_db -U postgres_user -c "GRANT ALL PRIVILEGES ON DATABASE redteam_toolkit_db TO redteamuser;" run: psql -h postgres -d postgres_db -U postgres_user -c "ALTER DATABASE redteam_toolkit_db OWNER TO redteamuser;" env: PGPASSWORD: postgres # https://www.hacksoft.io/blog/github-actions-in-action-setting-up-django-and-postgres#resources - run: sudo apt-get install libpq-dev - run: pip install --upgrade pip wheel - run: pip install bandit black … -
How can I fetch multiple data from API calls in React js?
I used django as backend and react as frontend. I am able to call the api and show the product details but in my serializer i have related product too. I send related product response from my serializer. I want to show related product after the product details section. How can I call the object?? #this is my serializer class ProductWithRelatedSerializer(ProductSerializer): related = serializers.SerializerMethodField(read_only=True) class Meta: model = Product fields = '__all__' def get_related(self, obj): related = Product.objects.filter( category_id=obj.category_id ).exclude(_id=obj.pk).order_by('?').select_related('user')[:4] ps = ProductSerializer(related, many=True) return ps.data this is my product view @api_view(['GET']) def getProduct(request, pk): product = Product.objects.get(_id=pk) serializer = ProductWithRelatedSerializer(product, many=False) return Response(serializer.data) in my frontend reducer export const productDetailsReducer = (state = { product: {}}, action) => { switch (action.type) { case PRODUCT_DETAILS_REQUEST: return { loading: true, ...state } case PRODUCT_DETAILS_SUCCESS: return { loading: false, product: action.payload } case PRODUCT_DETAILS_FAIL: return { loading: false, error: action.payload } default: return state } } this is my action export const listProductDetails = (id) => async (dispatch) => { try { dispatch({ type: PRODUCT_DETAILS_REQUEST }) const { data } = await axios.get(`/api/products/${id}`) dispatch({ type: PRODUCT_DETAILS_SUCCESS, payload: data }) }catch(error){ dispatch({ type: PRODUCT_DETAILS_FAIL, payload: error.response && error.response.data.detail ? error.response.data.detail : error.message, }) … -
How to run a function in background in django python only when it is called?
I have created an email functionality which will send access token to the user for verification. This process takes little time to execute. So, I want to push this function in background and notify the user with the message "The access token would be mailed to your email id. Please check you email". This is to keep user updated rather than him waiting for the access token notification once the whole task is completed. I don't want to schedule as it is not required here and Django's background_task module won't help I suppose. What could be the way-out? -
How to clear a airflow connection table, it is possible to delete a single connection with conn id
To delete a single connection: airlfow connections delete conn id how to delete the whole connections.? -
How to install Node Packages for an Elastic Beanstalk Python 3.7 Project Running on 64bit Amazon Linux 2?
I am using a Django package named django-pipeline to compress js and css files. When I deploy my project, I run Django's collectstatic command, from .ebextensions folder: 01_django.config: container_commands: ... 07_collectstatic: command: "source /var/app/venv/*/bin/activate && python3 manage.py collectstatic --noinput" The problem is, django-pipeline uses compressor libraries that require Node. I have copied two libraries (cssmin and terser) from my node_modules directory locally to my static directory. static |_vendor |___|.bin |_____|cssmin |_____|cssmin.cmd |_____|terser |_____|terser.cmd Secondly, I have the following setin on the Pipeline to tell the pipeline where the binaries exist: PIPELINE_CONFIG.update({ 'CSSMIN_BINARY': os.path.join(BASE_DIR, "static", "vendor", ".bin", "cssmin"), 'TERSER_BINARY': os.path.join(BASE_DIR, "static", "vendor", ".bin", "terser"), }) The Error 2021-09-14 05:00:58,513 P4080 [INFO] ============================================================ 2021-09-14 05:00:58,513 P4080 [INFO] Command 07_collectstatic 2021-09-14 05:00:59,502 P4080 [INFO] -----------------------Command Output----------------------- 2021-09-14 05:00:59,503 P4080 [INFO] Traceback (most recent call last): 2021-09-14 05:00:59,503 P4080 [INFO] File "manage.py", line 21, in <module> 2021-09-14 05:00:59,503 P4080 [INFO] main() 2021-09-14 05:00:59,503 P4080 [INFO] File "manage.py", line 17, in main 2021-09-14 05:00:59,503 P4080 [INFO] execute_from_command_line(sys.argv) 2021-09-14 05:00:59,503 P4080 [INFO] File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line 2021-09-14 05:00:59,503 P4080 [INFO] utility.execute() 2021-09-14 05:00:59,503 P4080 [INFO] File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/management/__init__.py", line 413, in execute 2021-09-14 05:00:59,503 P4080 [INFO] self.fetch_command(subcommand).run_from_argv(self.argv) 2021-09-14 05:00:59,503 P4080 [INFO] File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/management/base.py", line 354, … -
Legacy Apache 2.2.22 SSL Config with Django & Elasticsearch on Ubuntu 12.04
I have a legacy linux cluster based on Ubuntu 12.04 that hosts a django app on apache 2.2.22 (new system is replacing it, this is being maintained only). I've been asked to secure a website (internal facing only, not public) with some SSL keys that have been provided. I've created a symlink in /etc/apache2/conf.d to the config file below. I've been reviewing various old discussions similar to this setup. I've finally been able to get the apache service to start but the website now gives a 500 internal error on port 443. Any insights and insights are appreciated. This is still a bit new to me. Here's the config file (sorry it's a bit messy as I've been debugging) <VirtualHost *:443> #ServerName www.example.com #ServerAdmin webmaster@localhost #DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SSLEngine On # Set the path to SSL certificate #SSLCertificateFile /etc/ssl/certs/paclahpchn2_ssl_certs/paclahpchn2-chain.pem SSLCertificateFile /etc/ssl/certs/paclahpchn2_ssl_certs/paclahpchn2.crt SSLCertificateKeyFile /etc/ssl/certs/paclahpchn2_ssl_certs/paclahpchn2.key #Include conf-available/serve-cgi-bin.conf ProxyRequests Off ProxyPreserveHost On #Blocks reverse proxy ports /logs /logs_1 /logs_2 and /elasticsearch #match sub strings /logs* and /elasticsearch <Location ~ "/(logs|logs_1|logs_2|elasticsearch)"> Order deny,allow Deny from all AuthType Basic AuthName "Password Required" AuthBasicProvider file AuthUserFile /etc/apache2/elasticsearch-passfile Require valid-user Satisfy any </Location> #<Location /guacamole/> # Order allow,deny # Allow from all # … -
How to duplicate queryset output
When the test row satisfies both conditions 1 and 2, is there a way to print the query set twice? I've searched a lot about solutions, but only the method to distinct() duplicate querysets is shown, and there is no way to print duplicate querysets more than once. condition_1 = Student.objects.filter(Q(register_date__gte=from_date) & Q(register_date__lte=to_date)) condition_2 = Student.objects.filter(Q(eating_date__gte=from_date) & Q(eating_date__lte=to_date)) gap = ETC.objects.filter(Q(id__in=condition_1)) | Q(id__in=gap_condition_2))\ .annotate(total_gap=('create_date', filter=Q(id__in=condition_1.values('id')) + 'create_date', filter=Q(id__in=condition_2.values('id'))) -
Error loading mysqldb module in django after mysqlclient's installed
I suddenly found this issue with myssql + django in my lambdas. I used to have this snippet of code in my init and it used to work fine import pymysql pymysql.install_as_MySQLdb() Now I'm getting this error mysqlclient 1.4.0 or newer is required; you have 0.10.1.. Lambda request id: 9db6c25b-09d5-4721-8942-3a3b655ae9ba ok no problem I changed it to use mysqlclient but now I’m running into this issue Error loading MySQLdb module. Did you install mysqlclient?. Do I have to install it and do anything extra in my init file with mysqlclient?