如何在Visual Studio 2019中运行Django服务器?配置后运行报错求助
Hey there! Let's sort out that Django project running issue in Visual Studio 2019. I've been through this exact setup before, so here's a straightforward guide to get things working and take advantage of VS's killer debugging tools:
First, make sure Visual Studio is using the right Python environment for your Django project:
- Go to
Tools→Python→Python Environmentsfrom the top menu bar - In the pop-up window, locate the virtual environment (if you're using one) tied to your project, and confirm it's set as the active environment for the project
- Verify Django is installed in this environment: Switch to the
Packagestab, search fordjango, and ensure the version matches what your project requires
You've set manage.py as the launch file, but we need to tweak the run parameters to make it work:
- Right-click your project →
Properties→ Navigate to theDebugtab - In the
Command Argumentsfield, typerunserver(this is the Django command to start the dev server) - Confirm the
Working Directorypoints to your Django project's root folder (the one that containsmanage.py). If it's wrong, click the browse button to select the correct path
Here are the most frequent issues you might be hitting, and how to fix them:
Error:
ModuleNotFoundError: No module named 'django'
Cause: The active Python environment doesn't have Django installed
Fix: Open Visual Studio'sPython Interactivewindow, and runpip install django==x.x.x(replacex.x.xwith your project's required Django version). Alternatively, activate your project's virtual environment and run the same command.Error:
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS...
Cause: The working directory is incorrect—Django can't find your project's settings file
Fix: Head back to step 2 and double-check that theWorking Directoryis set to your project's root folder (e.g.,C:\Users\YourName\Projects\my_django_project)Error:
CommandError: You must set settings.DATABASES...
Cause: Database configuration is missing or migrations haven't been run
Fix:- Open the
Python ConsoleviaTools→Python→Python Console, then runpython manage.py migrate - If using the default SQLite, make sure the
db.sqlite3file in your project root has read/write permissions. For other databases (like MySQL), verify theDATABASESsection insettings.pyhas the correct credentials and connection details
- Open the
- Click
Debug→Start Debugging(or press F5) - If everything's set up right, the CMD window will show a message like:
Starting development server at http://127.0.0.1:8000/ - Open your browser and visit that URL—you should see Django's default welcome page!
Pro tip: Visual Studio's debugging tools are really powerful here. You can set breakpoints in your views.py, models.py, or any other code files, use F10 to step through lines, and inspect variable values in real-time. It's a game-changer for debugging complex Django workflows.
内容的提问来源于stack exchange,提问作者user12125534

