Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any better way to do like history.back() in django backend?
In Django, I have "form view(GET)" and "action view(POST)" If there is a validation error or any other error in action view, I want browser to go back to the previous form page with the input data whote by the user remains. I tried: At first, I used return redirect(request.META.get('HTTP_REFERER')). This code goes back to the previous page well, but all the input fields became empty. And now I am using return HttpResponse("<script>history.back();</script>") this code. This works very well. but It looks weird sending javascript response. What I was expected was like return redirect.back()(with like HTTP 301 or 30X status code) I was wondering if there is any better way or a proper way like officially provided by Django. -
Normalising Data with Django
I have several datasets in csv formats and instructions are given to normalise them for Django REST API development with sqlite3. I am very new to databases and django, and having some difficulties to organise the tables. I have 3 csv datasets. First dataset - protein sequence. Two columns with 'ProteinID' and 'protein_sequence' Second dataset - protein domain assignemtns. 'ProteinID', 'Organism_taxa_id', 'Organism_clade', 'Organism_genus_species', 'domain_description', 'domain_id', 'domain_start_coord', 'domain_end_coord', 'length_of_protein' Third dataset - pfam description. Two columns with 'domain_id' and 'domain_description' I am creating an application where users can search for protein data. Conditions are: Organisms HAVE MANY Proteins Organisms HAVE A Genus name Organisms HAVE A Species name Proteins HAVE MANY domains Proteins HAVE ONE sequence Domains HAVE ONE pfam domain ID May I know how I can model the tables for efficient querying? And I have rest_specification_and_example REST Specification: POST http://127.0.0.1:8000/api/protein/ - add a new record GET http://127.0.0.1:8000/api/protein/[PROTEIN ID] - return the protein sequence and all we know about it http://127.0.0.1:8000/api/protein/A0A016S8J7 returns { "protein_id": "A0A016S8J7", "sequence": "MVIGVGFLLVLFSSSVLGILNAGVQLRIEELFDTPGHTNNWAVLVCTSRFWFNYRHVSNVLALYHTVKRLGIPDSNIILMLAEDVPCNPRNPRPEAAVLSA", "taxonomy": { "taxa_id": 53326, "clade": "E", "genus": "Ancylostoma", "species": "ceylanicum" }, "length": 101, "domains": [ { "pfam_id": { "domain_id": "PF01650", "domain_description": "PeptidaseC13family" }, "description": "Peptidase C13 legumain", "start": 40, "stop": 94 }, { … -
TypeError: create_sql() got an unexpected keyword argument 'concurrently'
I'm trying to add a GIN Index to my usernames on my user model for better trigram similarity search: class User(models.Model): ... class Meta: ordering = ["-created_at"] indexes = [ UpperGinIndex( fields=["username"], name="user_username_gintrgm", opclasses=["gin_trgm_ops"], ) ] And when I run python manage.py makemigrations, no error is produced: # Generated by Django 3.2.7 on 2023-01-06 03:00 from django.db import migrations import myproj.db class Migration(migrations.Migration): dependencies = [ ... ] operations = [ migrations.AddIndex( model_name="user", index=myproj.db.UpperGinIndex( fields=["username"], name="user_username_gintrgm", opclasses=["gin_trgm_ops"], ), ), ] However, when I run python manage.py migrate, I get this error which doesn't seem to have any easy-to-google fixes. I've already tried updating Django to 3.2.16: File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/operations/models.py", line 761, in database_forwards schema_editor.add_index(model, self.index) File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/backends/postgresql/schema.py", line 218, in add_index self.execute(index.create_sql(model, self, concurrently=concurrently), params=None) TypeError: create_sql() got an unexpected keyword argument 'concurrently' Any ideas on how to fix this? -
where in my script is causing my csv data to not line up in the table?
After building my website, I noticed some slight details were off when returning values from my GETs. For reference, I have to create my GET to return these values. NOTE: "id" here is sequential the primary key value generated by django for the table that holds the domain data GET http://127.0.0.1:8000/api/pfams/[taxa_id] - return a list of all domains in all the proteins. GET should return: http://127.0.0.1:8000/api/pfams/55661 [ { "id": 88896, "pfam_id": { "domain_id": "mobidb-lite", "domain_description": "disorder prediction" } }, { "id": 88891, "pfam_id": { "domain_id": "PF00307", "domain_description": "Calponinhomology(CH)domain" } }, { "id": 88892, "pfam_id": { "domain_id": "PF00415", "domain_description": "Regulatorofchromosomecondensation(RCC1)repeat" } }, ... ] However, my current application only prints the following in REST { "id": 37922, "pfam_id": { "domain_id": "PF00115", "domain_description": "CytochromeCandQuinoloxidasepolypeptideI" } } I'm assuming something in my script went wrong or I linked my relationships badly and I printed it to the wrong row since my values dont lie up with the reference. I'll link below the snippet of how the CSV file looks - if anyone could point me towards the right direction, it would mean a lot. Thanks in advance! (my serializers, urls, and views are set up fine so I'll leave those out) Here's my … -
(Python) how to use APIs with Django rest framework, generating endpoints which can call in my existing website
ultimate goal: change mySQL data can result changed the website data (demo pic) The original website and MySQL before change (demo pic) The idea result pic (Python) How to Connect/Integrate Django with website the last discussion came up one of the way: using the API with Django rest framework, generating endpoints which can call in my existing website the goal is still wish to connect with Django, ps. I already have website done/build separately environment: mySQL, python, windows and exist website to connect for now mySQL is connected to Django Therefore, how to use APIs with Django rest framework, generating endpoints which can call in my existing website -
Python Django settings.py Module Not Found Error (module is just local .py file)
Background info Background Info can be found on my last post - Cannot import .py file into settings.py Problem When attempting to import a python file into settings.py I get an error The code: import test Password = test.Password The Error: [wsgi:error] [pid 3908:tid 1496] import test\r [wsgi:error] [pid 3908:tid 1496] ModuleNotFoundError: No module named 'test'\r WSGIPythonPath set In my D:\Apache24\conf\httpd.conf I have the WSGIPythonPath line set: WSGIPythonPath D:\PythonEnvs\myenv\Lib\site-packages However, test is just a python file I created titled test.py located in the same directory as settings.py. It does NOT exist in the folder site-packages like the other modules. Note I can import test into other python files. However, when I try and import test.py into settings.py I get an error 500 when restarting my Apache server and get the error above from the Problem section in my error logs. -
AWS Codebuild Installing Upgraded Version of Package but Old Version Still Detected/Used
I have a Django App deployed via AWS' elastic beanstalk, that uses the CodePipeline service to build. As part of that pipeline, the CodeBuild service is used to build the app that gets deployed to the ElasticBeanstalk environment. The build failed, sending the following error message: django.core.exceptions.ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17). Per Amazon's own package version listing I realize that is expected given the older version is intended to be on the Amazon Linux 2 distro. Ok. I wrote a shell script to download the latest version of SQLite and build from scratch, but I'm still getting the same issue. In the buildspec.yaml file I have the following: ... post_build: commands: - echo "beginning post-build phase..." - bash get_sqlite.sh - echo "sqlite version -- $(sqlite3 --version)" - python manage.py makemigrations ... In the CodeBuild logs, I can see the result of the echo command as such: sqlite version -- 3.40.1 2022-12-28 Yet, the build fails and the logs still show the following error: django.core.exceptions.ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17). Any idea what further steps need to be taken for the updated version to be detected rather than the previous one? -
how can i select correctly many to many field django
I need to select 'changes' which related to sku id I need help with views.py models.py Change class Change (models.Model): raw_current = models.ForeignKey(Raw, blank=True, null=True, on_delete=models.CASCADE, related_name='raw_current') raw_new = models.ForeignKey(Raw, blank=True, null=True, on_delete=models.CASCADE, related_name='raw_new') created_date = models.DateTimeField(default=timezone.now) # когда была создана заявка def __str__(self): return self.raw_current.num def publish(self): self.created_date = timezone.now() self.save() Raw class Raw (models.Model): num = models.CharField(max_length=200) # артикул сырья name = models.CharField(max_length=200) # наименование layer = models.CharField(max_length=200) # название слоя на русском def __str__(self): return self.num +' ' + self.name Sku class Sku (models.Model): num = models.CharField(max_length=200) # артикул готоваой продукции (ГП) name = models.CharField(max_length=200) # наименование ГП raw = models.ManyToManyField(Raw, blank=True, null=True) # сырье weight = models.IntegerField(blank=True, null=True) # вес photo = models.ImageField(blank=True, null=True, upload_to="images/") # фото type = models.ForeignKey(ProductsTypes, blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.num + ' ' + self.name views.py def change(request,sku_id): sku = Sku.objects.get(id=sku_id) list_change = Change.objects.filter(raw_current = sku.raw) return render(request, 'main/change.html', {'sku':sku,'list_change':list_change,'change':change,}) urls.py path('change/<sku_id>', views.change, name='change'), TypeError at /change/1 Field 'id' expected a number but got <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x10920d9f0>. if in views.py def change(request,sku_id): sku = Sku.objects.get(id=sku_id) list_change = Change.objects.all() return render(request, 'main/change.html',{'sku':sku,'list_change':list_change,'change':change,}) then i have the whole list but i need only changes belongs to selected sku thanks for … -
Django Rest UpdateView: This field is required
I have the following view: class CampaignUpdate(generics.RetrieveUpdateAPIView): queryset = Campaign.objects.all() serializer_class = CampaignSerializer permission_classes = [CampaignDetailPermission] lookup_field = 'cid' And I have the following test function: def test_update_campaign(self): request = self.factory.put(f'/', {'name': 'Updated Campaign'}) force_authenticate(request, user=self.merchant) response = CampaignUpdate.as_view()(request, cid=self.campaign.cid) # Check that the response status code is 200 (OK) print(response.data) self.assertEqual(response.status_code, 200) # Check that the campaign was updated in the database self.assertEqual(Campaign.objects.get(cid=self.campaign.cid).name, 'Updated Campaign') And I am getting the following error: System check identified 4 issues (0 silenced). ..........{'shop': [ErrorDetail(string='This field is required.', code='required')]} shop field is required for creation but i do not want to update this field everytime I update some other field. How can I make it optional for update or readonly after creation? In case, you need to see serializer: class CampaignSerializer(serializers.ModelSerializer): class Meta: model = Campaign fields = '__all__' -
Why am I getting a Type error produced even though on_delete is set to models.CASCADE?
Following the django portion of the book 'Python Crash Course' by Eric Matthes where you build a django topic website the code he used seems to be deprecated. For example methods like Foreign Key require an on_delete command in current versions of django however despite adding an on_delete argument I still get a typeerror. from django.db import models # Create your models here. class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """A entry in a given topic from the user""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) entry = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model.""" return self.text[:50] + "..." the error: Traceback (most recent call last): File "D:\lafem\You Don't Know Javascript\topicwebsites\manage.py", line 22, in <module> main() File "D:\lafem\You Don't Know Javascript\topicwebsites\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Python310\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Python310\lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Python310\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python310\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Python310\lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], … -
error after deleting app from django project
I am new to Django so please excuse my ignorance... I have been working on an e-commerce project with django in VS code. Everything was working fine until I thought I'd add an account feature. From the terminal I did a startapp account. Not long after doing this, I decided to go another route and not make an account app. So I deleted the account directory from the explorer from right clicking and selecting the delete option. Now, when I ran the server to make sure I didn't break anything, I did in fact break everything. I am using the venv and I do have my Onedrive open since the directory is saved in there. This is the error I got: (Django_projects) PS C:\Users\kylec\OneDrive\Documents\school_files\team_project\Django\bookify> py manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\kylec\appdata\local\programs\python\python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "c:\users\kylec\appdata\local\programs\python\python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\kylec\.virtualenvs\Django_projects-1wiE7bc9\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\kylec\.virtualenvs\Django_projects-1wiE7bc9\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\kylec\.virtualenvs\Django_projects-1wiE7bc9\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\kylec\.virtualenvs\Django_projects-1wiE7bc9\lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\kylec\.virtualenvs\Django_projects-1wiE7bc9\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\kylec\.virtualenvs\Django_projects-1wiE7bc9\lib\site-packages\django\__init__.py", line 24, in … -
How to change the background of input field with text (django form)?
I am building a form so when the button is clicked the function starts. So basically if the condition is True --> green, otherwise if False --> Red function check() { let correctAnswer = '{{ correct_answer }}'; let givenAnswer = document.getElementById('correct_answer').value; let exerciseForm = document.getElementById('form'); let form = document.getElementById('correct_answer'); if (givenAnswer === correctAnswer) { exerciseForm.style.backgroundColor = 'rgb(76, 234, 76)'; form.style.backgroundColor = 'rgb(76, 234, 76)'; } else if (givenAnswer != correctAnswer) { exerciseForm.style.backgroundColor = 'rgb(245, 69, 69)'; form.style.backgroundColor = 'rgb(245, 69, 69)'; } }; {{ sentence }} {{ form.correct_answer }} When I don't enter any text it seems to work. When I fill in some text it doesn't work any more. -
sorting feed by engagement Django
So, I´m currently working on a Social Media application where you can share image posts. Each post can be liked, and/or disliked by each user. At the moment, the feed is sorted by most recent post, however, I would like to sort it by engagement (number_of_likes + number_of_dislikes = engagement_count --> of all users). I´m new to python and quite unsure how to start. I had a few tries of using a class model and creating a list (engagement_count) in the def index(request): in views.py but I´m quite unable to connect the dots to something that makes sense. Please help me out with some tips how to approach this... thx. Here is the code. views.py: def index(request): #user_object = User.objects.get(username=request.user.username) #user_profile = User.objects.get(user=user_object) user_following_list =[] feed = [] user_following = FollowersCount.objects.filter(follower=request.user.username) for users in user_following: user_following_list.append(users.user) for usernames in user_following_list: feed_lists = Post.objects.filter(user=usernames) feed.append(feed_lists) feed_list = list(chain(*feed)) posts = Post.objects.all() Post.objects.order_by('number_of_likes') return render(request, 'index.html', {'posts': posts}) def like_post(request): username = request.user.username post_id = request.GET.get('post_id') post = Post.objects.get(id=post_id) #set up a filter so that a user can only like it a post once --> disable in project to give unlimited likes and dislikes like_filter = LikePost.objects.filter(post_id=post_id, username=username).first() if like_filter == None: … -
How to connect a python discord bot with a django website and execute commands over it
How can I connect my Python Discord Bot with my Django Website to execute commands like sending a message to a channel? -
Difference between Django `BaseCommand` loggers and `logging.getLogger()`
When writing custom Django management commands, the docs recommend using self.stdout and self.stderr. class Command(BaseCommand): def handle(self, *args, **options): self.stdout.write("Hello world!") self.stderr.write("Something went horribly wrong") I've typically used the logging module in the past: import logging logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): logging.info("Hello world!") logging.error("Something went horribly wrong") A few questions: Is there a difference between the Django BaseCommand loggers and the logging logger? Does the Django BaseCommand logger use the logging module under the hood? If so, what level does self.stdout and self.stderr use? -
S3 presigned url: 403 error when reading a file but OK when downloading
I am working with a s3 presigned url. OK: links works well to download. NOT OK: using the presigned url to read a file in the bucket I am getting the following error in console: <?xml version="1.0" encoding="UTF-8"?> <Error><Code>AuthorizationQueryParametersError</Code><Message>Query-string authentication version 4 requires the X-Amz-Algorithm, X-Amz-Credential, X-Amz-Signature, X-Amz-Date, X-Amz-SignedHeaders, and X-Amz-Expires parameters.</Message> and here is how generate the url with boto3 s3_client = boto3.client('s3', config=boto3.session.Config(signature_version='s3v4'), region_name='eu-west-3') bucket_name = config("AWS_STORAGE_BUCKET_NAME") file_name = '{}/{}/{}/{}'.format(user, 'projects', building.building_id, file.file) ifc_url = s3_client.generate_presigned_url( 'get_object', Params={ 'Bucket': bucket_name, 'Key': file_name, }, ExpiresIn=1799 ) I am fairly new to use s3 buckets so I am not sure what is wrong here, and searching around on SO and online has not been very helpful so far. Could anyone point me in the right direction? -
django views.py render difference in localhost and server
I have a problem with Django on the server side. everything is ok with the local host. but after uploading project files to the server some context of one app views.py are rendering differently. (the desired form is like local host numbers.) context.update({ 'data_u': around(array([mean(ui), std(ui), skew(ui), kurtosis(ui, fisher=False), mean(uf), std(uf), skew(uf), kurtosis(uf, fisher=False)]), 4), 'filtered_file': filtered_file, }) return render(request, 'filteration/statistics.html', context=context) on local host: on server: Also, the dynamic download link does not work on the server and I am not able to get the true URL of the file. I have used filtered = Despiking.objects.get(user=user, project_name=project_name) filtered_file = filtered.excel_file.url on localhost and it works ok. but in the server, I get an empty string. what I am doing wrong? -
How do I fix a error request in django python?
We have this problem in Django3: no1 = request.GET.get('no1') no2 = request.GET.get('no2') this output the message int the port: no1 = request.GET.get('no1') AttributeError: 'WSGIRequest' object has no attribute 'get' The solution with only .get('no..') or .GET('no...') is not useful, it outputs: TypeError at /result 'QueryDict' object is not callable -
Django API test.py 'TypeError: 'str' object is not a mapping'
I'm trying to write tests for a Django API, but I'm getting this error: TypeError: 'str' object is not a mapping Test.py class ProteinFamilyTest(APITestCase): def test_proteinFamilyReturnSuccess(self): proteinFamily = ProteinFamilyFactory.create(pk=1, domain="PF00360") url = reverse('ProteinFamilyDetail', kwargs={'pk':1}) response = self.client.get(url, follow=True) response.render() self.assertEqual(response.status_code, 200) What am I doing wrong? -
Django or Flask?
I am trying to build a webpage app that allows easy access to a tool that I built in python. The tool currently takes in csv files and then processes them and outputs a data frame with all necessary information. I guess I ultimately want a web app that allows a user to select csv files from their desktop and then outputs the data frame on the same page. What is the best software to do this? -
json loop from model in Django
How would I be able to create a loop on items, to further build up more items values. this is how my json looks, just not sure on the on the loop part to add extra items to the json_data so 1 or 20 items could be sent json_data = { 'data': { 'type': 'Delivery', 'customer_feedback': None, 'warehouse_address': None, 'items': [ { 'id': '5b22055510c92b1a046ece21', 'sku': '12387654', 'quantity': 8, }, { 'id': '5b22055510c92b1a046ece06', 'sku': '12387654', 'quantity': 5, }, ], }, response = requests.post('https://api.url', headers=headers, json=json_data) -
Sending a list value via ajax to view in Django
I'm trying to send a list from template to view Django via ajax. After I send that, I get same list as a string format! index.html <script> ... var provinces_list = [] var obj = document.getElementById('objectSelected'); for (var i=0; i<obj.length; i++) { provinces_list.push(obj.options[i].value) } var jsonText = JSON.stringify(provinces_list); $.ajax({ method: "GET", data: { 'P_list': jsonText }, url: '{% url '...' %}', dataType: 'json', success: function (context) { ... } }) </script> view.py provincesList = request.GET.get('P_list') when I debug, I get the list as str format: provincesList={str}'["X","Y","Z"]' I want to get value as a list. how can do that? thanks in advance -
Ensuring one task of a kind is being executed at a time. (Multiple tasks of different kinds can be executed concurrentlly) celery python
Let's say I have created two shared tasks: from celery import shared_task @shared_task def taskA(): #do something pass @shared_task def taskB(): #do something else pass I am using celery to perform certain tasks that will be invoked by the users of my Django project. I have no issue with taskA and taskB being executed at the same time. But, if taskA is already being executed, and another user tries to invoke taskA again, I want to show them an error message. Is there a way to do that? -
A weird behaviour of get_media_prefix of Django
I am monitoring a weird behaviour in the working of my django application. Sometimes the get_media_prefix returns a mix between static and get_media_prefix. I ask here because I have not found any solution in the searchers and If anyone could have any idea because server and web application do not shown any error, It just returns the incorrect path since is a mix between two paths. The django template is: {% load static %} <!DOCTYPE html> ... <script src="{% static "js/bootstrap.bundle.min.js" %}"></script> </head> <body> ... <img src="{% get_media_prefix %}{{ website.avatar }}" width="60" height="60" class="img-fluid rounded-circle" alt="Blog avatar"></img> ... View: def index(request): results = cache.get(1) if not results: # REDACTED code cache.set(1, foobar, 86400) return render(request,'index.html',{"Foobar" : foobar}) else: return render(request,'index.html',{"Foobar" : foobar}) Apache2 server: Alias /static/ /home/xxx/xxx.xxx/yyy/static/ Alias /media/ /home/xxx/xxx.xxx/yyy/media/ ... <Directory /home/xxx/xxx.xxx/yyy/static> <LimitExcept POST GET> Require all granted </LimitExcept> </Directory> <Directory /home/xxx/xxx.xxx/yyy/media> <LimitExcept POST GET> Require all granted </LimitExcept> </Directory> The weird situation always begins randomly and always looks like fix with a restart of apache2. for i in {1..20};do curl -s https://xxx.yyyy/ |grep avatar ; done <img src="/media/avatar/avatar2.webp" width="60" height="60" class="img-fluid rounded-circle" alt="Blog avatar"></img> <img src="/media/avatar/avatar2.webp" width="60" height="60" class="img-fluid rounded-circle" alt="Blog avatar"></img> <img src="/media/avatar/avatar2.webp" width="60" height="60" class="img-fluid rounded-circle" … -
Why does website not look like a module path?
I am going through a Django tutorial, and after creating my app directory, linking the urls.py files, and adjusting the views.py file, I am getting the error ImportError: website doesn't look like a module path. here is the full error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\utils\module_loading.py", line 25, in import_string module_path, class_name = dotted_path.rsplit(".", 1) ValueError: not enough values to unpack (expected 2, got 1) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\core\servers\basehttp.py", line 47, in get_internal_wsgi_application return import_string(app_path) File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\utils\module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\utils\module_loading.py", line 15, in cached_import module = import_module(module_path) File "C:\Conda\envs\DjangoTutorial\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\Dustin Oliver\Desktop\Coding Notes\Django\DjangoTutorial\dentist\dentist\wsgi.py", line 16, in <module> application = get_wsgi_application() File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\core\wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\core\handlers\wsgi.py", line 125, in __init__ self.load_middleware() File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\core\handlers\base.py", line 40, …