Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Table doesn't exist
It's not a duplicate, I've already seen other posts with the same title, but the problem doesn't occur in the same moment as in these posts and answers doesn't work. After basic setup on new Ubuntu 20.04 LTS Machine i cloned my repository, created virtual environment, installed dependencies, installed mysql, edited my.cnf file with database informations and everything was working fine to the moment i did python3 manage.py migrate. I have error (1146, "Table 'todochat_data.app_server' doesn't exist"). Well it obviously doesn't exist because my database is empty, but I don't know how to fix it. I've already done these basic project setups dozens of times, but I've never seen this problem. todochat_data.app_server model [client] database = todochat_data user = todochat_user password = database_user_password default-character-set = utf8 What I tried: python manage.py migrate --database dataset python manage.py migrate --fake commenting out app in installed_apps History of commands: 9 git clone https://github.com/n3rsti/ToDoChat.git 10 cd ToDoChat/ 11 virtualenv -p python3 venv/ 12 source venv/bin/activate 13 ls 14 pip3 install -r requirements.txt 15 nano todochat/todochat/settings.py 16 sudo mysql -u root 17 sudo apt install mysql-server 18 sudo mysql -u root # I created todochat_user here using this template CREATE USER 'djangouser'@'%' IDENTIFIED WITH mysql_native_password … -
Security implications of refresh token grace period
I have an OAuth2 server built with django-oauth-toolkit, and by default, refresh tokens are revoked immediately upon use. This means that if a client requests a new access token using a refresh token but doesn't receive the response due to a network interruption they will be forced to reauthenticate. The library provides the setting REFRESH_TOKEN_GRACE_PERIOD_SECONDS which is an amount of time to wait between the use of a refresh token and its revocation. If a client uses a refresh token and does not receive the response, that original refresh token will still be valid for REFRESH_TOKEN_GRACE_PERIOD_SECONDS which allows the client to get a new access token without needing to reauthenticate. As far as I can tell, the purpose of immediately revoking refresh tokens upon use is to prevent replay attacks, but since this authorization server exclusively uses https, it seems this is a sufficient defense against this type of attack. Are there other vulnerabilities that can result from having a grace period for refresh token revocation? What would be the implications of never revoking a refresh token? -
django_filters search on field in ManyToMany through model
I have a manytomany relationship with a through model (joint table). I'd like to utilize the search_fields in DRF or other custom Filter to filter on a field in the through model. model 1: class Company(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, blank=False, null=False) source = models.CharField(max_length=255, blank=False, null=False) ein_number = models.CharField(max_length=255, blank=True, null=False) record_keepers = models.ManyToManyField( 'record_keepers.RecordKeepers', through='record_keepers.CompanyRecordKeepers', related_name='record_keepers') model 2 (through model): class CompanyRecordKeepers(models.Model): id = models.AutoField(primary_key=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) filing_year = models.IntegerField(blank=False, null=False) company = models.ForeignKey('employers.Company', on_delete=models.PROTECT, blank=True, null=False) record_keeper = models.ForeignKey('RecordKeepers', on_delete=models.PROTECT, blank=True, null=False) model 3: class RecordKeepers(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, unique=True, blank=True, null=True) Now in my view, I'd like to search for companies who filed in the filing_year 2019 and whose record_keeper name is contains some_value View: class ListCompanyView(generics.ListAPIView): serializer_class = CompanySerializer permission_classes = [IsAdminUser] filter_backends = (SearchFilter,) search_fields = ['companyrecordkeepers__filing_year'] queryset = Company.objects.all() Ideally I could do a GET request with some params to filter on: ?companyrecordkeepers__filing_year=2019&name=some_value Any idea how to accomplish this? -
Django HTML templating and javascript - convert variable to string
I have a dictionary data that I want to append a variable from my template to as a string. data = {} data['name'] = {{ img_obj.name }} However, that just appends the name, not as string. I want it the value to be string. I tried using the safe filter, that did not work. -
With multi-stage Dockerfile, the pip wheel still needs the dependencies from the base builder
I am new to the Docker environment. So, sorry if asking this is a common thing. I'm using the Dockerfile below, which first uses a builder to make things with the wheel. The problem is that the cryptography package in my requirements.txt file (a pip package) needs gcc and some other packages to build. As you can see below, I installed these packages (gcc and others) with RUN apk add in the base builder and then built the wheel. However, in the final builder, I get error saying that "gcc: No such file ..." so meaning that the gcc was not installed. (But I'm using the generated wheel from the base builder! Why does it still need the gcc and other stuff?) If I install the gcc and other build dependencies in the final build too, again, it solves the problem, yes. But, in this case, I lose the benefits of using multi-stage Dockerfile. I can't understand the problem. Can you help me? Here's the Dockerfile: FROM python:3.9.1-alpine as builder WORKDIR /usr/src/MYAPP ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt . RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ libressl-dev libffi-dev cargo \ && apk … -
how can i make my django website vulnerable to SQL injection and DDoS attacks?
i built a django website for security testing purposes to perform a set of attacks and then use the logs for analysis. it is basically a website for a bank called cryptobank in this bank each user have one or more bank account and can transfer money to another account. after finishing develpment of the website i deployed it on a ubuntu server virtual machine and made it locally available iside my network. i used the defualt User module for the authentication system (login and log out)and the registration to this website. i wanted to ask how can i make my website vulnerable to various attacks including denial of service SQl injection etc.. for the Dos and DDos attacks; i tried those attacks using High Orbit Ion Canon tool also i tried using the following simple python code import socket import threading target = '192.168.0.176' port = 8000 def attack(): while True: s= socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((target,port)) s.sendto(("GET /login/" + " HTTP/1.1\r\n").encode('ascii'), (target, port)) s.sendto(("GET /" + " HTTP/1.1\r\n").encode('ascii'), (target, port)) s.close() for i in range(500): thread = threading.Thread(target=attack) thread.start() but the problem i that the website won't go down for some reason, refreshing pages only gets slowed down a little bit … -
Limiting the number of entries to be added to a Django model with a Foreign Key
I am creating a real estate system using Django. I have Property models where the number of available units is defined. I have a separate Model for units, where each unit of a property is defines with its unique characteristics. I want to limit the number of units to be added not to exceed the number of units as defined in the Property Model. How do I accomplish that. The Property model is as shown below: # property class Property(models.Model): name = models.CharField('Property Name', max_length=100, unique=True) owner = models.ForeignKey(PropertyOwner, on_delete=models.CASCADE) location = models.ForeignKey(Location, on_delete=models.CASCADE) type = models.ForeignKey(PropertyType, on_delete=models.CASCADE) no_of_units = models.IntegerField('Number of Units') date_added = models.DateField('Date added') The unit model is as defined: class Unit(models.Model): property = models.ForeignKey(Property, on_delete=CASCADE) name = models.CharField(max_length=10) -
Why django admin ignores registered models managers?
I have a custom manager for User model which creates other objects when a new user is added, that logic is in a subclass of django auth's UserManager, but admin app ignores that. From what I saw only methods of ModelAdmin are called like save_model() when adding models. How can I make it use my custom UserManager and call UserManager.create_user()? Maybe I can do that with custom ModelForm? -
DJANGO: ModelForm not redirecting after form validation
I'm trying to do something very simple, add a newsletter subscribe form into my base.html the form validates and saves to the database but does not want to redirect i've tried reverse, reverse_lazy, HttpResponseRedirect and more but still does not want to redirect. If anyone can help me I would greatly appreciate it. View class NewsletterSubscribeView(RedirectView): def get_redirect_url(self, *args, **kwargs): if self.request.method == "POST": form = NewsletterForm(self.request.POST) if form.is_valid(): form.save() messages.add_message( self.request, messages.SUCCESS, "Thank you for subscribing to our newsletter!" ) else: messages.add_message(self.request, messages.ERROR, form.errors) else: form = NewsletterForm() return reverse_lazy("home") Form class NewsletterForm(forms.ModelForm): class Meta: model = Newsletter fields = ["email"] email = forms.EmailField(label="", required=True) Models from django.db import models from django.urls import reverse_lazy class Newsletter(models.Model): email = models.EmailField(unique=True) date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = "Newsletter Subscriber" verbose_name_plural = "Newsletter Subscribers" def __str__(self): return self.email def get_absolute_url(self): return reverse_lazy("home") Urls urlpatterns = [ path("", ContactView.as_view(), name="contact"), path("newsletter/subscribe/", NewsletterSubscribeView.as_view(), name="newsletter_subscribe"), ] Base.html <form class="dzSubscribe" action="{% url 'newsletter_subscribe' %}" method="POST"> {% csrf_token %} <div class="dzSubscribeMsg"></div> <div class="form-group"> <div class="input-group"> {{ newsletter_form }} <div class="input-group-addon"> <button name="submit" value="Submit" type="submit" class="btn btn-primary gradient fa fa-paper-plane-o"></button> </div> </div> </div> </form> -
django contact page sending emails wrongly
I have made a contact page in my Django project but it sends an email from the email_host_user to itself and does not get the user's email from the contact form, I appreciate your help in advance. I had a setting for email confirmation from the registration page and I am using that same code here. #settings.py import socket socket.getaddrinfo('localhost', 25) EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = config("EMAIL_HOST") EMAIL_USE_TLS = True EMAIL_PORT = config("EMAIL_PORT") EMAIL_HOST_USER = config("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = config("EMAIL_HOST_PASSWORD") #urls.py from . import views app_name = 'website' urlpatterns = [ path('contact', views.contact, name="contact")] #contact.html <section id="contact" class="contact"> <div class="container"> <div class="row mt-5 justify-content-center" data-aos="fade-up"> <div class="col-lg-10"> {% if name %} <h2>Thank you {{ name }}</h2> <p>We recieved your email and will respond shortly.</p> {% else %} <form action="{% url 'website:contact' %}" method="post" role="form" class="php-email-form"> {% csrf_token %} <div class="row"> <div class="col-md-6 form-group"> <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" /> <div class="validate"></div> </div> <div class="col-md-6 form-group mt-3 mt-md-0"> <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" /> <div class="validate"></div> </div> </div> <div class="form-group mt-3"> <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of … -
PassWordChangeForm for other user than current one
I tried to follow some tutorials to implement the password change functionality, but the problem is, that its always for the currently authenticated user. I want for example an admin to be able to change the password of another user (not through the admin panel). class PasswordChangeForm(PasswordChangeForm): def __init__(self, *args, **kwargs): super(PasswordChangeForm, self).__init__(*args, **kwargs) self.fields['old_password'].widget.attrs['class'] = 'form-control' self.fields['new_password1'].widget.attrs['class'] = 'form-control' self.fields['new_password2'].widget.attrs['class'] = 'form-control' My view looks like this: def changepassword(request): user = User.objects.get(id = request.POST.get("id")) if request.POST.get("type") == "user_changepw": form = PasswordChangeForm(user=user) else: form = PasswordChangeForm(data=request.POST, user=user) if form.is_valid(): form.save() return render(request, 'user_changepw.html') The user is coming here from a list of all the users with corresponding buttons that have as input the id of that user and also a hidden input "user_changepw", so that the form isnt throwing errors the first time you get on the site. But this also seems to be the problem, because after that the "id" value in the POST request is lost, so that the attempt to fetch the user form the DB always fails, beacuse request.POST.get("id") is now None. What we be a good solution to keep the user-id in the function or how to pass it through so that it persists also … -
Company with ID “None” doesn’t exist. Perhaps it was deleted? (DJANGO)
'''It does save the model but when I click the saved model it gives the error "Company with ID “None” doesn’t exist. Perhaps it was deleted? "''' class Company(models.Model): company_code=models.CharField( max_length=30, blank=False,unique=True) company_name=models.CharField(max_length=80, blank=True) date=models.DateField() #objects=companyManager() def create_company(self,company_code): company_code = self.create_company( company_code='company_code' ) company_code.save(using=self._db) return company_code def __str__(self): return self.company_code -
NoReverseMatch at /job Reverse for 'job_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['jobs/(?P<job_id>[0-9]+)$']
I am getting this error in Django:NoReverseMatch at /job Reverse for 'job_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['jobs/(?P<job_id>[0-9]+)$'] My view is below: def job(request): jobs = Job.objects.filter(status=Job.ACTIVE).order_by('-created_at')[0:3] services = Service.objects.filter(status=Service.ACTIVE).order_by('-created_at')[0:3] return render(request,'job/jobs.html',{'jobs':jobs ,'services':services}) -
GeoDjango: Set default for PointField on MariaDB
How can I set a default point for a PointField? On my local sqlite instance it is working. Unfortunately it is not working with mariaDB. I tried this: point = models.PointField(srid=4326, default=Point(0.0, 0.0)) And getting the following error on mardiaDB (running migrations) django.db.utils.OperationalError: (1416, 'Cannot get geometry object from data you send to the GEOMETRY field') -
ModelAdmin save_model pytest django
I am working on a simple test case using pytest for my customized model admin. Here is what I am able to get so far. Not sure what else I can do get the test passed. ModelAdmin class class CustomerAdmin(admin.ModelAdmin): """ A UserAdmin that sends a password-reset email when verifying a new user. """ list_display = ["user", "is_verified"] list_per_page = 10 search_fields = [ "user", ] list_filter = ("is_verified",) # will check if the verifed boolean has changed def save_model(self, request, obj, form, change): if change and "is_verified" in form.changed_data: verified = form.cleaned_data["is_verified"] # if account is verified we will send password set form if verified: user_email = str(obj.user.email) reset_form = PasswordResetForm({"email": user_email}) assert reset_form.is_valid() # https must be set to True in production try: reset_form.save( request=request, use_https=False, email_template_name="core/password_reset_email.html", ) try: sf = salesforce_authenticate(SF_USERNAME, CONSUMER_KEY) except SalesforceAuthenticationFailed: pass except BadHeaderError: return HttpResponse("Invalid header found.") super().save_model(request, obj, form, change) Here is my test function so far. The logic is that I want to test out if an admin changes a value of a field called "is_verified" to True in the admin page, there are two events happen: An email will be sent out to the customer with password_reset_email template in order … -
FATAL: password authentication failed for user "dashboard_mineria_user"
I'm trying to run a project in django called dashboard_mineria. When I run it, I get this error Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread Thread-1: Traceback (most recent call last): File "/home/mauricio/Escritorio/python-virtual-environments/env/lib/python3.5/site- packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/home/mauricio/Escritorio/python-virtual-environments/env/lib/python3.5/site- packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/home/mauricio/Escritorio/python-virtual-environments/env/lib/python3.5/site- packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/home/mauricio/Escritorio/python-virtual-environments/env/lib/python3.5/site- packages/psycopg2/init.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user "dashboard_mineria_user" FATAL: password authentication failed for user "dashboard_mineria_user" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/home/mauricio/Escritorio/python-virtual-environments/env/lib/python3.5/site- packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/mauricio/Escritorio/python-virtual-environments/env/lib/python3.5/site- packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/home/mauricio/Escritorio/python-virtual-environments/env/lib/python3.5/site- packages/django/core/management/base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/mauricio/Escritorio/python-virtual-environments/env/lib/python3.5/site- packages/django/db/migrations/executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "/home/mauricio/Escritorio/python-virtual-environments/env/lib/python3.5/site- packages/django/db/migrations/loader.py", line 49, in init self.build_graph() File "/home/mauricio/Escritorio/python-virtual-environments/env/lib/python3.5/site- packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/mauricio/Escritorio/python-virtual-environments/env/lib/python3.5/site- packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/home/mauricio/Escritorio/python-virtual-environments/env/lib/python3.5/site- packages/django/db/migrations/recorder.py", line 56, in has_table … -
DRF: How to make serializer fields different depending on instance attributes
I'm not overly familiar with DRF or Django, but here goes: I'm working on a workout-API that returns a user, and the user is able to set the visibility of their profile. The table looks something like: id | username | email | coach_id | visibility where visibility is one of public, coach, private. This means that if User 1 has visibility = private, another user fetching their profile should only see the attributes id and username, but the user themselves should get all the attributes. The user's coach should see a profile if visibility = public or visibility = coach. I've looked into dynamically setting the serializer's fields-variable, with no luck (because the fields should be "generated" depending on the content of the object/instance). I've also looked into serializers.SerializerMethodField(), but it simply showed all fields at all times. Suppose I might have used that wrong. What I am wondering is: What is the best way to attack this problem? -
How to remove password confirmation field in django UserCreationForm
I have created a UserCreationForm as follow: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1'] exclude = ['password2'] def __init__(self, *args, **kwargs): super(UserRegisterForm, self).__init__(*args, **kwargs) # for fieldname in ['password2']: self.fields['password2'].help_text = None self.fields['password1'].help_text = None self.fields['username'].help_text = None However I am trying to remove Password Confirmation field from the register form, but so far couldn't find any solution for that. Do you know how to resolve this problem? -
How to create update form in a for loop?
I listing my customers in a table with for loop. I want to change one attribute (user) with a form in this table. For doing that I have to take customer's information and update that. But I don't know how can take a customer's id in a loop. this is my table: my customer list How can I take specific customer object and update it? Here are my codes. views.py def customer_list(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) customer_list = Customer.objects.filter(company=userP[0].company.comp_name) # Assign form = AssignForm(request.POST or None) if form.is_valid(): form.save() return redirect('user:customer_list') myFilter = TableFilter(request.GET, queryset=customer_list.all()) context = { 'customer_list': customer_list, 'myFilter': myFilter, 'form': form } return render(request, 'customer_list.html', context) models.py class Customer(models.Model): customer_name = models.CharField(max_length=20) country = models.CharField(max_length=20) ... user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, blank=True, null=True) class UserProfile(AbstractUser, UserMixin): company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True, unique=False) user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500, unique=True) first_name = models.CharField(max_length=200) customer_list.html <table id="multi-filter-select" class="display table table-striped table-hover grid_" > <thead> <tr> <th>Customer Name</th> <th>Country</th> <th>E-Mail</th> <th>Phone</th> <th>VAT Number</th> <th>Operations</th> </tr> </thead> <tfoot> <tr> <th>Customer Name</th> <th>Country</th> <th>E-Mail</th> <th>Phone</th> <th>VAT Number</th> <th>Quick Operations</th> </tr> </tfoot> <tbody> {% for customer in customer_list %} <tr> <td>{{customer.customer_name}}</td> <td>{{customer.country}}</td> <td>{{customer.email}}</td> <td>{{customer.telephone}}</td> <td>{{customer.VATnumber}}</td> <td> <div class="row"> <a href="/customers/{{ … -
Static file not found in heroku
I want to publish a very little site in heroku but i have a problem. It's working on local server but when I push it to heroku it's broken. I have a 404 error with my images and css links. Here my settings.py : Django settings for pizzamama project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'e(_(f@2@3o1c6c-96qt5p4y4-k@rt3uvj6z%j=2w**2yp(p^rk' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['fabpizzamama.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'menu.apps.MenuConfig', 'main.apps.MainConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'pizzamama.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'pizzamama.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES … -
Authentication user by type, not getting results after login
I am trying to authentication the user by type. I did this in simple HTML code, bat still not getting any results. This is my model.py: class CustomKorisnici(AbstractUser): user_type = models.CharField(max_length=100,blank=True,choices=user_type_choice) username = models.CharField(max_length=100,unique=True) last_name = models.CharField(max_length=100) first_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=100) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) email = models.EmailField(max_length=100,unique=True) my login HTML is working fine: <div class="form-group"> <div class="container"> <div class="form"> <form method="post"> {% csrf_token %} {{ form.as_p }} <button id="btn" class="btn">Login</button> </form> </div> </div> </div> </div> but on my home page HTML , I am not getting any ruselt {% if user.is_authenticated %} {% if user.user_type == korisni %} <div class="col-md-4"> <a class="nav-link" href="{% url 'post_page' %}">All posts</a> </div> {% endif %} {% endif %} -
XMLSchemaImportWarning: Import of namespace 'http://www.w3.org/2001/04/xmlenc#'
I am trying to integrate SAML2 Auth in the existing django project. However i have been getting this error continuously. F:\finessevenv\lib\site-packages\saml2\xml\schema\__init__.py:18: XMLSchemaImportWarning: Import of namespace 'http://www.w3.org/2000/09/xmldsig#' from ['http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd'] failed: block access to remote resource http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd. return _XMLSchema(source, **kwargs) F:\finessevenv\lib\site-packages\saml2\xml\schema\__init__.py:18: XMLSchemaImportWarning: Import of namespace 'http://www.w3.org/2001/04/xmlenc#' from ['http://www.w3.org/TR/2002/REC-xmlenc-core-20021210/xenc-schema.xsd'] failed: block access to remote resource http://www.w3.org/TR/2002/REC-xmlenc-core-20021210/xenc-schema.xsd. return _XMLSchema(source, **kwargs) F:\finessevenv\lib\site-packages\xmlschema\validators\schema.py:1191: XMLSchemaImportWarning: Import of namespace 'http://www.w3.org/2000/09/xmldsig#' from ['http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd'] failed: block access to remote resource http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd. build=build, F:\finessevenv\lib\site-packages\xmlschema\validators\schema.py:1191: XMLSchemaImportWarning: Import of namespace 'http://www.w3.org/2001/04/xmlenc#' from ['http://www.w3.org/TR/2002/REC-xmlenc-core-20021210/xenc-schema.xsd'] failed: block access to remote resource http://www.w3.org/TR/2002/REC-xmlenc-core-20021210/xenc-schema.xsd. build=build, What could be the possible reason of this error and how can i fix this? -
Can anyone help me with the algorithm in python3 please?
Input: products = ['Footwear', 'Apparel', 'Books', 'Gadgets'] damages = ['stained', 'wrinkled', 'torn', 'wadrobed', 'seal-broken'] frequency = { ('Footwear', 'stained'): 2, ('Apparel', 'wrinkled'): 2, ('Books', 'stained'): 1, ('Books', 'torn'): 1, ('Apparel', 'wadrobed'): 1, ('Gadgets', 'seal-broken'): 1, ('Footwear', 'torn'): 1, ('Footwear', 'wrinkled'): 1} Expected Output: {'Footwear':[2,1,1,0,0], 'Gadgets':[0,0,0,0,1], .... Missing out on correct algo. Just got started please help. -
Not able to deploy a project on heroku
There was an issue deploying your app. View the build log for details. -----> Building on the Heroku-20 stack -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed -
Django filter all items within bounding box (by LAT, LNG)
I use Postgres with Django and I have a model Parcel that has coordinate fields: address_lat = models.DecimalField... address_lat = models.DecimalField... I'm trying to create a method (on Manager) that returns all parcels withing the given area in km. I don't use Postgis and GeoDjango so it doesn't need to be within circle, it can be a square. So I did this: def get_bounding_box(lat, lng, km): lat_change = Decimal(km / 111.2) lng_change = Decimal(abs(math.cos(lat * (Decimal(math.pi) / Decimal(180))))) bounds = { 'lat_min': lat - lat_change, 'lng_min': lng - lng_change, 'lat_max': lat + lat_change, 'lng_max': lng + lng_change } return bounds class ParcelManager(models.Manager): def within_area(self, lat, lng, km): bounding_box = get_bounding_box(lat, lng, km) return self.get_queryset().filter(address_lat__gte=bounding_box['lat_min'], address_lng__gte=bounding_box['lng_min'], address_lat__lte=bounding_box['lat_max'], address_lng__lte=bounding_box['lng_max'], ) The problem is that this returns too much parcels. For 5cm input (0.00005) it returns two parcels, one of them is the same parcel but the other is almost 1km away. In [1]: p = Parcel.objects.last() In [2]: p.address_lat Out[2]: Decimal('34.784954778041') In [3]: p.address_lng Out[3]: Decimal('-92.250170096711') In [4]: Parcel.objects.within_area(p.address_lat,p.address_lng,0.00005) Out[4]: <QuerySet [<Parcel: Parcel object (42173)>, <Parcel: Parcel object (51764)>]> In [5]: results = Parcel.objects.within_area(p.address_lat,p.address_lng,0.00005) In [6]: results.first().address_lat Out[6]: Decimal('34.784954911726') In [7]: results.first().address_lng Out[7]: Decimal('-92.286596972046') Do you know where is the problem?