Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django models: UUID on non-primary-key field not generated in admin panel
I have added an UUIDField to one of my models. Everything works fine, except for creating objects from the admin panel, where the UUID is not generated automatically. I had to resort to setting the UUID on newly created instances. Here is the code of my model: class User(AbstractUser): ... uuid = models.UUIDField(unique=True, default=uuid.uuid4) I didn't do anything else anywhere. When I call User.objects.create(...), the instance is created with a uuid, but when I create one in the admin panel, it fails with uuid being null and violating the not-null constraint. As a workaround, I did this, but it doesn't seem right. class UserAdmin(ModelAdmin): ... def save_model(self, request, obj, form, change): if not change: obj.uuid = uuid4() return super().save_model(request, obj, form, change) -
How to show count of related foreign key objects inside brackets, in Django Admin filter?
I have to override the default Django admin list_filter to show the count of foreign key objects inside brackets, in the right hand side filters. I am able to do it for a specific filter, using the following code, but how do I create a Mixin or a class which can apply the same logic to all fields in list_filter? class ObjectCountInFilter(admin.SimpleListFilter): title = _('Client') parameter_name = 'client' def lookups(self, request, model_admin): qs = model_admin.get_queryset(request) for pk, name, count in qs.values_list('client__id','client__name').annotate(total=Count('client')).order_by('-total'): if count: yield (pk, f'{name} ({count})') def queryset(self, request, queryset): id_val = self.value() if id_val: return queryset.filter(client=id_val) -
Python 3 ERROR: Package 'openpyxl' requires a different Python: 3.5.3 not in '>=3.6, '
Trying to install python package import_export I've tried to install a python module: virtualenv . source bin/activate pip3 install -U django-import-export Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple Collecting django-import-export Using cached django_import_export-2.0.1-py3-none-any.whl (82 kB) Requirement already satisfied, skipping upgrade: Django>=2.0 in /home/pi/inventree-env/lib/python3.5/site-packages (from django-import-export) (2.2.9) Collecting diff-match-patch Using cached https://www.piwheels.org/simple/diff-match-patch/diff_match_patch-20181111-py3-none-any.whl (54 kB) Collecting tablib<1.0.0 Using cached tablib-0.14.0-py3-none-any.whl (65 kB) Requirement already satisfied, skipping upgrade: pytz in /home/pi/inventree-env/lib/python3.5/site-packages (from Django>=2.0->django-import-export) (2019.3) Requirement already satisfied, skipping upgrade: sqlparse in /home/pi/inventree-env/lib/python3.5/site-packages (from Django>=2.0->django-import-export) (0.3.0) Collecting xlrd Using cached xlrd-1.2.0-py2.py3-none-any.whl (103 kB) Collecting markuppy Downloading https://www.piwheels.org/simple/markuppy/MarkupPy-1.14-py3-none-any.whl (8.5 kB) Collecting xlwt Using cached xlwt-1.3.0-py2.py3-none-any.whl (99 kB) Collecting openpyxl>=2.4.0 Using cached https://www.piwheels.org/simple/openpyxl/openpyxl-3.0.3-py2.py3-none-any.whl (241 kB) ERROR: Package 'openpyxl' requires a different Python: 3.5.3 not in '>=3.6, ' I also installed sudo apt-get install python3-openpyxl Which works. However ImportError: No module named 'import_export' Anyone have a solution? -
Django Many To Many custom relation
I have one special requirement where I have to use multiple DB. DBs will will be created by users. Database creation and migration on the new DB created by user is done through script which is working fine. First DB (which is default DB) will only contain User model and DBDetails which store database names created by user. In these database I will have Multiple models which needs either ForeignKey or ManyToMany relationship with User Model of first database. instead of ForeignKey I have stored user_id as Integer Field in all the models. My problem is how to make a many to many relation between User and models of Other Database. I am thinking of writing a custom ManyToManyField which instead of taking a Model instance takes a field name like user_id. I have search django docs and here but the answers didn't fit my problem. -
Cloudinary with Django - use javascript to dynamically increase/decrease photo width and height after page rendered
I have Django app where I used Cloudinary to deliver images. The images are displayed in template with fixed width and height as follows: <a href="/photo/{{ photo.id }}/"> {% cloudinary photo.filename width=100 height=100 crop="fill" %} </a> I want to add a "+" and "-" buttons to dynamically increase and decrease script photo width and height after the page is rendered. I would have an array of possible width/height values eg 100, 125, 150, 175, 200, 225, 250, 300 that would be sequentially selected by clicking the "+" and "-" buttons. Ideally page doesn't reload, only Cloudinary call is made to retrieve resized photos. I am using Isotope.js to display photos in a grid which can be called to adjust placement on page. This is not just dynamically changing width/height values of rendered photos but getting new sized photos from cloudinary. The following script will get and render photo from Cloudinary and could replace width and height with variables: $.cloudinary.image(data.result.public_id,{ format: data.result.format, width: 100, height: 100, crop: "fill"}) I imagine looping through the rendered photo elements to replace existing photos with new photos using script above. But struggling to come up with approach. -
Maintaining user session without having user saved in django authentication system
I am having a small Django app in which users need to be authenticated externally via Webgate plugin installed on Apache. Webgate will use other enterprise authentication system hosted on the intranet to authenticate the users coming into my django site. Once the enterprise authentication system authenticates the user, it will redirect them to our site with a header REMOTE-USER. This header will contain the username. I need to just make sure that user mentioned in that header is able to access to the site even though it does not exist on my site, trusting that he is already authenticated. For this I am using 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', 'django.contrib.auth.middleware.RemoteUserMiddleware', ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.RemoteUserBackend', ) This works. But it creates users in the site. Requirement is that users must not exist in our database. They can exist in memory. They need to have a session Is this even possible in Django? If yes, how I could achieve this? I tried subclassing AllowAllUsersRemoteUserBackend as below and overriding authenticate method to return a user which is just in memory, not in DB. class AllowAllUsersRemoteUserBackendWithoutCreatingUnknownUsers(AllowAllUsersRemoteUserBackend): create_unknown_user = False def authenticate(self, request, remote_user): return User(username = remote_user) … -
Reverse for 'topic' with arguments '('',)' not found. 1 pattern(s) tried: ['topic/(?P<name>[^/]+)$']
My question is about redirection again to a /topics/ page where all entries for topic are located. When I end an entry this code and reload tab than showing this error is occured as below: Reverse for 'topic' with arguments '('',)' not found. 1 pattern(s) tried: ['topic/(?P[^/]+)$'] how can i solved this? at views.py from django.shortcuts import render, HttpResponse from django.views.generic.base import View from .models import author, catagory, article # Create your views here. class HomeView(View): def get(self, request, *args, **kwargs): post = article.objects.all() context = { "post":post } return render (request, 'index.html', context) def getauthor(request, name): return render (request, 'profile.html') def getsingle(request, id): return render (request, 'single.html') def getTopic(request, name): return render (request, 'category.html') at urls.py from django.urls import path from .import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.HomeView.as_view(), name = 'home'), #path('about/', views.AboutView.as_view(), name = 'about'), path('author/<name>', views.getauthor, name = 'author'), path('article/<int:id>', views.getsingle, name = 'single_post'), path('topic/<name>', views.getTopic, name = 'topic'), ] urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) at index.html {% extends "base.html" %} {% load static %} {% block title %} Welcome to my django templates {% endblock %} {% block content %} {% for p in post %} <article class="col-lg-3 col-md-3 col-sm-3 … -
File type from pandas.DataFrame.to_excel is "Zip archive data, at least v2.0 to extract"
I notice that the file type from an Excel file generated by pandas.DataFrame.to_excel is Zip archive data, at least v2.0 to extract. Please do note that the content type is fine: content_type, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet. In my Django project, I am essentially validating a file type before processing the uploaded file, and although the file generated by pandas.DataFrame.to_excel is a valid Excel file, the validation module is rejecting the uploaded file because of the file type being Zip archive data, at least v2.0 to extract, instead of Microsoft Excel 2007+. Please let me know how I can get around this validation. The code I used to replicate (i.e., to create an Excel file with the file type Zip archive data, at least v2.0 to extract) this issue is here. import pandas as pd import os import magic uploaded_file_path = r'somepath' path, filename = os.path.split(uploaded_file_path) filename_without_extension = os.path.splitext(filename) new_file_name = os.path.join(path, filename_without_extension[0]) + '_TESTING_BLAH_' + str(1) + '.xlsx' df1 = pd.DataFrame([['a', 'b'], ['c', 'd']], index=['row 1', 'row 2'], columns=['col 1', 'col 2']) df1.to_excel(new_file_name) file_type = magic.from_file(new_file_name) print(file_type) -
How to render comments using django Contenttypes and Generic Foreign Key?
I used django generic foreign key to comment all the models but i dont know why its not rendering in the template. models.py from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey,GenericRelation from django.utils import timezone class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') text = models.TextField(null=False, blank=False) def __str__(self): return self.text[:20] views.py def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) content_type = ContentType.objects.get_for_model(Post) obj_id = post.id comments = Comment.objects.filter( content_type=content_type, object_id=obj_id) return render(request, 'post_detail.html', {'post': post, 'comments': comments}) post_detail.html {% extends 'base.html' %} <div class="post"> {% if post %} <div class="date"> {{ post.published_date }} </div> {% endif %} <h2>{{ post.title }}</h2> <p>{{ post.content|linebreaksbr }}</p> <p class='lead'>Comments</p> {%for comment in comments %} {{comment.text}} {%endfor%} </div> {% endblock %} I am not getting the data for my comments for posts -
ImportError: d doesn't look like a module path
I've been through the basics of Django and was attempting a custom user model for a project. I tried a few codes from youtube and blogposts. Every time after I run makemigrations and migrate, it registers the user(createsuperuser) through the terminal but when I enter the view to admin(http://localhost:8000/admin/) it gives my this error: ImportError: d doesn't look like a module path. I tried this multiple times altering the fields but every time I get the same error. Also in the Traceback I gave this: The above exception (not enough values to unpack (expected 2, got 1)) was the direct cause of the following exception from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin ) from django.utils import timezone # Create your models here. class UserManager(BaseUserManager): def create_user( self, email, first_name, last_name, password=None, commit=True): """ Creates and saves a User with the given email, first name, last name and password. """ if not email: raise ValueError('Users must have an email address') if not first_name: raise ValueError('Users must have a first name') if not last_name: raise ValueError('Users must have a last name') user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, ) user.set_password(password) if commit: user.save(using=self._db) return user def create_superuser(self, email, first_name, … -
Django - How to use the model method in a fuction based view
I have created a function that sums all amounts in a model. How can I execute this function(get_tot_order_price) in a function based view(FBV)? def myview(request): ??? class BillingItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) product = models.ForeignKey(Product, on_delete=models.PROTECT,) quantity = models.PositiveIntegerField() order_price = models.FloatField() def __str__(self): return '{}'.format(self.id) def get_tot_order_price(self): total = 0 for price in self.order_price.all(): total += price return total -
How to get order_id in Razor Pay Payment Gateway?
I am looking for the order_id from the razorpay to save in the database, how do i get that in views.py to save in database. Payment is successfully done by the razerpay but I want to retrieve that order_id. I am getting the below error module 'razorpay.client' has no attribute 'order' checkout.html <form action="{% url 'checkout:payment' %}" method="POST"> {% csrf_token %} <script src="https://checkout.razorpay.com/v1/checkout.js" data-key="######################" data-amount="{{ amount }}" data-currency="INR" data-buttontext="Pay with Razorpay" data-name="Acme Corp" data-description="A Wild Sheep Chase is the third novel by Japanese author Haruki Murakami" data-image="https://example.com/your_logo.jpg" data-prefill.name="Gaurav Kumar" data-prefill.email="gaurav.kumar@example.com" data-prefill.contact="9999999999" data-theme.color="#F37254" > </script> <input type="hidden" custom="Hidden Element" name="hidden"> </form> -
How can i kill SubTask in Celery Whenever parent task is killed?
I'm using django and celery to build web application, But I'ma facing small issue. Whenever I killed task it only kill parents task and throw error. Is there any way to kill parent task as well as sub task at the same time successfully. -
How to list posts with an order ? - In Django
Here is my code: def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now().order_by('-published_date')) I want to list the post with an order here. However when I run the server, I am getting error like this: 'datetime.datetime' object has no attribute 'order_by' I am watching some udemy course so I am doing whatever he do. Can someone help me about it? -
Best way to store values in database, Django
I am working in a food ordering app(a personal project), where a user can set weekly schedule for his selected items (food) from vendor. I can't figure out way to store weekly data in a table for customer. In addition, user can specify quantity for each day. I am working in django. WHAT I TRIED: i tried to create a table with list of days and another table with items and quantity and relate them with ForeignKey . this works but i think this is not a good practice. Looking for some help. -
MultiValueDictKeyError i can not understand what is the problem in code
hello so here is my screenshots of django project hope anybody will solve my question bcoz i'm beginner in this field... ]2]3]4 -
Rest Framework Image Validation
I have a form that sends an image via Django Rest Framework. The serializer is as shown: class AvatarSerializer(serializers.ModelSerializer): avatar = Base64ImageField(validators=[image_validation]) class Meta: model = Profile fields = ('avatar',) I also have image validation that checks the size of the image so that it is not over 12MB: def image_validation(image): # 12MB MAX_FILE_SIZE = 12000000 print(image.name) if image.size > MAX_FILE_SIZE: print(image.size) raise ValidationError("File size too big!") The image size gets printed out when I try to upload an image greater than 12mb, however, I get this response in Chrome's network tab: Failed to load response data I read that it might be because of the image's size (I was trying to upload a 30mb image). The ValidationError is not shown and the user gets a 500 server error. How can I fix this? -
validate yamlusing pyrestest in django
Response to the request is: [ { "id": 4, "name": "asdsf", "tags": [ { "id": 1, "name": "boy" }, { "id": 5, "name": "cat" } ] }, { "id": 1, "name": "asdas", "tags": [ { "id": 1, "name": "man" }, { "id": 5, "name": "women" } ] } ] I am trying to check 1st name using pyresttest, so here is yaml file which i have created. My testcase.yaml - config: - testset: "Tests using test app" - test: # create entity - name: "Basic get most rated movie" - url: "/?tag=2&order_by=name" - group: "Successful" - method: "GET" - headers: {Content-Type: application/json} - expected_status: [200] - validators: # Check the user name matches - compare: {jsonpath_mini: "name[0]", comparator: "eq", expected: 'William Shakespeare Book name ?'} How will i check for the 1st response in my yaml ? -
Changing style of default django CMS menu not working properly?
I am using django-cms to generate the dynamic menus and sub-menus.I wanted to change the style of default li class generated by the django_cms. So I tried like this.I did this by this answer. partials/navigation.html {% load cms_tags menu_tags %} {% for child in children %} <li class="nav-item dropdown"> <a href="{{ child.attr.redirect_url|default:child.get_absolute_url }}" class="nav-link dropdown-toggle" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">{{ child.get_menu_title }}</a> {% if child.children %} <ul class="dropdown-menu"> {% show_menu from_level to_level extra_inactive extra_active template '' '' child %} </ul> {% endif %} </li> {% endfor %} base.html <div id="my-nav" class="collapse navbar-collapse"> <ul class="navbar-nav"> {% show_menu 0 100 100 100 "partials/navigation.html" %} </ul> </div> The result I am getting There is one sub menu for this About Us Menu but it is not displaying.Everything working but the title is not displaying. What I am doing wrong here? -
how to slove kernal error in jupyter notebook ?, win64
I am kinda new to Jupyter notebooks. I am getting a kernel error on the top right corner of the notebook(python 3) , also i can't run any code i wort , THIS IS THE ERROR Traceback (most recent call last): File "C:\Users\LAM\Anaconda3\lib\site-packages\tornado\web.py", line 1699, in _execute result = await result File "C:\Users\LAM\Anaconda3\lib\site-packages\tornado\gen.py", line 742, in run yielded = self.gen.throw(*exc_info) # type: ignore File "C:\Users\LAM\Anaconda3\lib\site-packages\notebook\services\sessions\handlers.py", line 72, in post type=mtype)) File "C:\Users\LAM\Anaconda3\lib\site-packages\tornado\gen.py", line 735, in run value = future.result() File "C:\Users\LAM\Anaconda3\lib\site-packages\tornado\gen.py", line 742, in run yielded = self.gen.throw(*exc_info) # type: ignore File "C:\Users\LAM\Anaconda3\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 88, in create_session kernel_id = yield self.start_kernel_for_session(session_id, path, name, type, kernel_name) File "C:\Users\LAM\Anaconda3\lib\site-packages\tornado\gen.py", line 735, in run value = future.result() File "C:\Users\LAM\Anaconda3\lib\site-packages\tornado\gen.py", line 742, in run yielded = self.gen.throw(*exc_info) # type: ignore File "C:\Users\LAM\Anaconda3\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 101, in start_kernel_for_session self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_name) File "C:\Users\LAM\Anaconda3\lib\site-packages\tornado\gen.py", line 735, in run value = future.result() File "C:\Users\LAM\Anaconda3\lib\site-packages\tornado\gen.py", line 209, in wrapper yielded = next(result) File "C:\Users\LAM\Anaconda3\lib\site-packages\notebook\services\kernels\kernelmanager.py", line 168, in start_kernel super(MappingKernelManager, self).start_kernel(**kwargs) File "C:\Users\LAM\Anaconda3\lib\site-packages\jupyter_client\multikernelmanager.py", line 110, in start_kernel km.start_kernel(**kwargs) File "C:\Users\LAM\Anaconda3\lib\site-packages\jupyter_client\manager.py", line 240, in start_kernel self.write_connection_file() File "C:\Users\LAM\Anaconda3\lib\site-packages\jupyter_client\connect.py", line 547, in write_connection_file kernel_name=self.kernel_name File "C:\Users\LAM\Anaconda3\lib\site-packages\jupyter_client\connect.py", line 212, in write_connection_file with secure_write(fname) as f: File "C:\Users\LAM\Anaconda3\lib\contextlib.py", line 112, in __enter__ return next(self.gen) File … -
ValueError at /cart/chelsea-01920-jersey/ invalid literal for int() with base 10: 'color'
Hi guys im getting this error try to with my models and views Traceback (most recent call last): File "C:\Users\hp\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\hp\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\hp\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\hp\OneDrive\Desktop\DevProjects\Elsie_Final\carts\views.py", line 57, in UpdateCart cart_item, created = CartItem.objects.get_or_create(cart=cart, item=item) File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\models\query.py", line 538, in get_or_create return self.get(**kwargs), False File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\models\query.py", line 399, in get clone = self.filter(*args, **kwargs) File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\models\query.py", line 892, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\models\query.py", line 910, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\models\sql\query.py", line 1290, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\models\sql\query.py", line 1318, in _add_q split_subq=split_subq, simple_col=simple_col, File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\models\sql\query.py", line 1251, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\models\sql\query.py", line 1116, in build_lookup lookup = lookup_class(lhs, rhs) File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\models\lookups.py", line 20, in init self.rhs = self.get_prep_lookup() File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\models\fields\related_lookups.py", line 115, in get_prep_lookup self.rhs = target_field.get_prep_value(self.rhs) File "C:\Users\hp\Anaconda3\lib\site-packages\django\db\models\fields__init__.py", line 966, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'color' models: class CartItem(models.Model): cart = models.ForeignKey(Cart, null=True, blank=True, on_delete=models.CASCADE) variations = models.ManyToManyField(Variation, null=True, blank=True) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity … -
How do I write my django code if the first field decides which database to access to get the rest of the fields
I'm writing a program that visualizes the data in multiple databases. I want my models.py to have a field that decides which database to load to visualize. This is proving to be difficult as after loading the data the program is to display the fields in the database but when I run manage.py it runs the while program and doesn't wait for me to input the name of the database from which to take the data and displays error as the fields are not defined How do I rectify this? -
how to retrieve user when logging in with `obtain_jwt_token` using Angular and Django
I have seen a couple posts regarding this that are 3-5 years old and wondering if there is a better way. Using Angular 8 and Django 3. I am using django-rest-framework, 'rest_framework.authtoken' and the generic path(r'api-token-auth/', obtain_jwt_token) endpoint to login a user and retrieve an authentication token. I am successful in retrieving the auth token for a user. After I login however I want to redirect to a dashboard page that shows all the users details, etc. Problem is the response I get to the client from that endpoint is a token key only. I want to also get all the user object/details.. how can I do this? Do I need to create an additional component that uses either the token or submitted username or something to then lookup the user that I am logging in? Or do i need a custom login view? Seems like it should automatically pass the user back after login... urls.py urlpatterns = [ path('dashboard/<int:pk>', UserDashboard.as_view(), name='dashboard'), path(r'api-token-auth/', obtain_jwt_token), ] -
SSL error when installing django for python3
$ pip3 install django Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(185090184, '[X509] no certificate or crl found (_ssl.c:3732)'),)': /simple/django/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(185090184, '[X509] no certificate or crl found (_ssl.c:3732)'),)': /simple/django/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(185090184, '[X509] no certificate or crl found (_ssl.c:3732)'),)': /simple/django/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(185090184, '[X509] no certificate or crl found (_ssl.c:3732)'),)': /simple/django/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(185090184, '[X509] no certificate or crl found (_ssl.c:3732)'),)': /simple/django/ Could not find a version that satisfies the requirement django (from versions: ) No matching distribution found for django I have tried various solutions. I installed python3.7 and then tried but same. I also tried this but the result was also same. $ sudo apt-get install python3-setuptools ca-certificates and same thing happens when I install django in a venv. Same goes for the installing a specific version of django. -
AssertionError: ValidationError not raised by full_clean
In the following form, I have declared a clean() method that is evaluating the following condition: Does the the expiration_date come before the the created_date? If the that condition is True, I want to raise a ValidationError. When the test is ran, I get the following error: AssertionError: ValidationError not raised by full_clean. However if form.errors.as_data() is called, this results in: {'expiration_date': [ValidationError(['The expiration date is set before the created date'])]} Could some explain as to what is happening? forms.py class MenuForm(forms.ModelForm): MENU_YEARS = [2019, 2020, 2021] season = forms.CharField( min_length=4, validators=[validate_season] ) items = forms.ModelMultipleChoiceField( queryset=Item.objects.all(), to_field_name='name' ) expiration_date = forms.DateTimeField( required=False, widget=SelectDateWidget( years=MENU_YEARS, empty_label=("Choose Year", "Choose Month", "Choose Day") ) ) def clean(self): cleaned_data = super().clean() created_date = cleaned_data['created_date'] = timezone.now() expiration_date = cleaned_data['expiration_date'] if created_date > expiration_date: raise ValidationError( {'expiration_date': "The expiration date is set before the created date"} ) class Meta: model = Menu fields = ['season', 'items', 'expiration_date'] test_forms.py class TestMenuForm(TestCase): @classmethod def setUpTestData(cls): cls.data = { 'season': 'Late Fall', 'items': ['Crepe'], 'expiration_date': datetime(2018, 1, 2) } def test_menu_model_clean(self): with self.assertRaises(ValidationError): self.menu_form.full_clean()