Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
For some migrations, why `sqlmigrate` shows empty, or the same SQL both directions?
I'm working on upgrading a legacy project, currently still on Python 2.7.18 as the highest Python-2 before upgrade to 3. After upgrading Django from 1.8.13 to 1.11.29, the project requires some database changes (unapplied migrations), and I'm using command python manage.py sqlmigrate to review the SQL statements. I have some questions, and any inputs will be highly appreciated: Some migrations, e.g. 0002_logentry_remove_auto_add below, SQL only contains comment, I'm wondering why. (venv) [ebackenduser@setsv EBACKEND]$ python manage.py sqlmigrate admin 0002_logentry_remove_auto_add BEGIN; -- -- Alter field action_time on logentry -- COMMIT; For migration 0002_auto_20160226_1747, SQL is the same for both forward and backward (--backwards) directions, and I'm also wondering 1) why, and 2) whether this should be a concern. Just want to be cautious with the production database, and thank you for your pointers. (venv) [ebackenduser@setsv EBACKEND]$ python manage.py sqlmigrate authtoken 0002_auto_20160226_1747 BEGIN; -- -- Change Meta options on token -- -- -- Alter field created on token -- -- -- Alter field key on token -- -- -- Alter field user on token -- ALTER TABLE `authtoken_token` DROP FOREIGN KEY `authtoken_token_user_id_535fb363_fk_auth_user_id`; ALTER TABLE `authtoken_token` ADD CONSTRAINT `authtoken_token_user_id_35299eff_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); COMMIT; (venv) [ebackenduser@setsv EBACKEND]$ python manage.py sqlmigrate --backwards authtoken … -
Django queryset in multiple tables
I have this kind of query using PostgreSQL: SELECT tbl_project_lu.project_id, tbl_project_lu.house_id, tbl_project_lu.project_name AS project, tbl_house_lu.house_name, tbl_project_lu.description, tbl_house_mbr.person_id FROM ((tbl_house_lu INNER JOIN tbl_house_mbr ON tbl_house_lu.house_id = tbl_house_mbr.house_id) INNER JOIN tbl_project_lu ON tbl_house_lu.house_id = tbl_project_lu.house_id) INNER JOIN tbl_proj_mbr ON (tbl_project_lu.project_id = tbl_proj_mbr.project_id) AND (tbl_house_mbr.house_mbr_id = tbl_proj_mbr.house_mbr_id) WHERE person_id = 'foo'; What is the best way to use this kind of query in django? Can Django ORM handle this kind of query or do I have to use stored proc for this? -
Getting error after changed sqlite to mysql, table doesn't exist?
i've finished developing a django project and wanted to change sqlite3 to MySql for a better database option. I tried in an empty project to change database, it worked like a charm. But now i changed db of my project and when i try to do python manage.py makemigrations it returns; django.db.utils.ProgrammingError: (1146, "Table 'tvekstra-django-tracker.tvchannels_channels' doesn't exist") Any help is appreciated, thanks. -
How to get access to authenticated, logged in user in vue.js and django rest framework
I want to get access to authenticated, currently logged in user, eg. to username and id, and to put it in to the form by default when I'm using POST method. My login component: import axios from 'axios'; export default { name: 'LoginForm', components: { }, data(){ return{ username: '', password: '', token: localStorage.getItem('user-token') || null, } }, methods: { login(){ axios.post('http://127.0.0.1:8000/auth/',{ username: this.username, password: this.password, }) .then(resp => { this.token = resp.data.token; localStorage.setItem('user-token', resp.data.token) this.$router.push(this.$route.query.redirect || '/') }) .catch(err => { localStorage.removeItem('user-token') }) } } } </script> Could you help me? -
Setting up Domain on DigitalOcean to Django & Nginx
Finishing up site migration, I've been able to get it running on the droplet IP I've also checked if IP propagation is complete and I've added the domain to digitalocean When I try the domain I get This site can’t be reached. I've tried to set up the nginx file to match this server { listen 80; server_name http://safariguides.org 162.243.173.84 safariguides.org; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/webapps/kpsga; } location /media/ { root /home/sammy/webapps/kpsga; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } and in the settings file DEBUG = True ALLOWED_HOSTS = [ 'http://safariguides.org', 'http://162.243.173.84/', '*' ] finally adding the * for maximum matches. checking for errors in nginx logs shows this sammy@kpsga:~/webapps/kpsga/kpsga$ sudo tail -F /var/log/nginx/error.log 2020/11/03 06:55:50 [warn] 70740#70740: server name "http://safariguides.org" has suspicious symbols in /etc/nginx/sites-enabled/kpsga:3 2020/11/03 07:00:36 [alert] 70778#70778: *14 open socket #16 left in connection 9 2020/11/03 07:00:36 [alert] 70778#70778: *15 open socket #17 left in connection 10 2020/11/03 07:00:36 [alert] 70778#70778: aborting 2020/11/03 07:00:36 [warn] 70858#70858: server name "http://safariguides.org" has suspicious symbols in /etc/nginx/sites-enabled/kpsga:3 2020/11/03 07:00:36 [warn] 70869#70869: server name "http://safariguides.org" has suspicious symbols in /etc/nginx/sites-enabled/kpsga:3 2020/11/03 07:04:34 [warn] 70893#70893: server name "http://safariguides.org" has suspicious … -
access database from dajngo views class
when I run my server,(in my website) in this case I get Error that is table not found. when I call this function in another class(not in views) it works! How can I solve this problem? `def calculate(request): vt =sql.connect('../db.sqlite3') imlec = vt.cursor() imlec.execute("SELECT pain from kaktüs_kaktüs WHERE id = (SELECT MAX (id) FROM kaktüs_kaktüs)") idsa = imlec.fetchone() for i in idsa: i image_a = Image.open(str(i)) image_a_array = np.array(image_a) print("1.resim Array") print("*************************************************************************") print(image_a_array) imlec.execute("SELECT pain_two FROM kaktüs_kaktüs WHERE id = (SELECT MAX (id) FROM kaktüs_kaktüs)") idsb = imlec.fetchone() for i in idsb: i image_b = Image.open(str(i)) image_b_array = np.array(image_b) print("2.resim Array") print("*************************************************************************") print(image_b_array) imlec.execute("SELECT pain_three FROM kaktüs_kaktüs WHERE id = (SELECT MAX (id) FROM kaktüs_kaktüs)") idsc = imlec.fetchone() for i in idsc: i image_c = Image.open(str(i)) image_c_array = np.array(image_c) print("3.resim Array") print("*************************************************************************") print(image_c_array) imlec.execute("SELECT pain_four FROM kaktüs_kaktüs WHERE id = (SELECT MAX (id) FROM kaktüs_kaktüs)") idsd = imlec.fetchone() for i in idsd: i image_d = Image.open(str(i)) image_d_array = np.array(image_d) print("4.resim Array") print("*************************************************************************") print(image_d_array) return render(request,"anasayfa.html")` -
Which field in Django model to choose for a file downloaded via API endpoint?
I am using Django 2.2 LTS I have a function that will download a file from endpoint def download_as_file(url: str, auth=(), file_path="", attempts=2): """Downloads a URL content into a file (with large file support by streaming) :param url: URL to download :param auth: tuple containing credentials to access the url :param file_path: Local file name to contain the data downloaded :param attempts: Number of attempts :return: New file path. Empty string if the download failed """ if not file_path: file_path = os.path.realpath(os.path.basename(url)) logger.info(f"Downloading {url} content to {file_path}") url_sections = urlparse(url) if not url_sections.scheme: logger.debug("The given url is missing a scheme. Adding http scheme") url = f"https://{url}" logger.debug(f"New url: {url}") for attempt in range(1, attempts + 1): try: if attempt > 1: time.sleep(10) # 10 seconds wait time between downloads with requests.get(url, auth=auth, stream=True) as response: response.raise_for_status() with open(file_path, "wb") as out_file: for chunk in response.iter_content(chunk_size=1024 * 1024): # 1MB chunks out_file.write(chunk) logger.info("Download finished successfully") return (response, file_path) except Exception as ex: logger.error(f"Attempt #{attempt} failed with error: {ex}") return None I also intend to have a Django model to store metadata associated with that downloaded file. class DownloadedFile(models.Model): # other fields but i skipped most of them here local_copy = models.FileField(upload_to="downloads/") … -
Custom user creation form always invalid in Django
I am working on building a new Django Website and am trying to make an abstract base class and using forms to fill it out. I thought I was doing it correctly, but whenever I try to fill out the form it is always invalid. I am wondering if anyone can help me with this problem. All of the other help I find online does not help me. Here is my code. Thanks My forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Profile class CustomUserCreationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = Profile fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def __init__(self, regLinkModel): super(CustomUserCreationForm, self).__init__() self.linkInfo = regLinkModel def save(self, commit=True): user = super(CustomUserCreationForm, self).save(commit=False) user.username = self.cleaned_data['username'] user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['fname'] user.last_name = self.cleaned_data['lname'] user.password1 = self.cleaned_data['password1'] user.password2 = self.cleaned_data['password2'] if commit: user.save() return user My Models.py class MyAccountManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, password): if not email: raise ValueError("User needs email address") if not username: raise ValueError("User needs username") if not first_name: raise ValueError("User needs first name") if not last_name: raise ValueError("User needs last name") user = self.model( email=self.normalize_email(email), password = password, username =username, first_name = … -
I was trying to run django qcluster in my local machine and getting this error - Any help would be really appreciated
I'm doing this to run the DjangoQ - This is my Q_CLUSTER config inside my settigns.py file - Q_CLUSTER = { 'name': 'default_orm', 'compress': True, 'save_limit': 0, 'orm': 'default' } python manage.py qcluster File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/multiprocessing/reduction.py", line 60, in dump ForkingPickler(file, protocol).dump(obj) AttributeError: Can't pickle local object 'BaseDatabaseCache.__init__.<locals>.CacheEntry' -
TypeError: create_user() missing 3 required positional arguments(when createsuperuser)
I get this error when trying to create superuser: TypeError: create_user() missing 3 required positional arguments: 'first_name', 'last_name', and 'role' Is this the proper way to create it? I want to create superuser without username, just with email, and user can login only with their email addresses, and now when I create superuser it wants email, how I wanted, but gives me the error too. class MyAccountManager(BaseUserManager): def create_user(self, email, first_name, last_name, role, password=None, **extra_fields): if not email: raise ValueError("Users must have an email address") user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, role=role, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email=self.normalize_email(email), password=password ) user.is_admin = True user.is_employee = True user.is_headofdepartment = True user.is_reception = True user.is_patient = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractUser): ADMIN = 1 RECEPTION = 2 HEADOFDEPARTMENT = 3 EMPLOYEE = 4 PATIENT = 5 NOTACTIVE = 6 ROLE_CHOICES = ( (ADMIN, 'Admin'), (RECEPTION, 'Reception'), (HEADOFDEPARTMENT, 'HeadOfDepartment'), (EMPLOYEE, 'Employee'), (PATIENT, 'Patient'), (NOTACTIVE, 'NotActive'), ) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, blank=True, default=True, null=True) email = models.EmailField(verbose_name="email", max_length=60, unique=True) is_superuser = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) is_headofdepartment = models.BooleanField(default=False) is_reception = models.BooleanField(default=False) is_patient … -
get current domain name in settings.py file
I am running a multisite project with various tenant domains. In my settings.py file, I have a variable name called TENANT_DOMAIN that I would want to set the current tenant domain name before the settings file is run. How do I go about this? -
Django reset password using phone number or email
I am creating a mobile app with django and drf. I am giving users the option to register using phone number or email. For email I can obviously use the built in PasswordResetView however I have no idea how to reset password using the phone number. Here is my User model class User(AbstractBaseUser): email = models.EmailField( null=True, blank=True, verbose_name='email address', max_length=255, unique=True, ) username = models.CharField( verbose_name='username', max_length=100, unique=True) phone_number = PhoneField( max_length=10, blank=True, null=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'username' objects = UserManager() -
Deploying Django application on LAN
I have a Django application that I want to deploy on LAN for use/production. I need a help how to deploy it on Windows Server (Step by step). -
in python how to access half iterate forloop value outside without if condition
i am iterating a large number of list like 100,000 data. I want to know how much iteration is completed outside of the loop. I don't want to use if condition. if condition increases execution time. def callme(): for data in range(100000): # i want to return 'data' after every 5 seconds. # without if condition return data -
how i can solve these error on django runserver
Whenever i want to run a server of django these error message shows in my VS code (django) PS C:\python\New folder\django\To_Do> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "c:\python\lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\python\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\python\New folder\django\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\python\New folder\django\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run -
python django: How to fix error saying: AttributeError at / 'Home' object has no attribute 'get'
i'm trying to create two pages for my website in django. I get an Error: AttributeError at /'Home' object has no attribute 'get' The above 'Home' is a class in my models but I do not know why it says 'Home object no attribute get' when I have called Home.objects.all() in my views.py My models: from django.db import models class Product(models.Model): name = models.CharField(max_length=20) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) class Home(models.Model): heading = models.CharField(max_length=10) words = models.CharField(max_length=10000) My views: from django.http import HttpResponse from django.shortcuts render from .models import Product, Home def index(request): products = Product.objects.all() return render(request, 'index.html', {'products': products}) def home(request): home_obj = Home.objects.all() return render(request, 'home.html', {'Home': home_obj}) My app urls: from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('fruits/', views.index), path('', views.Home), ] index.html: {% extends 'base.html' %} {% block content %} <div class="row"> {% for product in products %} <div class="col"> <div class="card" style="width: 18rem;"> <img src="{{ product.image_url }}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">₹ {{ product.price }}</p> <a href="#" class="btn btn-primary">add to cart</a> </div> </div> </div> {% endfor %} </div> {% endblock %} home.html: <h2>{{ home_obj.heading }}</h2> <p>{{ home_obj.words }}</p> … -
How to search for objects in the Django User model
I have a Profile model: from django.contrib.auth.models import User class Profile(models.Model): first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=100, blank=True) And a search contacts view: class SearchContactsView(ListView): model = Profile template_name = 'users/contact_search.html' context_object_name = 'qs' def get_queryset(self): q1 = self.request.GET.get('contact_name') q2 = self.request.GET.get('contact_location') if q1 or q2: return Profile.objects.filter(Q(first_name__icontains=q1) | Q(last_name__icontains=q1), location__icontains=q2) return Profile.objects.all() It is working fine but I would like to be able to search for contacts via the user field as well. Does anyone know a way to do that? -
What command do we use to create a folder in pycharm?
I was coding in python. I typed this code python3 manage.py startapp products in order to create a folder, and I tried to find the folder, but I did not see nothing appeared. May someone help me to fix it please? -
'AnonymousUser' object has no attribute 'authenticated'?
I am using Django Version: 3.0.2. Student registration is working and user is saving to database successfully. The problem is after login it is showing 'AnonymousUser' object has no attribute 'authenticated'. Please any one solve my problem? views.py: from django.contrib.auth.models import User, Group, auth def studentregistration(request): if request.method == 'POST': form = StudentRegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data['user_name'] password = form.cleaned_data['password'] confirmpassword = form.cleaned_data['confirm_password'] email = form.cleaned_data['email'] if password == confirmpassword: if User.objects.filter(username=username).exists(): messages.error(request,'user already exists please login') return render(request, 'login.html') elif User.objects.filter(email=email).exists(): messages.error(request, 'email already registered please login') return render(request, 'login.html') else: user=User.objects.create_user(username=username, password=password, email=email) user.save() messages.success(request, "Successfully registered, Please login") return render(request, 'login.html') else: messages.error(request, 'password and confirmation password do not match') return render(request, 'studentregistration.html') #return HttpResponseRedirect('studentregistration.html') else: form = StudentRegisterForm() return render(request, 'studentregistration.html', {'form': form}) def login(request): if request.method == 'POST': username = request.POST.get('user_name', '') password = request.POST.get('password', '') user=auth.authenticate(username=username,password=password) if user is not None: auth.login(request, user) return HttpResponseRedirect('exam_pattern') else: messages.error(request,'invalid credentials') return render(request, 'login.html') else: return render(request,'login.html') Here, i am autheticated user, but i am getting 'AnonymousUser' object has no attribute 'authenticated' after login. def render_questions(request): if not request.user.authenticated: return render(request, 'login.html') else: global exam_session exam_session = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) questions = … -
Django Channels error with received messages
I have a simple chat app example from channels dockerized but im having a problem when i open 2 chats. If i open the first window and send a message, the consumers capture my message and reply to all channels in group (only me at the moment) Normal test Then if i open another window and send a message i receive two messages in the same window (same socket) and not other message in the first window-chat New window and two messages BUT i can send messages from the old window, im just going to see this messages in the new window. No messages from user2 But i send messages, i cant see it and user2 can see it My consumer # chat/consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = text_data_json['username'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': username … -
How can i upload a image in database using django?
I have a python code for processing image. What i want now is- I want to upload an image from Webapp using django I want to process the uploaded image. I want to show the final output & store the result in server. can anyone help me with code & details? -
How to have a check that User must Select at least one of the two Foreign Keys in Django Rest Framework
I am trying to make a Django App. I am facing this issue that I need to bound the user to at least select one of the foreign keys. The logic being the user should have his own Idea or he needs to request one of the ideas posted by the teacher. My code looks like this. Models.py class RequestFYP(models.Model): requested_to = models.ForeignKey(Faculty, on_delete=models.CASCADE, related_name='Teacher') requested_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Student_Idea = models.ForeignKey(FYP, on_delete=models.CASCADE, null=True, blank=True) Related_Idea = models.ForeignKey(Idea, on_delete=models.CASCADE, null=True, blank=True) class Meta: verbose_name_plural = 'Requests' def __str__(self): return self.requested_by Serializers.py class RequestFYPSerializer(serializers.ModelSerializer): requested_by = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = RequestFYP fields = '__all__' API.py class RequestFYPView(generics.ListCreateAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = RequestFYPSerializer def get_queryset(self): return RequestFYP.objects.filter(requested_by=self.request.user) def create(self, request, *args, **kwargs): serializer = RequestFYPSerializer(data=request.data) if serializer.is_valid(): serializer.save(requested_by=request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Unable to save data into Foreign key fields in Django Rest Framework
I'm working on a project where I have to enroll students in a course. I have a model called Enrollment with two foreign key fields to Course, and Student. I'm trying to save course and student in Enrollment model when they submit. But after calling the save method also response returns a response as course and student are required. My models class Course(models.Model): course_name = models.CharField(max_length=300,default=None) author = models.ForeignKey(TeacherProfile,on_delete=models.CASCADE,null=True,default=None) course_description = models.TextField(null=True) course_cover = models.ImageField(null=True,blank=True,upload_to='course_covers/') def __str__(self): return self.course_name``` class Enrollment(models.Model): enroll_key = models.CharField(max_length=100,default="Text here",null=True) course = models.ForeignKey(Course,on_delete=models.CASCADE,null=True) student = models.ForeignKey(StudentProfile,on_delete=models.CASCADE,null=True) def __str__(self): return self.course.course_name class Meta: unique_together = [['course','student']] Serializer class CourseEnrollSerializer(serializers.ModelSerializer): class Meta: model = Enrollment fields = ['enroll_key','course','student'] My views @api_view(['POST']) @permission_classes([IsAuthenticated]) def EnrollCourse(request,pk): course = Course.objects.get(id=pk) print("course",course) student = StudentProfile.objects.get(user=request.user) print("student",student) serializer = CourseEnrollSerializer(data=request.data) print(serializer) print("loading the serializer...") if serializer.is_valid(): serializer.save(course=course,student=student) else: print("Serializer not valid",serializer.errors) return Response(serializer.errors) urls.py path('enrollcourse/<int:pk>/',views.EnrollCourse,name='enroll_course'), #pk is course primarykey What I get after printing serializer.errors {'course': [ErrorDetail(string='This field is required.', code='required')], 'student': [ErrorDetail(string='This field is required.', code='required')]} -
no module named 'social' when I'm trying to get a new facebook access_token in the postman using my new heroku domain name instead of localhost:8000
There Are The Steps I Followed To get an access_token after pushed my project into heroku I Changed My Site Url Of My App On Facebook from localhost:8000 to https://whispering-hamlet-67095.herokuapp.com/ changed my ALLOWED_HOSTS In Settings.py To ALLOWED_HOSTS = ["localhost","whispering-hamlet-67095.herokuapp.com"] This Step=> ### Testing On PostMan To Get facebook access_token As Usual Like I Used To Do When My Project is Only Running Locally But I Got This error When I Changed The Url From localhost:8000/ to https://whispering-hamlet-67095.herokuapp.com/ So What Should I Do To Use Facebook access_token with my new heroku domain and solve this error And There Are My settings.py code : import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ---------- SECRET_KEY = 'lr2g%2&4666(ghg%&dqhlzcm=f9$5&%q6l*z1+v7vh+khxackr' DEBUG = True ALLOWED_HOSTS = ["localhost","whispering-hamlet-67095.herokuapp.com"] ---------- INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'egystoreapp', 'rest_framework_social_oauth2', 'social_django', 'oauth2_provider', 'bootstrap3', ] ---------- MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ---------- ROOT_URLCONF = 'egystores.urls' ---------- TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] ---------- WSGI_APPLICATION = 'egystores.wsgi.application' ---------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } ---------- AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, … -
ModuleNotFoundError: No module named 'mysite' (PythonAnywhere0
I'm trying to deploy my Django site using PythonAnywhere. The steps I followed were from https://help.pythonanywhere.com/pages/DeployExistingDjangoProject/ This is the code in my WSGI File This is what it says in my error log