Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use django AppConfig.ready()
I can't seem to get my ready function under my AppConfig to work. Here is my code from apps.py: from django.apps import AppConfig from django.contrib.auth.models import User from django.db.models.signals import post_save, post_delete from django.db.models import Max, Count from .models import Player, PlayerStats, TotalLevels class BloxorsConfig(AppConfig): name = 'bloxors' def ready(self): MaxCurrentLevel = PlayerStats.objects.aggregate(max_levels=Max('level_no'))['max_levels'] PlayerCount = Player.objects.aggregate(count_players=Count('player_name', distinct=True))['count_players'] print(MaxCurrentLevel, PlayerCount) I read in the documentation that ready() gets called each time at the beginning of manage.py runserver but then why does nothing happen. Ideally I was expecting it to print the two values MaxCurrentLevel, PlayerCount. Can someone point out what I am doing wrong and help solve this? As always, I greatly appreciate your answers! -
Navbar inherited from base.html using Django templating doesn't render styles properly
I'm implementing a navbar and I wanted to use django templating for the DRY principle. The first picture is its appearance before templating, the second one is after templating. (https://imgur.com/a/FOEqKFB) How do I get the css files to render properly in the inherited html file? I thought it was a case of me not calling the CSS files in base.html (like this one: another similar answer), but I checked the code for base.html and I've already called the Bootstrap CDN for the navbar styles on the header. What went wrong in my code? This is the relevant code for the problem: base.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <title>{% block title %}Title{% endblock title %}</title> {% block head_favicon %} <link rel="icon" type="image/x-icon" href="/favicon.ico"> {% endblock head_favicon %} {% block head_meta %} {% block head_meta_charset %} <meta charset="UTF-8"> {% endblock head_meta_charset %} {% block head_meta_contentlanguage %} <meta http-equiv="X-UA-Compatible" content="ie=edge" value="en-US"> {% endblock head_meta_contentlanguage %} {% block head_meta_viewport %} <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0"> {% endblock head_meta_viewport %} {% endblock head_meta %} {% block head_css %} {% block head_css_site %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> {% endblock head_css_site %} {% block head_css_section %}{% endblock head_css_section %} {% block head_css_page … -
django post_save causing IntegrityError - duplicate entry
I need help to fix the issue IntegrityError at /admin/gp/schprograms/add/ (1062, "Duplicate entry '65' for key 'PRIMARY'") I am trying to insert a row into a table SchProgramForStates (whenever new entry gets added into a model SchPrograms) with two columns state_id (taking it from django session) and program_id trying to take it from SchPrograms model class . It works fine when I only save SchProgram table so I feel problem is with the below code. Please help me to fix this. @receiver(post_save, sender=SchPrograms, dispatch_uid="my_unique_identifier") def my_callback(sender, instance, created, *args, **kwargs): state_id = state_id_filter #its a global variable if created and not kwargs.get('raw', False): pfst_id = SchProgramForStates.objects.create(program_id=instance.program_id, state_id=state_id) pfst_id.save(force_insert=True) -
How to run Object_detection_image.py, which is outside my django project?
I am using windows 10 Django version: 2.1.1 with Python version: 3.5 I have my TensorFlow object detection API, that trained my images which is totally outside of my Django project. However, I created my Django project after that in the same environment that I had my TensorFlow object detection models. Both of them with the same (python version: 3.5). Before creating the Django webpage, I always needed to run my 'Object_detection_image.py' from anaconda prompt line, otherwise, I got an error. My question is: how I can specify my Object_detection_image.py path directory in the setting.py in Django using anaconda prompt line? When I write my directory like this: C:\tensorflow1\models\research\object_detection then how I can use anaconda prompt line in this path? because if I write it like this, it doesn't work. please help me. Thank you. -
Create or Update Update a many-many relationship in Django Graphene
I had an issue of not being able to update Models with foreign keys in python django, below is my rating class class Rating(Timestamp): user = models.ForeignKey(User, on_delete=models.CASCADE) movie = models.ForeignKey(Movie, on_delete=models.CASCADE) rating = models.FloatField( validators=[MinValueValidator(0), MaxValueValidator(10)]) def __str__(self): return f'{self.movie} : {self.rating}' class Meta: unique_together = (("user", "movie"),) I was trying to update it via the below mutation class AddEditRating(graphene.Mutation): rating = graphene.Field(RatingType) class Arguments: movie = graphene.ID() user = graphene.ID() rating = graphene.Float() def mutate(self, info, **arg): user = arg.get("user") movie = arg.get("movie") rating = arg.get("rating") obj, created = models.Rating.objects.update_or_create( user=user, movie=movie, defaults={"rating": rating} ) return AddEditRating(rating=obj) When i hit the mutation thought I get a warning that the user must be of UserType mutation { addEditRating(movie: 1, user: 3, rating: 9.7) { rating { id rating } } } Finally This is the error that i am getting "errors": [ { "message": "Cannot assign \"'3'\": \"Rating.user\" must be a \"User\" instance.", "locations": [ { "line": 2, "column": 3 } ], "path": [ "addEditRating" ] } ], Any help on this topic would be highly appreciated. also is there a better way to create update models? -
Why am I getting botocore.exceptions.ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden?
I'm getting this traceback when trying run run manage.py collectstatic as part of an AWS ElasticbeanStalk deploy using an S3 bucket. File "./src/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 162, in handle if self.is_local_storage() and self.storage.location: File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 216, in is_local_storage return isinstance(self.storage, FileSystemStorage) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/utils/functional.py", line 213, in inner self._setup() File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 491, in _setup self._wrapped = get_storage_class(settings.STATICFILES_STORAGE)() File "/opt/python/bundle/3/app/src/core/storage.py", line 64, in __init__ super(StaticStorage, self).__init__(*args, **kwargs) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 376, in __init__ self.hashed_files = self.load_manifest() File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 386, in load_manifest content = self.read_manifest() File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 380, in read_manifest with self.open(self.manifest_name) as manifest: File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/files/storage.py", line 33, in open return self._open(name, mode) File "/opt/python/run/venv/local/lib/python3.6/site-packages/storages/backends/s3boto3.py", line 464, in _open f = S3Boto3StorageFile(name, mode, self) File "/opt/python/run/venv/local/lib/python3.6/site-packages/storages/backends/s3boto3.py", line 72, in __init__ self.obj.load() File "/opt/python/run/venv/local/lib/python3.6/site-packages/boto3/resources/factory.py", line 505, in do_action response = action(self, *args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/boto3/resources/action.py", line 83, in __call__ response = getattr(parent.meta.client, operation_name)(**params) File "/opt/python/run/venv/local/lib/python3.6/site-packages/botocore/client.py", line 357, in _api_call return self._make_api_call(operation_name, kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/botocore/client.py", line 661, in _make_api_call raise error_class(parsed_response, operation_name) botocore.exceptions.ClientError: An … -
Display user`s protrait from model in template in django
I want to display the the user protrait of the user in the templates. models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to='user/%Y/%m/%d/', blank=True) views.py @login_required def dashboard(request): # Display all actions by default actions = Action.objects.exclude(user=request.user) following_ids = request.user.following.values_list('id', flat=True) if following_ids: # If user is following others, retrieve only their actions actions = actions.filter(user_id__in=following_ids) actions = actions.select_related('user', 'user__profile')\ .prefetch_related('target')[:10] return render(request, 'account/dashboard.html', {'section': 'dashboard', 'actions': actions}) tempate: <img src="{{ Profile.photo.url }} " height="40" width="40"/> -
How to resolve django admin error with 302 problems?
I am continuously getting error while trying to log in to django admin page. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). December 07, 2019 - 13:53:40 Django version 3.0, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: / [07/Dec/2019 13:53:42] "GET / HTTP/1.1" 404 2027 [07/Dec/2019 13:53:47] "GET /admin HTTP/1.1" 301 0 [07/Dec/2019 13:53:47] "GET /admin/ HTTP/1.1" 302 0 [07/Dec/2019 13:53:47] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1913 [07/Dec/2019 13:53:47] "GET /static/admin/css/login.css HTTP/1.1" 200 1233 [07/Dec/2019 13:53:47] "GET /static/admin/css/base.css HTTP/1.1" 200 16378 [07/Dec/2019 13:53:47] "GET /static/admin/css/responsive.css HTTP/1.1" 200 18052 [07/Dec/2019 13:53:47] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [07/Dec/2019 13:53:47] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692 [07/Dec/2019 13:53:47] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876 [07/Dec/2019 13:53:59] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 And after this it is automatically closing. -
Django template object not showing
So I've come across this weird thing. I can't pass data within the template unless it's within the forloop. for example.. I can pretty much print a variable just within a for loop but something outside a forloop is not showing up. {{listings.make}} <<<< This isn't printing {% for listing in listings %} <p>{{listing.make}}</p> <<<< This is printing {% endfor%} def search(request): queryset_list = Vehicle.objects.all() context = { 'listings': queryset_list } return render (request, 'mainapp/new_listing.html', context) class Vehicle(models.Model): year = models.CharField(max_length=4, choices=YEAR) make = models.CharField(max_length=50, default="") model = models.CharField(max_length=50, default="") version = models.CharField(max_length=50, default="") description = models.TextField(max_length=50, default="") def __str__(self): return self.make Any idea what is going on actually. As you can see I m using a function-based view. Thank you -
Comparing value from html to context
I need to compare a value (variable) extracted from a page to context. For example: Color is a dropdown selection. $(document).ready(function(){ $("#color").change(function() { var selected_color = $(this).val() ; {% if context_value == selected_color %} .. do something {% endif %} }); Is this possible ? If not, is there some solution for such case ? -
How can update many_to_many relational fields with bulk_update() method in Django?
How can I update many_to_many fields with the bulk_update method in Django? Code: get_user_model().objects.using('default').bulk_update( User.objects.using('default').all(), ('password','groups') ) Error: {ValueError}bulk_update() can only be used with concrete fields. -
How to display Django BooleanFields selected true in template?
everyone! I created a model object. This object has several boolean fields. # models.py class TeamCharacteristic(models.Model): team = models.ForeignKey('Teams',on_delete=models.CASCADE) power1 = models.BooleanField(null=True, blank=True) power2 = models.BooleanField(null=True, blank=True) power3 = models.BooleanField(null=True, blank=True) power4 = models.BooleanField(null=True, blank=True) power5 = models.BooleanField(null=True, blank=True) class Meta: verbose_name = 'Team style' verbose_name_plural = 'Teams style' def __str__(self): return "{} 's style".format( self.team, ) Some of them are right and others are wrong. I want to show only the fields that have the correct value in the template. How can I do this in a shorter way instead of checking each field individually? # views.py from django.shortcuts import render, get_object_or_404 from .models import Matches from denemee.apps.home.models import TeamCharacteristic def matches_details(request, page_id=None, team=None, **kwargs): m_detail = get_object_or_404(Matches, id=page_id) home_team_chr = get_object_or_404(TeamCharacteristic, team=m_detail.h_team) away_team_chr = get_object_or_404(TeamCharacteristic, team=m_detail.a_team) payload = { 'm_detail': m_detail, 'home_team_chr': home_team_chr, 'away_team_chr': away_team_chr } return render(request, 'match_detail.html', payload) -
Working with autofield and unique_constraint Django
My models.py of class app: Teacher and StudentInfo will store their respective details. from form.models import StudentInfo from teacherform.models import Teacher class ClassRoom(models.Model): standard = models.CharField(max_length=50) section = models.CharField(max_length=50) teacher = models.OneToOneField(Teacher, on_delete = models.CASCADE) class ClassRoomStudent(models.Model): classRoom = models.ForeignKey(ClassRoom, on_delete=models.CASCADE) rollNumber = models.AutoField() student = models.OneToOneField(StudentInfo, on_delete=models.CASCADE) I want to auto increment 'rollNumber' when I add new row to my ClassRoomStudents, but if the student is from different class then rollNumber count should reset it should start again. As different students can have the same roll number if they are from different classrooms. I am aware of unique constraint. But even after unique_constraint I am still not sure how my rollNumber will increment of different classrooms. Like won't it be continuosly incrementing the rollNumber number which will obviously be unique for different or same class ? -
Is there any way to filtering the queryset dynamicaly in django forms for a foreignkey correct?
I am creating a form for this model class SemAssign(models.Model): staff = models.ForeignKey(User, on_delete=models.CASCADE) semester = models.ForeignKey(Subject, on_delete=models.CASCADE, default=1) def __str__(self): return f'{self.staff.username}' and my forms.py looks like class SemAssignForm(forms.ModelForm): class Meta: model = SemAssign fields = ['staff','semester'] And i made a queryset based on a user-defined filter as in my views.py def assign_sem(request): if request.user.is_staff: dept = request.GET.get('department') sem = request.GET.get('semester') form=SemAssignForm(request.POST) #form.fields['staff'].queryset = User.objects.filter(is_staff=True, profile__Department=dept) #form.fields['semester'].queryset = Subject.objects.filter(sem=sem) if form.is_valid(): SemAssign=form.save() return redirect('dashboard') When the query works perfectly the form is validated as wrong. And if i don't make query the form is validated successfully. I'm sure i missing somewhere in querying the foreignkey set. Can anyone sought me that? My friend suggested me with modelformset, but that is not my scope. I just want to filter the fields of SemAssign models based on a GET request filter. -
How can add multiple database for tests in Django tests
Question: How can I add multiple databases for testing in Django? When I ran my test suits I got this Error: AssertionError: Database queries to 'mig' are not allowed in this test. Add 'mig' to path_to_test_suit.MigrationServiceTest.databases to ensure proper test isolation and silence this failure. Here are my PostgreSQL settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db_1_name', 'USER': 'db_1_user', 'PASSWORD': 'db_1_passwd', 'HOST': 'db_1_host', 'PORT': 'db_1_port', }, 'mig': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': db_2_name, 'USER': db_2_user, 'PASSWORD': 'db_2_passwd', 'HOST': 'db_2_host', 'PORT': 'db_2_port', }, } I use Django-nose for running test suits and use Django 2.2 -
Why password is not hashed when create user?
I've created a custom user model and in the register page if I set password on submit the browser do not let me to save because password is empty even if it is filled. In admin panel If I want to create a user on submit the password box remain in plain text. How can I fix that? # My user model class Crescatori(AbstractBaseUser, PermissionsMixin): """ Model Crescatori, folosit la inregistrarea utilizatorilor""" email = models.EmailField(unique=True, null=True, db_index=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) nume = models.CharField(max_length=40) prenume = models.CharField(max_length=50) telefon = models.CharField(max_length=25, blank=True, null=True) strada = models.CharField(max_length=254, blank=True, null=True) numarul = models.CharField(max_length=5, blank=True, null=True) judet = models.CharField(_('Judet/Sector'), max_length=128, blank=True, null=True) tara = models.CharField(max_length=150, blank=True, null=True) REQUIRED_FIELDS = ['nume', 'prenume', 'judet', 'tara'] USERNAME_FIELD = 'email' objects = UserManager() class Meta: verbose_name = "Crescator" verbose_name_plural = "Crescatori" def get_short_name(self): """ Returneaza numele mic al crescatorului""" return self.nume def get_full_name(self): """ Returneaza numele complet al crescatorului""" return '%s %s' % (self.nume, self.prenume) def __str__(self): return self.email # User Manager class UserManager(BaseUserManager): """ Manager crescatori/useri inregistrati""" def create_user(self, email, password, **extra_fields): """ Functie pentru crearea utilizatorilor""" if not email: raise ValueError(_('Adresa de email nu poate fi necompletata')) email = self.normalize_email(email) user … -
Django: Getting NoReverseMatch While Submitting the Form, URL has Slug
I am learning Django by building an application, called TravelBuddies. It will allow travelers to plan their trip and keep associated travel items (such as bookings, tickets, copy of passport, insurance information, etc), as well as create alerts for daily activities. The application will also able to update local information such as weather or daily news to the traveler. Travelers can also share the travel information with someone or have someone to collaborate with them to plan for the trip. I am facing a problem. I have a form like this: When I click on the Submit button, I am supposed to be redirected to http://127.0.0.1:8000/triplist/johor-bahru/. Instead, I get this error: NoReverseMatch at /addactivity/ Reverse for 'activity' with no arguments not found. 1 pattern(s) tried: ['triplist/(?P<slug>[-a-zA-Z0-9_]+)/$'] Request Method: POST Request URL: http://127.0.0.1:8000/addactivity/ Django Version: 3.0 Exception Type: NoReverseMatch Exception Value: Reverse for 'activity' with no arguments not found. 1 pattern(s) tried: ['triplist/(?P<slug>[-a-zA-Z0-9_]+)/$'] Here are my codes in models.py inside Trips folder: from django.contrib.auth.models import User from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Trip(models.Model): trip_name = models.CharField(max_length=100) date = models.DateField() planner_name = models.CharField(max_length=100) add_coplanner = models.ManyToManyField(User) trip_description = models.CharField(max_length=1000, default='null') slug = models.SlugField(max_length=150, default='null') … -
Reverse for 'editPost' with arguments '('',)' not found. 1 pattern(s) tried: ['editPost/(?P<postslug>[^/]+)/$']
I am getting this error inside below template {% for post in post_queryset %} <div class="card-body"> <div class="date">{{ post.created_date }}</div> <div class="title"> {{ post.text }} {{ post.slug }} <a href="{% url 'editPost' post.slug %}" ><i class="fa fa-edit"></i></a> <a onClick="delete_post('{{post.slug}}','{{post_id}}')"><i class="fa fa-trash-o"></i></a> </div> </div> {% endfor %} I am getting the error in this line <a href="{% url 'editPost' post.slug %}" ><i class="fa fa-edit"></i></a> I displayed {{post.slug}} just before this line and commenting the link line just to make sure post.slug has some content. It looks post.slug has valid slug information. I also tried passing just some string instead of post.slug like below then it was working <a href="{% url 'editPost' 'some_string' %}" ><i class="fa fa-edit"></i></a> my urls.py is like below path('editPost/<postslug>/',views.editPost, name='editPost') Can someone help me to find the error? -
Cannot add path to package
I have download django-todo for my website, I am writting some function on the view but i am not able to add path to the urls.py even if it is correct. For example : from django.conf import settings from django.urls import path from todo import views from todo.features import HAS_TASK_MERGE app_name = "todo" path("add_list/", views.add_list, name="add_list"), path("add_listreccurence/", views.add_listreccurence, name="add_listreccurence"), The first one come with the package, the second is mine. It is exactly on the same file, with the same path but I cannot import it, it says : AttributeError: module 'todo.views' has no attribute 'add_listreccurence' Could you help me ? Thanks -
Where we should change initial data in the serializer?
Questions: Where I should change initial_data in the serializers? Is it a recommended way to change initial_data in the validate_field_name() methods? should validate_field_name methods return something? Code: from django.contrib.auth import get_user_model from rest_framework import serializers class MySerializer(serializers.ModelSerializer): def validate_owner(self, owner_id): try: return get_user_model().objects.get(owner_id=owner_id) except get_user_model().DoesNotExist or get_user_model().MultipleObjectsReturned: return owner_id If I don't change initial_data in validate_field_name methods, I'll fetch the data twice. For example: from django.contrib.auth import get_user_model from rest_framework import serializers from rest_framework.exceptions import ValidationError class MySerializer(serializers.ModelSerializer): def validate_owner(self, owner_id): try: get_user_model().objects.get(owner_id=owner_id) except get_user_model().DoesNotExist or get_user_model().MultipleObjectsReturned: raise ValidationError('User does not exists.') def create(self, validated_data): validated_data['owner'] = get_user_model().objects.get(owner_id=validated_data['owner_id']) # create instance -
How to make python in template to enter if condition only once
I have a some products and some pictures of in different models. While displaying all products I need to display 1 image in the table. I tried this: template : <tr class="check_items_row"> <td style="width:20px;"> <div class="checkbox lgi-checkbox m-t-5"> <label> <input class="check check_item" type="checkbox" value="{{instance.pk}}" name="delete_item"> <i class="input-helper"></i> </label> </div> </td> <td><a href="{% url 'products:product' pk=instance.pk %}">{{instance.auto_id}}</a></td> <td>{{instance.category}}</td> <td>{{instance.subcategory}}</td> <td>{{instance.name}}</td> {% for item in product_gallery %} {% if item.product == instance and test == 0 %} <td><img src="{{item.image.url}}" alt="Image" style="width:100px;"/></td> {% endif %} {% endfor %} </tr> {% endfor %} views.py def products(request): instances = Product.objects.filter(is_deleted=False).order_by('auto_id') product_gallery = ProductGallery.objects.all() context = { 'title': "Product ", 'instances' : instances, "product_gallery": product_gallery, "test": 0, } return render(request,'products/products.html',context) in my thoughts I just need to change the value of test in template if it enters the if condition once . This code is displaying all images of a product. I just need one image of every product. Here i will need to change the value inside if condition and reset to 0 after the for loop -
Django Signal that provides access to response of a request?
So far in our code we have implemented Django built-in signals for handling user login, logout, and failed login as well as db actions with pre-save, post_save and post_delete signals. I am looking to maintain consistency by performing some operations on the http response after a request has been made using signals. However, I do not see any built-in signal that grants access to the response object. I am aware of the request_finished signal but this does not seem to provide access to the response object. I have successfully achieved what I need using Django's process_response function in middleware but was wondering if there was a way I could maintain consistency and use a signal here as well. We are using Django 2.2 and DRF 3.8.2 -
AttributeError: '_shims' object has no attribute 'InstallRequirement'
I'm sorry if I didn't speak well in English because I'm not good at English. Specifically, the environment was being constructed with reference to this article. The error occurred when 「pipenv install gunicorn」 command was executed to introduce “gunicorn”. The execution result of 「pipenv install gunicorn」 is as follows. /home/app-user/.local/python/lib/python3.7/site-packages/pipenv/vendor/attr/_make.py:618: RuntimeWarning: Missing ctypes. Some features like bare super() or accessing __class__ will not work with slots classes. set_closure_cell(cell, cls) Installing gunicorn… Traceback (most recent call last): File "/home/app-user/.local/python/bin/pipenv", line 10, in <module> sys.exit(cli()) File "/home/app-user/.local/python/lib/python3.7/site-packages/pipenv/vendor/click/core.py", line 764, in __call__ return self.main(*args, **kwargs) File "/home/app-user/.local/python/lib/python3.7/site-packages/pipenv/vendor/click/core.py", line 717, in main rv = self.invoke(ctx) File "/home/app-user/.local/python/lib/python3.7/site-packages/pipenv/vendor/click/core.py", line 1137, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/app-user/.local/python/lib/python3.7/site-packages/pipenv/vendor/click/core.py", line 956, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/app-user/.local/python/lib/python3.7/site-packages/pipenv/vendor/click/core.py", line 555, in invoke return callback(*args, **kwargs) File "/home/app-user/.local/python/lib/python3.7/site-packages/pipenv/vendor/click/decorators.py", line 64, in new_func return ctx.invoke(f, obj, *args, **kwargs) File "/home/app-user/.local/python/lib/python3.7/site-packages/pipenv/vendor/click/core.py", line 555, in invoke return callback(*args, **kwargs) File "/home/app-user/.local/python/lib/python3.7/site-packages/pipenv/vendor/click/decorators.py", line 17, in new_func return f(get_current_context(), *args, **kwargs) File "/home/app-user/.local/python/lib/python3.7/site-packages/pipenv/cli/command.py", line 254, in install editable_packages=state.installstate.editables, File "/home/app-user/.local/python/lib/python3.7/site-packages/pipenv/core.py", line 1909, in do_install pkg_requirement = Requirement.from_line(pkg_line) File "/home/app-user/.local/python/lib/python3.7/site-packages/pipenv/vendor/requirementslib/models/requirements.py", line 1068, in from_line if isinstance(line, pip_shims.shims.InstallRequirement): File "/home/app-user/.local/python/lib/python3.7/site-packages/pipenv/vendor/pip_shims/shims.py", line 254, in __getattr__ return super(_shims, self).__getattribute__(*args, **kwargs) AttributeError: '_shims' object has no attribute 'InstallRequirement' We … -
Sass_Processor and Compressor Are Not Creating .css File with Django 2.2, No Errors
I recently decided to switch my project over to sass as I like the DRY-ness of it. To get set up, I followed these two sites: https://www.accordbox.com/blog/how-use-scss-sass-your-django-project-python-way/ and https://terencelucasyap.com/using-sass-django/ It seemed to be working the first time around, but then I made more changes to the .scss file and tried to recompile, but no changes were made. I found the generated .css file and deleted it, thinking it might regenerate it, but not it doesn't seem to be doing anything when I compile. I have tried moving around where the sass_processor is looking, and where to save it to, but now I'm not sure what the problem is. I am completely new to sass, and fairly familiar with Django so I'm sure this is a simple problem I am missing. I have been unable to find any questions related, as mine does not throw any errors.. there just isn't a file? When I run ./manage.py compilescss I get Successfully compiled 1 referred SASS/SCSS files. then I collect the static files and runserver but inside of the chrome inspector, I do not see a css file where I normally would and none in my directory either. setting.py """ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) … -
Render date for yesterday with a link
I have a workspace where users can add note, they can pick a date I am trying to create 2 links, one for yesterday, one for tomorrow. Right now I am using a calendar and it is fine, but I would like to create 2 quick links that send them to the note for yesterday. So i have a code like that : def WorkspaceYesterday(request): yesterday = datetime.now() - timedelta(days=1) yesterday.strftime('%m%d%y') But i dont know how to render it in my template with a link. Thank you