Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i am unable to publish new app to my console the button for "accept the play app signing terms of service" is disabled. Tell me what should I do
enter image description here I was trying to publish app to my console which already has two apps live since some months but i cannot publish it because the button for accept the play app signing terms of service button was disabled. I don't know why this happened please give me solution -
Not connecting Android application to Paycharm
I wrote an API with django and my API program works fine. When I use the retrofit library to receive information from the API running by Pycharm, I encounter an error "Failed to connect to /127.0.0.1:8000","Could not remove dir '/data/data/com.example.project_____uploadfile2/code_cache/.ll/': No such file or directory". API interface public interface Api { String URL1="http://127.0.0.1:8000/api/"; @GET("get-data") Call<List<models>> getname(); } MainActivity public class MainActivity extends AppCompatActivity { ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView =findViewById(R.id.listview); getname1(); } private void getname1() { Call<List<models>>call=retrofitClient.getInstance().getApi().getname(); call.enqueue(new Callback<List<models>>() { @Override public void onResponse(Call<List<models>> call, Response<List<models>> response) { List<models> modelsList =response.body(); String[] name1=new String[modelsList.size()]; for (int i=0;i<modelsList.size();i++){ name1[i]=modelsList.get(i).getName(); } listView.setAdapter(new ArrayAdapter<String>( getApplicationContext(), androidx.appcompat.R.layout.support_simple_spinner_dropdown_item ,name1)); } @Override public void onFailure(Call<List<models>> call, Throwable t) { Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show(); Log.e("erorr", t.getMessage() ); } }); } } retrofitClient public class retrofitClient { private static retrofitClient Instance=null; private Api api; private retrofitClient(){ Retrofit retrofit=new Retrofit.Builder().baseUrl(URL1) .addConverterFactory(GsonConverterFactory.create()) .build(); api =retrofit.create(Api.class); } public static synchronized retrofitClient getInstance(){ if (Instance==null){ Instance=new retrofitClient(); } return Instance; } public Api getApi(){ return api; } } models public class models { public String getName() { return name; } public void setName(String name) { this.name = name; } private String name; } I read on a … -
Anyone please help me to fix this error in Django?
I use Django for web development. When i make some changes in models then i run "Python manage.py makemigrations" and "python manage.py migrate". But at migrate code running i got some errors as follows: python manage.py makemigrations No changes detected python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, home, sessions Running migrations: Applying home.0020_image_desc_image_propertytype...Traceback (most recent call last): File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 90, in _execute return self.cursor.execute(sql, params) File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 357, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: new__home_image.desc The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\genio\OneDrive\Documents\HamroKothaProject\hello\manage.py", line 22, in main() File "C:\Users\genio\OneDrive\Documents\HamroKothaProject\hello\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management_init_.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management_init_.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 135, in migrate state = self._migrate_all_forwards( File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\genio\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\migration.py", line 130, in … -
How to create custom Django URL filter
I have set up a django project and i use the viewsets.ModelViewSet. I need to use some custom filters from my react project through url that calls to the api, something like .../model/username="Test"/ where the username is the foreignKey in my model. I deploy my backend in Heroku. Thank you I tried using different kind of ready packages, but they did not work. -
Custom User Model [closed]
I need to have a custom model for my project rather using Django's default one i need go with my own. And also i need to use Django authentication. There's an another problem when wrote a sign out view without using logout function instead i used session. fush but when press browser's back button I'm able to view the previous page is there's any alternate way to solve this??? Imma beginner at this. So basically they're saying use abstraction Base class -
backend.quote_name not working, suggest somthing to make this work
` def dump_model(model): from django.db import connection, backend opts = model._meta cursor = connection.cursor() fields, default = get_model_stru(model) cursor.execute('select %s from %s' % (','.join(map(backend.quote_name, fields)), backend.quote_name(opts.db_table))) return call_cursor(opts.db_table, fields, cursor) ` Django version I am using is 1.6.7,I tried connection.ops.quote_name, str(), also tried defining quote_name nothing seems to working -
Django Form, how to get further model info for ModelChoiceField
I have 3 models that are related to eachother. A showing has the 'film' and 'screen' foreignkeys that link to Film and Screen. I'm trying to setup a webpage so that you can view information on a showing that is already setup, and edit it from dropdowns of what films and screens are available. The problem I have at the moment is that instead of showing the screen numbers, and film titles that can be selected from, my dropdowns are showing 'Screen Object (4)' or 'Film Object (2)'. How do I get that next level of information to show from each object? My models are: class Film(models.Model): ageRatings =[ ("U", "U"), ("PG", "PG"), ("12", "12"), ("15", "15"), ("18", "18"), ] id = models.AutoField(primary_key=True) title = models.CharField(max_length=255) length = models.DurationField() rating = models.CharField(max_length=3, choices=ageRatings, default="U") genre = models.CharField(max_length=50) poster_url = models.CharField(max_length=255, default='') class Screen(models.Model): id = models.AutoField(primary_key=True) cinema = models.ForeignKey(Cinema, on_delete=models.CASCADE, related_name='screens') screen_number = models.PositiveSmallIntegerField() seating_capacity = models.PositiveIntegerField() class Showing(models.Model): id = models.AutoField(primary_key=True) film = models.ForeignKey(Film, on_delete=models.CASCADE, related_name='showings') screen = models.ForeignKey(Screen, on_delete=models.CASCADE, related_name='showings') start_time = models.DateTimeField() end_time = models.DateTimeField(null=True) available_seats = models.IntegerField() adult_price = models.FloatField() student_price = models.FloatField() child_price = models.FloatField() def save(self, *args, **kwargs): self.end_time = self.start_time + self.film.length super().save(*args, … -
django.db.utils.IntegrityError: UNIQUE constraint failed: profiles_api_userprofile.id
I have created a custom model on django to create users and superuser, and now when i try to create a superuser, i get the following error django.db.utils.IntegrityError: UNIQUE constraint failed: profiles_api_userprofile.id models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager class UserProfileManager(BaseUserManager): """Manager for user profiles""" def create_user(self, email, name, password=None): """Create a new user profile""" if not email: raise ValueError("Users must have an email address") email = self.normalize_email(email) user = self.model( email=email, name=name ) # creates a new model that the manager is representing user.set_password(password) user.save(self._db) return user def create_superuser(self, email, name, password): """Create and save a new superuser with given details""" user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(self._db) return user # is_superuser is automatically created by PermissionsMixin class UserProfile(AbstractBaseUser, PermissionsMixin): """Database model for users in the system""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserProfileManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["name"] def get_full_name(self): """Retrieve full name of user""" return self.name def get_short_name(self): """Retrieve short name of user""" return self.name def __str__(self): """Return string representation of our user""" return self.email I added the model in the settings.py … -
Django: python manage.py runserver exits with ‘Performing system checks, what is the possible issue?
I am working on a django project and have been using python manage.py runserver to spin up my development local server, but it just started exiting at Performing system checks. This is the first time i am encountering such issue, have any one experienced this issue before, please how do i go about it? C:\Users\Destiny Franks\Desktop\ecommerce_prj>python manage.py runserver Watching for file changes with StatReloader Performing system checks... C:\Users\pc-name\Desktop\ecommerce_prj>python manage.py runserver Watching for file changes with StatReloader Performing system checks... C:\Users\pc-name\Desktop\ecommerce_prj> This is how everything looks, it does not show any error message or issue, just breaks off and return to the cmd -
Check if a code exists in Django Database
I'am trying to check if a value exists in one of my database fields so this is my models.py class Student(models.Model): username = models.CharField(max_length=200, null=True, blank=True, verbose_name='نام کاربری') code = models.CharField(max_length=10, null=True, validators=[MinLengthValidator(10)], blank=True, verbose_name='کد ملی') def __str__(self) -> str: super(Student, self).__str__() return self.username class Meta: verbose_name = 'دانش آموز' verbose_name_plural = 'دانش آموزان' I can create a model in django's panel but the thing that I want, is Checking if a property of this class exists this is my views.py class LoginView(View): def get(self: Self, request: HttpRequest) -> HttpResponse: login_form: LoginForm = LoginForm() return render( request=request, template_name='index.html', context={ 'login_form': login_form, } ) def post(self: Self, request: HttpRequest) -> Union[HttpResponseRedirect, HttpResponsePermanentRedirect, None]: login_form: LoginForm = LoginForm(request.POST or None) if (login_form.is_valid()): username = login_form.cleaned_data.get('username') code = login_form.cleaned_data.get('code') # I want to check if " code " is in database # if it exists, login # else show an error I want to check if the code variable value, exists in my database and if it exists, login else show an error I expect my code check the value existance but I don't know how to do that -
Using ForeignKey key Django to reference the 'id' from another table
I want to use the user_id as a foreign key in CPA table here is my model ---models.py---- and on the Django admin admin page It show all of the user data. **Please note that the person detail on the image have been generated using Faker. I have try using this user_id = models.ForeignKey(User,to_field='id', on_delete=models.CASCADE, default=1) I want it to show just the id number which is 1 as follow expected value How can I do that?? Thank you for your reply -
Django's bulk_create doubts
I'm adding this function to my Django app, but I have a couple of questions I need to know and which I couldn't find in Google. Does it insert all records in the order the list is given? Or can they be suffle? Can I know which id corresponds to the index in the list of the items to give? In case an error happened will it prompt which one failed, and will continue inserting the others, or will it stop inserting the rest of elements? -
Updated data don't seem in DRF api response
The updated data doesn't seem in api response. When I add or update some data in admin panel it doesn't affect to api response. To fix it i must write docker-compose restart. How can i fix this problem I supposed that this problem comes from caches issue. Therefore i add cache configuration in settings like this: `CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } }` But it doesn't fix problem -
how to add Comment form inside a post detailed
Is there any way I can add a comment form inside a post's details? I have a view that shows a model object, and I want to allow users to comment on that view. I have tried to use this method, but using that method, a user should leave a post's details and add their comment somewhere else rather than doing it inside a post's details? I have try to do that using the method below, but it gives me an error every time I clicked on submit button: TypeError at /video-play/so-da-shakuwa/ Field 'id' expected a number but got <Video: videos/DJ_AB_-_Masoyiya_Official_Video_9UfStsn.mp4>. views: def play_video(request, slug): play = get_object_or_404(Video, slug=slug) if request.method == 'POST': comments = request.POST['comments'] new_comment = Comment.objects.create( comments=comments, post_id=play ) new_comment.user = request.user new_comment.save() return redirect('Videos') context = { 'play':play } return render(request, 'video/play_video.html', context) template: <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <div class="container"> <div class="row"> <div class="col-md-9"> <form action="" method="post"> {% csrf_token %} <div class="input-group"> <textarea name="comments" id="comment" cols="10" class="form-control" placeholder="write your comment"></textarea> <button class="btn btn-primary" type="submit">submit</button> </div> </form> </div> </div> </div> models: class Video(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=70) video = models.FileField(upload_to='videos') created_on = models.DateTimeField(auto_now_add=True) banner = models.ImageField(upload_to='banner') slug = models.SlugField(max_length=100, unique=True) class Comment(models.Model): user … -
Wrong Routing Django
I have a Django project with this layout in baseApp views.py def Home(request): rooms = Room.objects.all() context = {'rooms':rooms} return render(request,'base/home.html',context) def room(request,pk): room = Room.objects.get(id=pk) context = {'room':room} return render(request,'base/room.html',context) def createRoom(request): context= {} return render(request,'base/room_form.html',context) in baseApp urls.py urlpatterns = [ path('', views.Home, name="home page"), path('<pk>/', views.room, name="room"), path('create-room/',views.createRoom, name="create-room"), ] in the base/temp/home.html <h2> <a href="{% url 'create-room' %}">Create Room</a></h2> it supposed to go to to this url : 172.0.0.1:8000/create-room/ " to room_form.html" but it goes to : 172.0.0.1:8000/room/create-room with error Field 'id' expected a number but got 'create-room' I am Expecting it supposed to go to to this url : 172.0.0.1:8000/create-room/ showing room-form.html -
Creating a fully functional website that can be used [closed]
I need help, can someone please help me in finishing creating a website, it is a project I am supposed to be done with by Wednesday, I need help making the links active and functional where after clicking a website it directs you to a webpage with information also, the buttons to be made functional The website should be responsive and active and can be used the website currently looks like this: https://afia.azurewebsites.net/ourhospital/ the github repo link is: https://github.com/abayomiabiodun/AFIA-MBELE.git PLEASE HELP THANKS SOMEONE TO KINDLY HELP IN FINISHING THE WEBSITE -
Django query __in filter on subquery joined over multiple fields without foreignkey
Short: This is the SQL I try to achieve in django: with start_dates as ( select m2.person_id, min(m2.date_current) as start_date from my_table m2 where [...] group by person_id ) select * from my_table m inner join start_dates sd on m.person_id = sd.person_id and m.date_current >= sd.start_date ; Long: There is a table which I need to access twice. The table constists of activities of people. Each people has multiple activities so multiple rows in this table. 1) First access is to find for a set of given filters (like the name of the acitivity and the age of the person) which persons activities fit the filters and per person what is its oldest acitivity fitting the filters. I call that oldest-date "start_date". On SQL this could look like: select m2.person_id, min(m2.date_current) as start_date from my_table m2 where [...] group by person_id With this query I found a sub-set of people with their oldest filtered-activity (so there may be also older activities which do not fit the filters above) Sample A sample would be to find all people ever did taking drugs plus the date when it happened first. 2) Second access is to get for every person found all its … -
login with LinkedIn: Django REST and React.js
I've got problems with authentication with LinkedIn. In my React app, I created LoginButton component following documentation for react-linkedin-login-oauth2. import { useLinkedIn } from 'react-linkedin-login-oauth2'; import linkedin from 'react-linkedin-login-oauth2/assets/linkedin.png'; function Login() { const { linkedInLogin } = useLinkedIn({ clientId: '78j5bjwgkxxxxx', redirectUri: 'http://127.0.0.1:8000/dj-rest-auth/linkedin/', onSuccess: (data) => { console.log(data) }, onError: (e) => { console.log(e) } }); return ( <img onClick={linkedInLogin} src={linkedin} /> ); } export default Login That button is kinda working. As far as I'm understanding, 'redirect_URI' should point backend view, it redirects me to http://127.0.0.1:8000/dj-rest-auth/linkedin/ with code and state. But backend doesn't log me in automatically and manually (I'm trying to paste "code" form URL to "code" in form below. Then I'm getting that: My backend should work (I did everything following documentation for dj-rest-auth and allauth) from allauth.socialaccount.providers.linkedin_oauth2.views import LinkedInOAuth2Adapter from allauth.socialaccount.providers.oauth2.client import OAuth2Client from dj_rest_auth.registration.views import SocialLoginView class LinkedinLogin(SocialLoginView): adapter_class = LinkedInOAuth2Adapter client_class = OAuth2Client callback_url = 'http://127.0.0.1:8000/dj-rest-auth/linkedin/' from django.urls import path from . import views urlpatterns = [ path('accounts/', include('allauth.urls')), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('dj-rest-auth/linkedin/', views.LinkedinLogin.as_view(), name='linkedin_login'), ] Next issue is, after login with button from frontend, I'm getting "user closed the popup" error, I'm not closing or unfocusing anything, in other worlds onError is running, … -
How to deal with Django Cascade deleted objects in django-simple-history?
I have a problem with django-simple-history when I use cascade deletion on objects. I have several tables in my database that inherit from other tables, so I’ve set the deletion to cascade. The problem is that when I want to query Historical Objects generated by django-simple-history, I do have the one in the parent table, but for objects in the children table, that were automatically deleted by Django, I this error : MyApp.models.parentTable_object.DoesNotExist: parentTable_object matching query does not exist. If I understand the problem, django-simple-history tried to create a Historical object for my deleted object but failed because it needed the parent object it inherited and that no longer exists at this point. I can’t do without cascading so I hope it’s possible because django-simple-history has met all my expectations so far. Thanks you for your help My environment: OS: Windows 10 Browser: Firefox Django Simple History Version: 3.1.1 Django Version: 4.0.3 Database Version: django's integrated SqLite3 -
AttributeError: type object 'object' has no attribute 'id'
I am trying to add permissions to my Django Rest Framework Project, but i get an error: AttributeError: type object 'object' has no attribute 'id' My permissions.py file looks like this: from rest_framework import permissions class UpdateOwnProfile(permissions.BasePermission): """Allow users to edit their own profile""" def has_object_permission(self, request, view, obj): """Check user is trying to edit their own profile""" if request.method in permissions.SAFE_METHODS: return True return object.id == request.user.id My views.py class for the UserProfile looks like this: class UserProfileViewSet(viewsets.ModelViewSet): """Handle creating and updating profiles""" serializer_class = serializers.UserProfileSerializer queryset = models.UserProfile.objects.all() authentication_classes = ( TokenAuthentication, ) permission_classes = ( permissions.UpdateOwnProfile, ) My serializers.py file: class UserProfileSerializer(serializers.ModelSerializer): """Serializes a user profile object""" class Meta: model = models.UserProfile fields = ("id", "email", "name", "password") extra_kwargs = { "password": { "write_only": True, "style": { "input_type": "password" }, } } def create(self, validated_data): """Create and return a new user""" user = models.UserProfile.objects.create_user( email=validated_data["email"], name=validated_data["name"], password=validated_data["password"], ) return user def update(self, instance, validated_data): """Handle updating user account""" if "password" in validated_data: password = validated_data.pop("password") instance.set_password(password) return super().update(instance, validated_data) The traceback of the error: Traceback (most recent call last): File "/Users/xxxx/Desktop/django-rest-tutorial/django/venv/lib/python3.11/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/xxxx/Desktop/django-rest-tutorial/django/venv/lib/python3.11/site-packages/django/core/handlers/base.py", line 145, in _get_response response = … -
Choice field validation DRF
Hi all I have my model and its serializer, what I discovered when testing is that serializer is saved no matter what I have in my choice field but in Django admin choice field is empty when the data is wrong and when the data is right I can see the correct option so, -> wrong choice data -> saved regardless -> nothing in django admin -> correct choice data -> saved -> correct value in django admin How can I return validation error if I detect that user posted incorrect data? what I was trying out is topic = serializers.ChoiceField(choices=School.topic) and I don't think that iterating over each tuple and searching for a string is correct or efficient code class SchoolViewSet(viewsets.ModelViewSet): queryset = School.objects.all() serializer_class = SchoolSerializer def create(self, request): serializer = SchoolSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class School(models.Model): SUBJECT = ( ('Math', 'Mathematic'), ('Eng', 'English'), ('Cesolved', 'Chemistry'), ) name = models.CharField(blank=False, max_length=50) subject = models.CharField(choices=SUBJECT, max_length=15, blank=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return str(f'{self.name} is {self.subject}') class SchoolSerializer(serializers.ModelSerializer): subject = serializers.ChoiceField(choices=School.SUBJECT) def validate(self, data): name = data["name"] if (5 > len(name)): raise serializers.ValidationError({"IError": "Invalid name"}) return data class Meta: … -
Can i use django.db.transaction.atomic with ThreadPoolExecutor?
I have a large set of Projects to validate and update with transaction in 1 perform. If 1 project failed it need to rollback all projects. but when i use ThreadPoolExecutor it got stuck with no log ERROR or WARNING even with max_workers=1. from concurrent.futures import ThreadPoolExecutor, wait @transaction.atomic def update_projects() projects = Project.objects.filter(...) items = [(project, auth) for project in projects] with ThreadPoolExecutor(max_workers=MAX_WORKER) as executor: futures = [executor.submit(validate_and_update, *item) for item in items] wait(futures) def validate_and_update(project, auth): # get other data and validate with project. project.save() i tried multiprocessing instead of threading but it got other error like: "no results to fetch" "pop from empty list" pool = multiprocessing.Pool(processes=2) for item in items: pool.apply_async(validate_and_update, *item) # close the pool pool.close() # wait for all tasks to complete pool.join() -
Why is Source Control (VScode) asking to commit every single file on my computer to git?
I am trying to create project using Python and Django, using a virtual environment. This is how I set up the project in terminal: cd MyProject python3 -m venv env source env/bin/activate pip install django django-admin startproject (projectname) When I go to open the file in VSCode, source control scans and prompts to commit every single file on my computer (including files in the trash) to Git, to the point where it says "Too many changes were detected. Only the first 10000 changes will be shown below". Why is this happening? I tried right clicking and doing 'discard changes' but it ended up deleting files. -
issue when using django(daphne) and scrapy together
Im having issues getting my scrapy spider to work with django when using daphne. i noticed that when i use the normal wsgi server ie. without adding daphne to the list of installed apps, everything works fine as expected. but with daphne, my spider gets stuck after initial requests and never gets to parse. i have made a minimalistic reproduction of the issue , and would be very greatful with anyone can explain why this issue occurs and how to go about it resolving it. thanks PS: this is just a reproduction of the issue, as for why i need daphne, my project uses django channels project structue daphne_scrapy/ ├── daphne_scrapy │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── spiders.py │ ├── urls.py │ ├── views.py │ └── wsgi.py ├── db.sqlite3 └── manage.py settings.py (these were the only changes made to the settings.py file, added daphne and asgi_app) INSTALLED_APPS = [ 'daphne', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] WSGI_APPLICATION = 'daphne_scrapy.wsgi.application' ASGI_APPLICATION = 'daphne_scrapy.asgi.application' spider.py note: i need to do the django setup because my spider needs to made use of django models in the real project im working on. import scrapy from scrapy.crawler import CrawlerProcess … -
Docker python: can't open file 'manage.py': [Errno 2] No such file or directory
I have two questions at once (Main)I'm trying to deploy a Django project on Docker and I get a python error: can't open file '/backend/manage.py': [Errno 2] No such file or directory Can I use env_file instead of environment for Postgres ? Project structure films -backend -config -__init__.py -asgi.py -settings.py -urls.py -wsgi.py -manage.py -venv -.env -docker-compose.yml -Dockerfile -requirements.txt enter image description here Dockerfile FROM python:3.10 COPY requirements.txt /temp/requirements.txt WORKDIR /backend ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN pip install -r /temp/requirements.txt COPY . . docker-compose.yml version: '3.7' services: web: build: . container_name: films command: > sh -c "python manage.py migrate && python manage.py runserver" ports: - "8000:8000" depends_on: - db env_file: - .env db: image: postgres container_name: db_film environment: - POSTGRES_DB=films - POSTGRES_USER=username - POSTGRES_PASSWORD=password