Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I need to display statistics as a number
I just started learning django and ran into a problem when using def str(self): return self.timetable the date in the admin panel is displayed as numbers, but it gives the error ''str returned non-string (type datetime.time)'' when replacing str with something else, the time is displayed like this -
Django - what is wrong with my If statement?
Good afternoon all, I inserted an if statement in my template - I only want the form to appear if the product category is "Champagne". For some reason, the product does not appear for champagne products. Here is the code Models.py CATEGORY=( (1,'Rum'), (2,'Gin'), (3,'Whisky'), (4,'Champagne'), (5,'Others'), ) class Product(models.Model): name = models.CharField('Product Name', max_length=120, null=True) category = models.IntegerField(choices=CATEGORY, default=0) description = models.TextField(blank=True, null=True) price = models.DecimalField(null=True, max_digits=6, decimal_places=3) image_url= models.URLField('Image Web Address', blank=True) product_url = models.URLField('Product Web Address', blank=True) class Meta: db_table='Product' def __str__(self): return str(self.name) HTML {% if product.category == 'Champagne' %} <div class="d-flex flex-column mt-4"> <a class="btn btn-outline-secondary btn-sm" href="{% url 'ElderFlowerReview' product.id %}">Tasting Notes</a> </div> {% endif %} Forms.py class DrinkForm(ModelForm): class Meta: model = Product fields = ('name','category', 'description') labels ={ 'name': '', 'category': '', 'description': '', } widgets = { 'name': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter name'}), 'category': forms.Select(attrs={'class':'form-control', 'placeholder':'Enter category'}), 'description':forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter description'}), } -
Docker image ran for Django but cannot access dev server url
Working on containerizing my server. I believe I successfully run build, when I run docker-compose my development server appears to run, but when I try to visit the associated dev server URL: http://0.0.0.0:8000/ However, I get a page with the error: This site can’t be reachedThe webpage at http://0.0.0.0:8000/ might be temporarily down or it may have moved permanently to a new web address. These are the settings on my Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR C:/Users/15512/Desktop/django-project/peerplatform COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . ./ EXPOSE 8000 CMD ["python", "./manage.py", "runserver", "0.0.0.0:8000", "--settings=signup.settings"] This is my docker-compose.yml file: version: "3.8" services: redis: restart: always image: redis:latest ports: - "49153:6379" pairprogramming_be: restart: always depends_on: - redis command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" env_file: - ./signup/.env - ./payments/.env - ./.env build: context: ./ dockerfile: Dockerfile ports: - "8000:8001" container_name: "pairprogramming_be" volumes: - "C:/Users/15512/Desktop/django-project/peerplatform://pairprogramming_be" working_dir: "/C:/Users/15512/Desktop/django-project/peerplatform" This is the .env file: DEBUG=1 DJANGO_ALLOWED_HOSTS=0.0.0.0 FYI: the redis image runs successfully. This is what I have tried: I tried changing the allowed hosts to localhost and 127.0.0.0.1 I tried running the command python manage.py runserver and eventually added 0.0.0.0:8000 When I run … -
How to create a modelform and save object in Django?
all! models.py: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class UserChoice(models.Model): user_choice = models.ForeignKey(Choice, on_delete=models.CASCADE) def __str__(self): return self.user_choice views.py: def index(request): question_list = Question.objects.all() context = {'question_list': question_list} return render(request, 'polls/index.html', context) index.html.py: <form method="post""> {% csrf_token %} {% for question in question_list %} <h3>{{question.question_text}}</h3> <select hidden="" name="form-{{ forloop.counter0 }}-question" id="id_form-{{ forloop.counter0 }}-question"> <option value="{{question.id}}" selected="">{{question.question_text}}</option> </select> {% for answer in question.choice_set.all %} <label for="id_form-{{ forloop.counter0 }}-answer"> <input type="radio" name="form-{{ forloop.parentloop.counter0 }}-answer" id="id_form-{{ forloop.counter0 }}-answer" value="{{answer.id}}"> {{answer.choice_text}} </label> <br> {% endfor %} {% endfor %} <br /> <br /> <input type="submit" value="Submit"> </form> Question: How to save user choice using UserChoice model per each question? How to create such modelform? Is my UserChoice model is good for storing these informations? P.s. I know how to create simple ModelForm, but here my little knowledge about Django stopped me :). For now, I have no idea how to create this form, I read about modelformset_factory, but did not understand...( Any help appreciated! -
I'm trying to send email with Django
I'm trying to send email with Django but i keep getting SMTPConnectError ErrorMessage [Views.pysettings.py -
Placement of {% if form.errors %} on login template
I'm not sure if I'm allowed to ask these types of questions here since it's not a problem per say, so please let me know. But I was wondering for the login.html template on Django: {% extends 'learning_logs/base.html' %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} <form method = "post" action="{% url 'login' %}"> {% csrf_token %} {{ form.as_p }} <button name = "submit">log in</button> <input type="hidden" name="next" value="{% url 'learning_logs:index' %}" /> </form> {% endblock content %} How come it checks for the form.errors before the it even processes the form? Thanks for any help on this question. -
Django APITest case not returning anything in get request
I am developing an API with Django, and I also want to test it, but I am having some trouble doing that. I need to test that to a given URL, what is returned is what I expect, and I want to do so with APITestCase of django rest framework. The endpoint is something similar: http://localhost:5000/api/v1/rest_of_url/ When I type it in the browser, it return something similar: {"count": 1, "next": null, "previous": null, "results": [{"stuff": 3, "stuff2": "adf", "stuff3": "asdf", "stuff4": "ff"}]} So, to test that I wrote the following code in Django: class TargetApiTestCase(APITestCase): def test_get(self): response = self.client.get("/api/v1/rest_of_url/", format='json') print(response) print(response.content) print(response.status_code == status.HTTP_200_OK) As response I get the following output from the prints statements: <JsonResponse status_code=200, "application/json"> b'null' True But I should get some data, to check. I know that after that I have to query the db to check and use self.assertEqual, but for now my problem is retrieving data via get Maybe it is only a problem of settings. I tried require responde.data, but it responded with an error. Please, can someone help me? Thank -
How to check if a object has ManyToMany reference in a queryset django?
I have these models in my django project class Question(models.Model): heading = models.CharField(max_length=300) description = models.TextField() class Profile(models.Model): name = models.CharField(max_length=100,null=False,blank=False) completed = models.ManyToManyField(Question) I'm trying to find a optimized way for fetching a list of questions for user it should with whether they have completed it or not. I think it can be done with these quersets:- all_questions = Question.objects.all() completed_questions = Question.objects.filter(profile = profile_instance) where profile_instance is a profile object. Then we can loop through the all_questions and check whether they also exist in completed_questions, but i am not sure whether this is optimized for pagination. I'm using Django-Rest Framework pagination. -
How to write changes in fields to LogEntry?
I had a task to create action which will change status of object(s). Action is already create. Code for example: class MyAdmin(admin.ModelAdmin): actions = ['decline_status', ] def decline_status(self, request, queryset): decline_status = constants.DECLINED.value objects_to_decline = queryset.exclude(status=decline_status).filter(status=decline_status) if objects_to_decline.count() > 0: objects_to_decline.update(status=decline_status) But now I have a problem: I need to write changes which were called by decline_status action to LogEntry table. Nothing is happend when i use LogEntry.objects.create(different_kwargs). And I'm trying to use self.log_change(request, obj, some_change_message), but changes appear only on the main page of admin in the window: recent actions window I need to write changes to LogEntry like they are written after default action delete_selected. Can you help me? -
How to update M2M field related data attributes in Django
I want to update the vote value of each candidate which is related with m2m field of specific Constituencies. I have Constituencies update function where user update the Constituencies but i my case i also want to update the candidates vote value which is coming from object in object.candidates.all class Candidates(models.Model): name = models.CharField(max_length=100) votes = models.PositiveBigIntegerField(default=0) class Constituencies(models.Model): candidates = models.ManyToManyField(Candidates) views.py def constituency_detail(request, pk): obj = get_object_or_404(Constituencies, id=pk) form = ConstituenciesForm(request.POST or None, instance=obj) if request.method == 'POST': pass template.html <h5>{{ object }}</h5> {% for object in object.candidates.all %} <h5>{{ object }}</h5> {{ object.votes }} as input field {% endfor %} -
Django: Prepopulate extra fields in a Formset with a ManyToMany Model
I have two models with a ManyToMany (M2M) relationship. In order to have extra fields on the M2M Model, I defined a through= model. I tried setting up a inlineformset_factory, using parent=ChildModel and model=ParentModel.parent_child.through as described in this thread pendant to inline formsets for many-to-many relations. But it did not solve my issue. How can I access (i.e. prepopulate) and update the extra fields of the M2M model, when using formsets? models.py class ParentModel(models.Model): name = model.CharField() parent_child = model.ManyToManyField(ChildModel, through='ParentChildModel') class ChildModel(models.Model): name = model.CharField() class ParentChildModel(models.Model): parent = models.ForeignKey(ParentModel, on_delete=models.CASCADE) child = models.ForeignKey(ChildModel, on_delete=models.CASCADE) extra_field_1 = models.CharField() forms.py class ChildForm(forms.ModelForm): class Meta: model = ChildModel fields = '__all__' ChildFormset = modelformset_factory(ChildModel, form=ChildForm, extra=0, can_delete=True, can_order=True, ) -
Can't load local images with HTML
I am developing a simple site with Django, and wanted to load some images locally to some pages. But it doesn't load for some reason. I know there are similar questions, and from what i understand; a-) It can be a directory problem, html file and img file is in the same directory. Still doesn't work; directory, and the html file. I tried moving the img.jpg to the templates/images directory and try <img src="images/img.jpg" height="400" width="374"> within the html file but that didn't work either. b-) It could be a typo, but from the images up there that shouldn't be the case either. c-) Files could be corrupted, I can open the image with browsers and tried using different images too. d-) Img could be restricted, but that is not the case either. I think. Trying to fix this for two days now, thought for some reason usage of extend or block might cause some problems and tried without them, still no good. and as i said its only a problem with local files. Can use files with direct link. Thanks in advance, sorry for any problems with the format. -
Recipient variables have no value in django-anymail and Mailgun
I'm trying to add some metadata to emails, but never receive it in logs and in webhooks. Here is what I'm doing: recipient_variables = {recipient:metadata} msg.merge_metadata = recipient_variables This is how the msg.merge_metadata looks like: {'EMAIL': { 'submission_id': 'ID'}} This is what data looks like in Mailgun web logs: "user-variables": { "submission_id": "%recipient.v:submission_id%", }, And webhook just receives: {'submission_id': ''} I also tried msg.extra_headers["X-Mailgun-Recipient-Variables"] = json.dumps(recipient_variables) It also hasn't changed anything much, but webhook now receives this instead> {'submission_id': '%recipient.v:submission_id%'} Am I doing anything wrong? The whole process seems to be pretty straightforward. — Anymail version — 8.6 ESP (Mailgun, SendGrid, etc.) — Mailgun django 4.0.4, requests 2.27.1, python 3.10 Settings: ANYMAIL = { "MAILGUN_API_KEY": "", "MAILGUN_SENDER_DOMAIN": '', "MAILGUN_API_URL": "https://api.eu.mailgun.net/v3", "WEBHOOK_SECRET" : "", "MAILGUN_WEBHOOK_SIGNING_KEY": "", } -
Pagination with ordering and other get variables
In a class based ListView, while rendering i want to dynamically change the no of items shown per page and the sorting order of those items. I referred to this question and the answer by skoval00 works for me when i change the ordering and change the pages. But as soon as i change the no of items per page, my ordering is lost. For ex: my generic view links to http://127.0.0.1:8000/marketplace/. If i set the pagination to 10 items per page. The url changes to http://127.0.0.1:8000/marketplace/?paginate_by=10 But now if i change my ordering too, i expect something like http://127.0.0.1:8000/marketplace/?paginate_by=10&ordering=end_date but i get http://127.0.0.1:8000/marketplace/?ordering=end_date And the pagination changes to the default value. Same thing happens vice-versa. If i order first and then change pagination, then i lose the ordering once the pagination changes. How do i preserve the first argument while adding the second one? Here is the relevant class in views.py class CatalogueListView(ListView): model = Catalogue context_object_name = 'catalogues' template_name = 'marketplace/catalogue_list.html' paginate_by = 5 ordering = ['end_date'] def get_queryset(self): if self.request.GET.get('ordering'): ordering = self.request.GET.get('ordering') else: ordering = 'end_date' query_set = Catalogue.objects.filter(admin_approved=True, end_date__gt=timezone.now()).order_by(ordering) return query_set def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.GET.get('paginate_by'): context['paginate_by'] = self.request.GET.get('paginate_by') else: context['paginate_by'] = … -
Display 1 when no data is exist in database
I am trying to generate incremental id whenever I am adding new data in my model. here I am getting the the next number whenever I am adding new data. but If there is no any data in my table its giving me error. 'NoneType' object has no attribute 'tax_id' Here is my code views.py def tax_settings(request): latest_id = (Tax_Settings.objects.last()).tax_id+1 if request.method == 'POST': tax_id = latest_id name = request.POST['tax_name'] tax_percentage = request.POST['tax_percentage'] tax_details=Tax_Settings.objects.create(tax_id=tax_id, name=name, tax_percentage=tax_percentage) tax_details.save() next_id = (Tax_Settings.objects.last()).tax_id+1 return render(request,"settings/tax-settings.html",{"latest_id":next_id}) else: return render(request,"settings/tax-settings.html",{"latest_id":latest_id}) html <input type="text" class="form-control" placeholder="{{latest_id}}" name="tax_id" disabled> which condition I can give to my latest_id if data(tax_id) not exists? -
To manage user authentication on multiple website through SSO
Created an account on Onelogin which act like Identity Provider (IDP) Created a connector app for the website 1 Added onelogin SSO configuration for the website 1 Added the onelogin auth in the website 1 Added a link to the website 2 in the authenticated pages of the website 1 After onelogin auth in website 1, I wanted to know what are the next steps. -
Does Django Optimize the query if it gets run multiple times with the same filter?
class MyModel(models.Model): task_id = models.UUIDField() task_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name='+') task = GenericForeignKey('task_type', 'task_id') ..... @property def task_description(self): if self.task_status === 'pending': return 'Pending Task' else: task = Task.objects.filter(self.task_id).first() return task.name or '' In case self.task_status is not pending, then for each task, it looks up the Task table for the name. My Question. suppose task ids [1,2,3,3,3] then what will be the queries that get run ? is this N+1 problem ? for id 1, it checks the Task table where id = 1. for 2 3 it does too. But for id == 3, does it look up the table 3 times with same filter like where id = 3 ? -
How can I deploy code to production when I am running celery, redis, django with docker compose?
I am running celery, Redis, Django, and flower containers with docker compose. The docker-compose.yml file is similar to this tutorial. The whole app can run very well. The problem is when I change the code and deploy it to production. I found that the code was often not updated and this caused errors. For example, I try to change the celery task code or add new tasks. The updated tasks cannot be deployed From restarting the workers, I tried to run the commands: celery multi start 1 -A proj -l INFO -c4 --pidfile=/var/run/celery/%n.pid celery multi restart 1 --pidfile=/var/run/celery/%n.pid kill -HUP $pid But the task is not updated after my testing. The task is still loading the old code. How can I deploy code to production? Should I restart the container with? docker-compose restart celery From the celery docs, it says that: For production deployments you should be using init-scripts or a process supervision system (see Daemonization). The Daemonization is completely not related to docker. I don't understand how Daemonization is related to deployment with docker / docker compose. Actually I don't understand why Daemonization is related to deployment from the official docs. -
Wagtail add bulk actions to ModelAdmin IndexView
I would love to add custom bulk actions to a ModelAdmin index view. Is that possible already or a feature request potentially? The ModelAdmin module’s IndexView is great to filter a larger number of pages. I would love to select a bunch of these pages and start a custom bulk action like "publish", "unpublish" or "add to another page". Alternatively I could try to add more attributes/columns to the page Explorer, which already offers these bulk actions. But the ModelAdmin module was added to Wagtail to do exactly that. So I think, that adding bulk actions to the ModelAdmin is the way to go. -
Want to show Fetched Data on Doughnut Chart with Percentage label in JavaScript
I am new at JavaScript. I want to display counts of rows on Doughnut Chart dynamically. Data is fetching dynamically in form of table. key: "results_callback", value: function results_callback(data) { data = data.tasks; if (Object.keys(data).length == 0) { $("div#no_more_results").show(); $("div#no_more_results").html("<h6 style='color: #9c0a0d;'>No More Results</h6>"); this.empty_results = true; } else { $("table#recent thead").append("<tr style='color: #840a0c!important;'> <th>H1</th> <th>H2</th> <th class='text-center'>H3</th> <th class='text-center'>H4</th> <th class='text-right'>H5</th> <th class='text-right'>H6</th> </tr>"); console.log(analysis.length) data.forEach(function (analysis, i) this is the code where data is fetching and providing the data in form of table. Now what I have done. I have used the localstorage.setItem through ID in Index.html(1) Page <script> var table = document.getElementById("recent"); //var totalRowCount = table.rows.length; // 5 var tbodyRowCount = table.tBodies[0].rows.length; // 4 alert("total no of files are:" +tbodyRowCount) console.log(tbodyRowCount) //console.log(totalRowCount) </script> <script> var x = { count: [tbodyRowCount], //count: [totalRowCount] }; localStorage.setItem("tbodyRowCount", count) //localStorage.setItem("totalRowCount", count) //localStorage.getItem("tbodyRowCount") </script> Here is the code to create a table in index.html(1) <table id="recent" class="table table-striped table-responsive recent_table"> <thead ></thead> <tbody ></tbody> <tfoot ></tfoot> </table> Here is the code to fetch data in index.html(2) where I am calling the data on Doughnut Chart <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script type="text/javascript" src="https://unpkg.com/chart.js-plugin-labels-dv/dist/chartjs- plugin-labels.min.js"></script> <!--<srcipt src = "https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin- datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></srcipt> --> <script> var tcount = … -
Organise selection from cache only (no database hit is permitted)
Django==4.0.5 django-cachalot==2.5.1 Model: class General_Paragraph(models.Model): treaty = models.ForeignKey('treaties.Treaty', on_delete=models.PROTECT, db_index=True) identifier = models.CharField(max_length=100, blank=False, null=False, db_index=True, unique=True) Cash warming: @admin.action(description='Warm cache up') def warm_up(modeladmin, request, queryset): MODELS_AND_APPS = { ... "General_Paragraph": "paragraphs_of_treaties", ... } for model_name in MODELS_AND_APPS: current_model = apps.get_model(app_label=MODELS_AND_APPS[model_name], model_name=model_name) all_instances = current_model.objects.all() list(all_instances) # The very warming the cache up. Problematic code: def get_texts_in_languages(treaty, paragraph_identifier, party): general_paragraph = General_Paragraph.objects.get(treaty=treaty, identifier=paragraph_identifier) SQL: SELECT ••• FROM "paragraphs_of_treaties_general_paragraph" WHERE ("paragraphs_of_treaties_general_paragraph"."identifier" = 'Par 1' AND "paragraphs_of_treaties_general_paragraph"."treaty_id" = 1) LIMIT 21 What I need I use Memcached. As this is reading, I don't want any reading from the database. Everything should be requested from the cache. As far as I have understood, .objects.get(treaty=treaty, identifier=paragraph_identifier) will not be covered by Django Cachalot. Could you help me write a code that will not hit the database. Any warming ups of the cache are possible. I have enough resourses at my hosting. My problem is that I can't understand what to do: whether some elegant query is possible here or I will have to loop over all the cache? -
NoReverseMatch: Reverse for '' with arguments '('',)' not found
I'm trying to pass the intern's id through the django url but this error is occurring. Internal Server Error: /partiu-estagio/dashboard Traceback (most recent call last): File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "D:\SEC\codigoWeb\DesenvolvimentoSec\sistemaSec\home\views.py", line 61, in dashboard_partiu_estagio return render(request, 'home/PAES_dashboard.html',dados) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\loader_tags.py", line 62, in render result = block.nodelist.render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\defaulttags.py", line 312, in render return nodelist.render(context) File "C:\Users\etsva\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 938, in render bit … -
Django app with Memcached using Dockerfile only
I need to add memcached in my Django app, I tried the same with docker-compose but I don't want to use docker-compose, instead I need to use Dockerfile. Is there anyway for it -
Unable to create process
I updated my python version and when I try to run server on prompt for django I get this error. Unable to create process using 'C:\Users\ALFRED\AppData\Local\Programs\Python\Python311\python.exe manage.py runserver': The system cannot find the file specified. -
Activating virtual env
I made a virtual environment ,I can activate it in command prompt, but it doesn't activate with my_venv2\Scripts\activate.bat and I cant activate it in pycharm's terminal