Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why my website called an API 2 times at a time
Here is my project: http://18.217.194.30/ Why it's using two requests at the time ? ) 49 / 60 REQUESTS LEFT) 60 requests for 1 IP or for all daily users ? This is my views.py: def user(req, username): username = str.lower(username) # Get User Info with urlopen(f'https://api.github.com/users/{username}') as response: source = response.read() data = json.loads(source) # Get Limit Call API with urlopen(f'https://api.github.com/rate_limit') as response: source = response.read() limit_data = json.loads(source) context = { 'username': username, 'data': data, 'limit_data': limit_data, } return render(req, 'user.html', context) Here is my project github: https://github.com/nathannewyen/octoProfile-github/blob/master/octoProfile_app/views.py -
Confused with static files in django production?
I have this structure in my django project: The structure of the folders is as below image: I have these line in settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ ... 'django.contrib.staticfiles', ... ]**strong text** MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] and I have this in the urls file: if settings.DEBUG: # new urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if DEBUG = True: I hit python manage.py runserver and then 127.0.0.1:8000 and everything is good. if DEBUG = False: I hit python manage.py collectstatic The static files get collected in the staticfiles directory. I then hit python manage.py runserver and then 127.0.0.1:8000 The static files and media files are not loaded in this case. Any solution to this problem? -
Django Tutorial instructions seem wrong for lattest version
I am following the tutorial here https://docs.djangoproject.com/en/3.0/intro/tutorial01/ for Django and I have ran the to commands as such. I am new to Django and reasonable new to phython development coming from a c# background. python -m pip install Django django-admin startproject mysite python manage.py startapp polls I ran the second one while in mysite now when I look at my directory structure it doesnt include the urls object But yet the mysite folder does?. Yet acording to the way the site shows it it does is there something im missing. -
How to destroy resource in a django+fastcgi+IIS setup?
I have this interesting issue. I am using the Django setup to serve queries. Initially, I was hoping for concurrent execution but there is one component X that doesn't allow its multiple invocation due to apparent failure in its license checking code when called parallely. To make sure that only 1 instance of django runs, I am planning to do the following: IIS: It doesn't have anything to do with concurrency directly as far as I checked. I might be wrong. FastCGI module in IIS: Max instances: 1 ( I think this means that fastcgi will only load 1 codebase of django app in memory.) Instance Max Request: 200 (This will make sure that after my above codebase of django app in memory handles 200 requests sequentially, it destroys itself and restart.) Why this recycling is even necessary? Queue Length: 1000 (This will create a backlog of incoming requests and even if they are coming from multiple sources, it will make sure that they aren't rejected immediately) Django: Now this component X takes around 1-2 second to load itself, so i can't put its loading code inside POST view function. I am planning to put it in apps.py inside a … -
Reverse for url not found in python urlpatterns
I made URL config urlpatterns = [ path('', lambda request: redirect('stocks', permanent=False)), path('stocks', views.stocks.index, name='stocks.index'), path('stocks/<slug:slug>', views.stocks.show, name='stocks.show'), path('stocks/<slug:slug>/load', views.stocks.load, name='stocks.load') ] These URLs are ok, and they work but not first path('', lambda request: redirect('stocks', permanent=False)), It gives when I try http://127.0.0.1:8000 NoReverseMatch at / Reverse for 'stocks' not found. 'stocks' is not a valid view function or pattern name. But if I try http://127.0.0.1:8000/stocks all is ok What's wrong here? -
how can i access to the intermediary table fields through the parent table in django?
this is my tables: class MyUser(models.Model): pass class Product(models.Model): name = models.CharField() class Order(models.Model): customer = models.ForeignKey(MyUser, on_delete=models.CASCADE) products = models.ManyToManyField(Product , through='MidCartProduct') class MidCartProduct(models.Model): class Meta : unique_together = (('order_id' , 'product_id')) order_id = models.ForeignKey(Order , on_delete=models.CASCADE) product_id = models.ForeignKey(Product , on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField() and so how can i access to the intermediary table quantity field through the Order table? is that possible? i tried to do this but not working : >>> a = Order.objects.first().products.first() >>> a.quantity Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'Order' object has no attribute 'quantity' Sorry for my bad English -
Django - how to call a phone number AND open a form page with one click?
I hope to get ist straight: I have a Django app with customer addresses and 'activities' whoch protocolls any contact to customers via email or phone. When the user clicks on a phone number (link) I want the system to dial that number and at the same time to create a record in a table (activities), render another page with a form, where he writes down notes while talking to the customer. How can I do that without a second click? I know, I create a link <a href='tel:{{ customer.phone }}'> that much is clear. But how to do a second action on the same click? Probably with JavaScript (I use jQuery, but am a novice to JavaScript). Alternatively I thought I could call the "Call-Phone-Number" action in a view which is called by the link (instead of 'tel:...') in the first place and does all the form rendering, which is more comfortable for me. But how to call a phone number from a view in python and render a page simultaniously (or one after the other without waiting) ? I hope my situatuon is clear... Thanx for any help! -
How to make Serializer class for manytomany field to be empty on POST
The ItemSerializers is for the Model Item which is a manytomany field in the model supplier , am trying to make it not required , but it is not working ,, her is my code : class SupplierSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(read_only=True) person_name = serializers.CharField(max_length=120, allow_blank=True) company_name = serializers.CharField(max_length=120, allow_blank=True) tax_number = serializers.CharField(max_length=120, allow_blank=True) items = ItemSerializer(many=True, allow_null=True, required=False) class Meta: model = Supplier fields = '__all__' the problem is in the line items = ItemSerializer(many=True, allow_null=True, required=False) AS I can't send a post a request with items field empty !! -
Do I need to create the template if I want to load the template correctly?
def directory_index(path, fullpath): try: t = loader.select_template([ 'static/directory_index.html', 'static/directory_index', ]) except TemplateDoesNotExist: t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE) c = Context() else: c = {} files = [] for f in fullpath.iterdir(): if not f.name.startswith('.'): url = str(f.relative_to(fullpath)) if f.is_dir(): url += '/' files.append(url) c.update({ 'directory': path + '/', 'file_list': files, }) return HttpResponse(t.render(c)) This snippet is from static.py source code. It seems select_template will try to load directory_index.html or directory_index from the static subdirectory. To avoid raising the error, I guess I need to create a static folder following my DIR path and place directory_index.html in it, right? -
Django way of model reverse_name with different linked model classes
I have a Problem with accessing models of different classeds via related_name and I need your help to find a clean solution, that uses few SQL queries and is easily extendable: class RoundTripToDifferentPlaces(models.Model): price = models.FloatField(default=0) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) ... class PlaceVisit(models.Model): roundtrip = models.OneToOneField(RoundTripToDifferentPlaces, related_name="place_visit") individual_price = models.FloatField(default=0) name = models.CharField(max_length=31, null=True) street = models.CharField(max_length=31, null=True) creation_date = models.DateTimeField(auto_now_add=True) ... class RestaurantVisit(models.Model): place = models.OneToOneField(Job, on_delete=models.CASCADE, primary_key=True) Some more fields...about pricedetails class LibraryVisit(models.Model): place = models.OneToOneField(Job, on_delete=models.CASCADE, primary_key=True) Some more fields...about pricedetails ...many more subcategories of places and i will add more in the future In my views I loop through the RoundTripToDifferentPlaces and i need to grab all information of the related models. I wish I could in my models: class RestaurantVisit(models.Model): placevisit = models.OneToOneField(Placevisit, related_name="specific_visit") roundtrip = models.OneToOneField(RoundTripToDifferentPlaces, related_name="restaurant_visit") Some more fields... class LibraryVisit(models.Model): placevisit = models.OneToOneField(Placevisit, related_name="specific_visit") roundtrip = models.OneToOneField(RoundTripToDifferentPlaces, related_name="library_visit") Some more fields... and in my views / templates: ... roundtrip = RoundTripToDifferentPlaces().objects.filter(user = request.user ) for visit in roundtrip.place_visit.all(): print(visit) print(visit.spefic_visit) #does not work #and e.g.: print(roundtrip.restaurant_visit) #works perfectly (A RoundTrip can have only one visit or as many as there are different models) It seems that im not allowed to give the same … -
SearchVecotor not searching tags field
I am trying to make SearchVecotor search in the tags field also, it was working with two fields, its either it is not searching the fields or search vector is not working properly with three fields. I have a tag field that's in the db because of taggit I am using postgresql view function that contains the search instructions def home_page_view(request): posts = Post.published.all().order_by('-publish')[:5] # Using the search bar search_form = SearchForm() query = None results = [] if 'query' in request.GET: search_form = SearchForm(request.GET) if search_form.is_valid(): query = search_form.cleaned_data['query'] search_vector = SearchVector('title', 'body', 'tags') search_query = SearchQuery(query) results = Post.published.annotate( search=search_vector, search_rank=SearchRank(search_vector, search_query) ).filter(search=query).order_by('-search_rank') return render(request, 'pages/page/search_results.html', {'query': query, 'search_form': search_form, 'results': results} ) return render(request, 'pages/page/home.html', {'section': 'home', 'posts': posts, 'query': query, 'search_form': search_form, 'results': results } ) -
Running 10 functions asynchronously in Djano Views using Asyncio
Im facing difficulties while trying to execute around 10 functions simultaneously using asyncio in Django. I could not find nay clear documentation on how to use asyncio with django. I made around 10 http requests to different using TOR which is by default slow. Instead of making these requests one by one, which usually takes around 2 minutes, I wanted to perform all the 10 requests simultaneously. There are 10 distinct functions each making a http request a different URL and scrape data and return JSON. URLscrape.py : async def scrape1(username): response = request.get('http://example.com'+username) return response.json() async def scrape2(username): response = request.get('http://something.com'+username) return response.json() I have 10 individual functions like the above with different URLs and perfrom scraping and return a json data. In Django views, I did like this: Views.py from URLscrape import scrape1, scrape2........scrape10 def scrapper(): loop = asyncio.get_event_loop() feature1 = loop.run_in_executor(None, scrape1, username) feature2 = loop.run_in_executor(None, scrape2, username) .... feature10 = loop.run_in_executor(None, scrape10, username) response1 = await future1 response2 = await future2 ..... response10 = await future10 response1 = response1.text ...... response10 = response2.text return render(request, 'index.html', {'scrape1':response1,'scrape10':response10}) But I dont know how to use loop.run_until_complete() to complete the script. Im in a restricted situation to use … -
Download file Django from Digital Ocean
I have a problem downloading some photos from a Django App residing on a Digital Ocean server. My local folder is practically not read: "C: / caricafoto /" below my code View def scaricaFoto(request, pk): lavoro = get_object_or_404(Lavori, pk=pk) foto = lavoro.foto_lavoro.all() b=0 for f in foto: a = f"http://161.35.157.223" + f.image.url b += 1 c = f"/caricafoto/" + str(b) + '.jpg' urllib.request.urlretrieve(a, c) context = {'lavoro':lavoro, 'foto':foto} return render(request, 'schede/scarica_foto.html', context) Below is the error message: error I have tried different paths but with none of these the "c: / caricafoto" folder is recognized. I thank in advance who can help me Claudio -
Django Deployment on Heroku with Gunicorn
After successfully deploying to Heroku, whenever i want to access the page i get "Application Error". Looking through my Heroku log, error below is what i get regularly. 2020-07-10T15:03:39.152131+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 181, in init_signals 2020-07-10T15:03:39.152372+00:00 app[web.1]: util.set_non_blocking(p) 2020-07-10T15:03:39.152403+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 253, in set_non_blocking 2020-07-10T15:03:39.152670+00:00 app[web.1]: flags = fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK 2020-07-10T15:03:39.152717+00:00 app[web.1]: AttributeError: module 'fcntl' has no attribute 'fcntl' -
Charting over 5 million measurements of sensor with Django
i'm currently using Echarts (i've used in the past Highcharts) and it's working fine with small datasets: it has a lot of features, options and it's pretty nice to view and use. Now, i have a lot of sensors that acquires a lot of data (data is captured with a frequency of 500khz) and the users needs to analyze the acquired dataset (that has 2/5 millions of point) many times a day/week. I've seen that those charting libraries are totally a crap solution when the dataset is very big, so, any solution? I wish to integrate those charts with my django app, so an integrated solution (or a python based one) is mandatory... -
Django + DjangoRestFramework: How to build a Django WebApp using DjangoRestFramework API?
I know Django Web App Development, API Development with DjangoRestFramework, and using DjangoRestFramework API in other programming platforms such as JavaScript and React. But what I am having confusion is at using the DjangoRestFramework API in a simple Django Web Application. How to retrieve the values that have been parsed from a serializer of DjangorestFramework API and return it to the view, which is an HTML template? The URL api/task-list returns all tasks added in the database. This is how it is done in API programming. def taskList(request): tasks = Task.objects.all() serializer = TaskSerializer(tasks, many=True) return Response(serializer.data) While in the Django web app the tasks are passed as a context and it returns or renders a template where we can loop the task from the tasklist and display it in an HTML view page. def taskList(request): tasks = Task.objects.all() context = {'task': tasks} return render(request, 'todo/tasklist.html', context) If we have to use the API in Javascript based application than we can do it simply by doing the following: If there is a HTML division with id list-wrapper <div id="list-wrapper"> Than in the JavaScript section we can consume the API and do the data retrieval operation like shown below: buildList() function … -
COUNT field not set during pagination in django
i have created an API end-point using with custom method. This returns a paginated response. but when i try to get response after filtering records i get following error. lib/python3.6/site-packages/sql_server/pyodbc/base.py", line 575, in execute return self.cursor.execute(sql, params) django.db.utils.Error: ('07002', '[07002] [Microsoft][ODBC Driver 17 for SQL Server]COUNT field incorrect or syntax error (0) (SQLExecDirectW)') Following is code snippet that i am using to return paginated response. Code: data_dict= request.data for k,v in data_dict.items(): my_filter("{0}_{1}".format(k, "in")]=v obj=Master.objects.filter(**my_filter) page = self.paginate_queryset(obj) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) return Response({}) -
Apache not starting and error logs aren't showing why
I'm trying to start Apache for my Django project on this AWS Lightsail server (Ubuntu). I tried the following commands to start Apache: apachectl start service apache2 start Those commands don't throw errors and so I check the status of Apache service apache2 status and it shows this: service apache2 status ● apache2.service - The Apache HTTP Server Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled) Drop-In: /lib/systemd/system/apache2.service.d └─apache2-systemd.conf Active: inactive (dead) since Fri 2020-07-10 10:27:37 CDT; 19min ago Process: 27000 ExecStop=/usr/sbin/apachectl stop (code=exited, status=0/SUCCESS) Process: 26983 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS) Main PID: 26060 (code=exited, status=0/SUCCESS) Jul 10 10:27:37 ip-172-26-0-126 systemd[1]: Starting The Apache HTTP Server... Jul 10 10:27:37 ip-172-26-0-126 apachectl[26983]: httpd (pid 26768) already running Jul 10 10:27:37 ip-172-26-0-126 systemd[1]: Started The Apache HTTP Server. I looked at the logs in /var/log/apache2 cat error.log [Fri Jul 10 10:31:36.874946 2020] [mpm_event:notice] [pid 27082:tid 140450046516160] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.7.1 Python/3.7 configured -- resuming normal operations [Fri Jul 10 10:31:36.875051 2020] [core:notice] [pid 27082:tid 140450046516160] AH00094: Command line: '/usr/sbin/apache2' From what I can tell, it doesn't really show anything useful. I tried to check if the process was running and I think it is? ps aux | grep apache ubuntu 27082 0.0 0.5 … -
Django use view response in html file
I have a function in my views.py file that returns a list of files in a path and I want to use that list in a html file, so I call the view response in this way: {% url 'files' %}(I also tried with {{ }} notation but I got this error Could not parse the remainder: '% url 'files' %' from '% url 'files' %') but i only get this /files/ no the list I want, so how can I get the list ? this is my views.py file : def itemlist(request): files = [] for root, dirs, files in os.walk('mypath'): for file in files: files.append(os.path.join(root,file)) list_files = json.dumps(files) return HttpResponse(your_list_as_json) this is my urls.py file: from almacen_folders.views import itemlist urlpatterns = [ url(r'^django-admin/', admin.site.urls), url(r'^files/$',itemlist,name='files'), ] in the html file i call the view like this {% url 'files' %} -
Exception Type: ParseError Exception Value: JSON parse error - Expecting value: line 1 column 1 (char 0)
I was learning how to do basic CRUD operations in DRF, and when I do PUT request to this url I came across this error. ParseError at /api-article/detail/2/ JSON parse error - Expecting value: line 1 column 1 (char 0) Request Method: PUT Request URL: http://127.0.0.1:8000/api-article/detail/2/ Django Version: 3.0.8 Exception Type: ParseError Exception Value: JSON parse error - Expecting value: line 1 column 1 (char 0) Exception Location: /home/AnimeshK/Dev/parviz_api/lib/python3.8/site-packages/rest_framework/parsers.py in parse, line 67 Python Executable: /home/AnimeshK/Dev/parviz_api/bin/python Python Version: 3.8.3 Python Path: ['/home/AnimeshK/Dev/parviz_api/src', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/AnimeshK/Dev/parviz_api/lib/python3.8/site-packages'] Server time: Fri, 10 Jul 2020 15:12:12 +0000 Below is my view.py @csrf_exempt def article_detail(request, id): try: art_obj = Article.objects.get(id=id) except Article.DoesNotExist: raise Http404 if (request.method == 'GET'): # normal detail view serializer = ArticleSerializer(art_obj) return JsonResponse(serializer.data) elif (request.method == 'PUT'): # article update view data = JSONParser().parse(request) serializer = ArticleSerializer(art_obj, data=data) # so that the existing data gets rendered in the PUT walla form if (serializer.is_valid()): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif (request.method == 'DELETE'): art_obj.delete() return HttpResponse(status=204) Below is the full traceback: > representation and the index in ``s`` where the document ended. > This can be used to decode a JSON document from a string that may > have extraneous … -
Best way to store (javascript code) in a dynamic website editor
I am creating a dynamic website editor. Multiple users can come to this website editor (web based) and create their own site. I want to allow user to enter chat widget code, Fb pixel code, google analytics code etc (basically javascript code snippets). Since this code is unique to each user, whats the best way to store the code entered by users (database? or a separate file unique to each user). I have safety concerns about storing js code snippet in db. Any suggestion. I am using jquery, python, django. -
How to freeze datetime.now for unit testing
I have a model that uses a function to return a default datetime: class Company(models.Model): q1_results_date = models.DateField( verbose_name='Q1 financial results', default=quarter_results_date(1), blank=False, null=False, ) def quarter_results_date(month): return datetime.datetime( datetime.datetime.now().year, month, calendar.monthrange(datetime.datetime.now().year, month)[1] ) I want to unit test this, which requires me to set datetime.now() to a known value. To do this I am using freezegun.freeze_time: def test_quarter_results_date(self): with freeze_time("2012-01-14"): print('check datetime.now()', datetime.now()) c = Company.objects.create() ... However, although the print statement shows 2012-01-14, the datetime is not frozen as it still uses today's date when evaluating c1.q1_results_date. How can I correct this? -
Page returns 'Not Found' when opening URL to image in deployment but works in local machine. [Django Rest Framework]
My Django REST API supposedly is able to GET and POST images. During development, I was able to save the image into the database and retrieve the saved image via the URL of the image. However, when deployed to Heroku, the page returns 'Not Found' when I clicked the URL to the image. requirements.txt asgiref==3.2.10 dj-database-url==0.5.0 Django==3.0.8 django-heroku==0.3.1 djangorestframework==3.11.0 gunicorn==20.0.4 Pillow==7.2.0 psycopg2==2.8.5 pytz==2020.1 sqlparse==0.3.1 whitenoise==5.1.0 settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' django_heroku.settings(locals()) urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('element.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py (Element App) from django.db import models # Create your models here. class Element(models.Model): element_name = models.CharField(max_length=255, unique=True) element_tag = models.CharField(max_length=255) element_type = models.CharField(max_length=255) element_img = models.ImageField(upload_to='elements/') creator_tag = models.CharField(max_length=255) creator_link = models.CharField(max_length=255) def __str__(self): return self.element_name serializers.py (Element App) from rest_framework import serializers from element import models class ElementSerializer(serializers.ModelSerializer): element_img = serializers.ImageField(max_length=None, use_url=True) class Meta: model = models.Element fields = ('id', 'element_name', 'element_tag', 'element_type', 'element_img', 'creator_tag', 'creator_link') views.py (Element App) from django.shortcuts import render from rest_framework import viewsets from rest_framework import filters from element import serializers from element import models # … -
Django Admin Shows Instance Created But Cannot See It In DRF View
I am following a course on DRF. It basically is creating a Q&A site. Now I tried answering a Question using the DRF interface. But when I look at the question, it still shows answer count as zero. But the answwers are visible on the Django Admin Panel. My code for the same is: models.py file class Question(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) content = models.CharField(max_length=240) slug = models.SlugField(max_length=240, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="questions") def __str__(self): return self.content class Answer(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) body = models.TextField() question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="answers", null=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) voters = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='votes') def __str__(self): return f'{self.body} by {self.author.username}' The serializers.py file: from rest_framework import serializers from ..models import (Answer, Question) class AnswerSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(read_only=True) created_at = serializers.SerializerMethodField(read_only=True) likes_count = serializers.SerializerMethodField(read_only=True) user_has_voted = serializers.SerializerMethodField(read_only=True) class Meta: model = Answer exclude = ['question', 'voters', 'updated_at'] def get_created_at(self, instance): return instance.created_at.strftime("%B %d %y") def get_likes_count(self, instance): return instance.voters.count() def get_user_has_voted(self, instance): request = self.context.get('request') return instance.voters.filter(pk=request.user.pk).exists() class QuestionSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(read_only=True) created_at = serializers.SerializerMethodField(read_only=True) slug = serializers.SlugField(read_only=True) answers_count = serializers.SerializerMethodField(read_only=True) user_has_answered = serializers.SerializerMethodField(read_only=True) class Meta: model = Question exclude = ['updated_at'] def get_created_at(self, instance): return instance.created_at.strftime("%B %d %y") def … -
“ImportError: Couldn't import Django.” even after having Django in Virtualenv
I am trying to run an old project of django but i am geeting error like couldnt import Django. i already activated my virtualenv. Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?