Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django generic view redirect
I have created a blog app using Django wherein Generic views are used to Add, Update and Delete a blog post. I want to know a method by which I could redirect to the same Blog page after creating it or updating it. Thanks -
view function is not being executed
I was trying to make a basic banking system using django, in which a user can transfer money to other user. But when I tried to transfer money nothing happens, probably because transfer function in views.py is not being executed. Here are transaction.html file and transfer function from views.py.: transaction.html ''' {% extends 'bank/base.html' %} {% block content %} <div class="container"> <h2>Transfer Money</h2> <form method="post"> {% csrf_token %} <label for="s_acc">Select sender details</label> <select name="s_acc" required> <option value="select">Select</option> {% for cust in customer %} <option value="{{cust.account_number}}">{{cust.name}}: {{cust.account_number}} : {{cust.balance}}</option> {% endfor %} </select> <br> <label for="amt">Enter amount</label> <input type="number" name="amt" required> <br> <label for="r_acc">Select receiver details</label> <select name="r_acc" required> <option value="select">Select</option> {% for cust in customer %} <option value="{{cust.account_number}}">{{cust.name}}: {{cust.account_number}} : {{cust.balance}}</option> {% endfor %} </select> <br> <button type="submit" name="button">TRANSFER</button> </form> </div> {% endblock %} ''' transfer function from vews.py: def Transfer(request): customer = Customer.objects.all(); if request.method=="POST": s_acc = request.POST.get('s_acc') amt = request.POST.get('amt') r_acc = request.POST.get('r_acc') print(s_acc) print(amt) print(r_acc) amt = int(amt) if((s_acc=='select')or(amt=='select')or(r_acc=='select')or(s_acc==r_acc)): messages.warning(request,"Account not selected or both the accounts are same") elif(amt<=0): messages.warning(request,"Enter valid amount") else: for c in customer: if(c.account_number == s_acc): s_name = c.name; if(amt>c.balance): messages.warning(request,"Insufficient balance") break for x in customer: if(x.account_number == r_acc): r_name = x.name … -
CORS issue working with DJango Simple SSO
I'm using a fork of Django Simple SSO as an authentication mechanism on a Server. It works great while we use the "standard" way to log in on the server. This means, we just access to the /login path, log in, and then navigate across the restricted paths, etc. The problem comes when we want to connect to a 3rd server that also relays on SSO auth vía javascript/AJAX without direct access to /login path first. I've tried to use django-cors-headers but didn't get the expected result. I'm close to give up so any help is welcome. The problem When the browser is redirected to the Auth Server in order to verify that the browser is logged with a valid user, the cookie header is not transferred. (See the diagram on button for further details on how Simple SSO works) The headers set by the auth-server on the preflight request are the following: Access-Control-Allow-Credentials: true Access-Control-Allow-Headers: accept-encoding, accept, authorization, cookie, content-type, dnt, origin, user-agent, x-csrftoken, x-grafana-org-id, x-dashboard-id, x-panel-id, x-requested-with Access-Control-Allow-Methods: DELETE, GET, OPTIONS, PATCH, POST, PUT Access-Control-Allow-Origin: https://client-server-domain Access-Control-Max-Age: 86400 Connection: keep-alive Content-Length: 0 Content-Type: text/html; charset=utf-8 Date: Fri, 16 Jul 2021 12:14:54 GMT Server: nginx Vary: Origin The headers … -
I got IntegrityError with delet user in django
When I delete user , I got this error. There are some problems with moving django-registration-redux(django-registration) to django-allauth. So I was trying to drop registration_registrationprofile table. But I can't find that table. I can only see those tables. It isn't look like related to this problem. How can I delete user succesfully? account_emailaddress papers_paperstatus account_emailconfirmation papers_signature addresses_address papers_verifyingexplanation auth_group profiles_alloweduser auth_group_permissions profiles_alloweduser_allowed_users auth_permission profiles_customuser authtoken_token profiles_customuser_groups django_admin_log profiles_customuser_user_permissions django_content_type profiles_expertprofile django_migrations profiles_mandate django_session profiles_profile django_site socialaccount_socialaccount papers_contractor socialaccount_socialapp papers_explanationsignature socialaccount_socialapp_sites papers_paper socialaccount_socialtoken Those are error stacks. IntegrityError at /api/user/25/ update or delete on table "profiles_customuser" violates foreign key constraint "registration_registr_user_id_5fcbf725_fk_profiles_" on table "registration_registrationprofile" DETAIL: Key (id)=(25) is still referenced from table "registration_registrationprofile". Request Method: DELETE Request URL: https://dev.onepaper.biz/api/user/25/ File "/home/ubuntu/djangovenv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 242, in _commit return self.connection.commit() The above exception (update or delete on table "profiles_customuser" violates foreign key constraint "registration_registr_user_id_5fcbf725_fk_profiles_" on table "registration_registrationprofile" DETAIL: Key (id)=(25) is still referenced from table "registration_registrationprofile". ) was the direct cause of the following exception: File "/home/ubuntu/djangovenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/ubuntu/djangovenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/djangovenv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/ubuntu/djangovenv/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) … -
Customizing the Ordering Field in ElasticSearch in Django_Restful_framework
class PublisherDocumentView(DocumentViewSet): document = RecommendationDocument serializer_class = RecommendationElasicSerializer lookup_field = 'id' fielddata = True filter_backends = [ FilteringFilterBackend, CompoundSearchFilterBackend, DefaultOrderingFilterBackend, OrderingFilterBackend, SearchFilterBackend, SuggesterFilterBackend, # This should be the last backend ] search_fields = ( 'sku','artikelNr1','artikelNr2', 'statusCode' ,'statusText' ,'saisonRetourenCode','saisonRetourenText','saisonCode','saisonText','geschlechtCode','geschlechtText','rayonCode','rayonText','warenArtCode','warenArtText','wuCode','wuText','waCode','warenGruppe','alterCode','farbe','material','bezeichnung','pictureName','picturePathLocal','kollektion','comCode' ,'lieferant','eKchf','eti','vp','groessenCode','categories','groessen','zlQty', 'productId','published','productName','shortDescription','fullDescription','flag' ) multi_match_search_fields = ( 'sku','artikelNr1','artikelNr2', 'statusCode' ,'statusText' ,'saisonRetourenCode','saisonRetourenText','saisonCode','saisonText','geschlechtCode','geschlechtText','rayonCode','rayonText','warenArtCode','warenArtText','wuCode','wuText','waCode','warenGruppe','alterCode','farbe','material','bezeichnung','pictureName','picturePathLocal','kollektion','comCode' ,'lieferant','eKchf','eti','vp','groessenCode','categories','groessen','zlQty', 'productId','published','productName','shortDescription','fullDescription','flag' ) filter_fields = { 'artikelNr1': 'artikelNr1.raw', 'artikelNr2': 'artikelNr2.raw', 'statusText': 'statusText.raw', 'flag': 'flag.raw', } ordering_fields = { 'flag': 'flag.raw', } ordering = ('flag', ) I want to customize the ordering of this "flag" field based on their value like "isMust or IsNew" suppose to come first in ordering field. do you guys know how to do this? any body has any idea how to fix these problems. Thanks in advance -
How to use gulp in django project
I downloaded the "Neumorphism" template from the Internet and want to use it in my Django project. When I added the HTML and CSS files to my project separately, the drop down page on the mobile page did not open. I realized that I had to use the gulp file in the project. But I need to learn the steps to add a template that uses gulp and nodejs. I'm using virtualenv and need to know how to configure the file structure to work properly when running the server?(python manage.py runserver) And another question, to upload the site to the server, what are the conditions for using gulp on a personal computer? -
How to filter from two related models in django
This is my model class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='profile') mob_no = models.CharField(max_length=10,blank=False,default=None) address = models.TextField(blank=False,default=None) country = models.CharField(max_length=80,blank=False,default=None) pin = models.PositiveIntegerField(blank=False,default=None) sponsor_id = models.CharField(max_length=15,blank=False,default=None) #ref id is sponsor id of the person who added the user. ref_id = models.CharField(max_length=15,blank=False,default=None) class Meta: verbose_name_plural = "User Profile" def __str__(self): return self.user.username #---------------------------------------------User Payment Details------------------------------------------------------ class UserPaymentProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='payprofile') selected_product = models.CharField(max_length=80,blank=False,default='NIL') payment_status = models.BooleanField(default=False) Tid = models.CharField(max_length=40,blank=False,default=0) class Meta: verbose_name_plural = "User Payment Profile" def __str__(self): return self.user.username I am trying to get list of users with a specific sponsor_id and payment_status == True I could not fin a way to filter from both related models -
Multiplying the values of two different models in Django
Well i'm trying to create two models whereas the product model is: class Product(models.Model): id = models.AutoField(primary_key=True) price = models.FloatField(null=False) inStock = models.BooleanField(null=False) and another model for cart where: class Cart(models.Model): productID = models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.IntegerField() total I want total here to equal Product.price multiplied by the Cart.quantity Is there a way how can I achieve it on Django? -
Valid (?) JSON data causing errors in Django, must be served to frontend as string and converted by JSON.parse() in javascript - why?
I have a JSON file hosted locally in my Django directory. It is fetched from that file to a view in views.py, where it is read in like so: def Stops(request): json_data = open(finders.find('JSON/myjson.json')) data1 = json.load(json_data) # deserialises it data2 = json.dumps(data1) # json formatted string json_data.close() return JsonResponse(data2, safe=False) Using JsonResponse without (safe=False) returns the following error: TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False. Similarly, using json.loads(json_data.read()) instead of json.load gives this error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) This is confusing to me - I have validated the JSON using an online validator. When the JSON is sent to the frontend with safe=False, the resulting object that arrives is a string, even after calling .json() on it in javascript like so: fetch("/json").then(response => { return response.json(); }).then(data => { console.log("data ", data); <---- This logs a string to console ... However going another step and calling JSON.parse() on the string converts the object to a JSON object that I can use as intended data = JSON.parse(data); console.log("jsonData", data); <---- This logs a JSON object to console But this solution doesn't strike me as a complete … -
Django - Get URL from DB and use it as src in in iframe
I have simple requirement. There is a URL that is stored in DB. I need to retrieve this URL from the DB and in my template use this URL as SRC value in an iframe. Model.py: from django.db import models # Create your models here. class DashboardLink(models.Model): dashboard_url = models.CharField(max_length=255, unique=True) Views.py from django.shortcuts import render from .models import DashboardLink def index(request): dashboard_url = DashboardLink.objects.all() return render(request, 'index.html') In Index.html I have the following code, in which I want to use the url retrieved from the DB. index.html <p>{{ dashboard_url.dashboard_url }}</p> ### This is to just check if the data is being fetched or not.. This too results in blank. #### <section> <iframe width="100%" height="700" src="{% for item in dashboard_url %} {{ item }} {% endfor %}" frameborder="0" allowfullscreen></iframe> </section> <br><br> </div> In urls.py I have the following code: *urls.py* path('index/', logged_in_views.index, name='index'), When I use Inspect, I see the following [![enter image description here][1]][1] Can someone please help me in understanding what am I missing? [1]: https://i.stack.imgur.com/C7Oek.png -
Updating User details in UserDetail Table using One-To-One Relation Django Rest API
I am new to Django. I am trying to update User details in another table using One-To-One relation by following Django document but is giving me an error. Creating a new user is working fine Models.py class UserDetails(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) phone=models.CharField(max_length=10) address=models.CharField(max_length=200,default="") created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) objects=models.Manager() def __str__(self): return self.user.username Serializer.py class UserDetailsSerializer(serializers.ModelSerializer): class Meta: model = UserDetails fields= ['phone','address'] class CreateUserSerializer(serializers.ModelSerializer): userdetails=UserDetailsSerializer() class Meta: model = User fields=['id','url','username','email','password','userdetails'] def create(self,validated_data): user_data=validated_data.pop('userdetails') user=User.objects.create_user(**validated_data) UserDetails.objects.create(user=user,**user_data) user.save() return user def update(self,instance,validated_data): user_data=validated_data.pop('userdetails') user=User.objects.update(**validated_data) UserDetails.objects.update(user=user,**user_data) user.save() return user The error I get - (1062, "Duplicate entry 'admin' for key 'auth_user.username'") I know we can update it column by column but I want to update all columns at once as I have a lot of columns. I want a method similar to create. One more question is that can I combine these create and update as they are doing the same thing? -
transaction in ethereum ropsten net
I'm trying to make a transaction in a ethereum ropsten testnet, and I receive the ether from ropsten ethereum faucet, but when I try to send the transaction raise this error: ValueError: {'code': -32000, 'message': 'insufficient funds for gas * price + value'}. How can i do? This is my code: from web3 import Web3 def sendTransaction(message): w3 = Web3(Web3.HTTPProvider('https://ropsten.infura.io/v3/af2c9d3063c34f29aed833341a7a0b90')) address = '' #address of wallet privateKey = '' #privatekey nonce = w3.eth.getTransactionCount(address) gasPrice = w3.eth.gasPrice value = w3.toWei(0, 'ether') signedTx = w3.eth.account.signTransaction(dict( nonce=nonce, gasPrice=gasPrice, gas=100000, to='0x0000000000000000000000000000000000000000', value=value, data=message.encode('utf-8') ), privateKey) tx = w3.eth.sendRawTransaction(signedTx.rawTransaction) txId = w3.toHex(tx) return txId -
Trying to get value of a subprocess
I am creating a function to test connection and to get value but it is not working. I'm using a grep to get only received value. def testConnection(ip): TIMEOUT = 10 args = ('sudo', 'ping', '-c', '1', '-q', ip, '|', 'grep -E -o', '"[0-9]+ received"', '|', 'cut', '-f1', '-d') try: popen = subprocess.Popen(args, stdout=subprocess.PIPE) popen.wait(timeout=TIMEOUT) if (popen == 1): print(ip + " is up") else: print(ip + " is down") except subprocess.TimeoutExpired as e: print(e) return False if(popen.returncode != 0): raise ServiceException() -
while I am hovering on main category then I am getting a drop down of sub category. but it hiding behind another div. How to prevent
while I am hovering to an main category I am getting fine sub category drop down but the sub category drop down is hiding behind the image as you can see in the image I have attached.So here I have use "z-index:1" but it is not working so how to solve this issue please let me know <div class="dropdownCategory"> <a class="dropbtnCat" href="{% url 'coupons' Categories.cat_name %}">{{Categories.cat_name}}<i class="arrow-indicator fa fa-angle-right" aria-hidden="true"></i></br></a> <div class="dropdown-contentCat"> {% for subCategories in SubCategoriesBar %} {% if Categories.cat_id == subCategories.parent_id %} <a href="{% url 'coupons' subCategories.cat_name %}">{{subCategories.cat_name}}</a> {% endif %} {% endfor %} </div> </div> css .dropdown-contentCat { display: none; position: absolute; background-color: #f1f1f1; min-width: 160px; box-shadow: 0px 8px 16px 0px rgb(0 0 0 / 20%); z-index: 1; left: 101%; top: -2px; border-top: 2px solid #DB0038; font-size: 14px; } -
How to save data in both (user and profile) tables using django signals in a single request?
I have a register form with fields(firstname, lastname, username, email, dateofbirth, phoneno.) I have used signals to create a record in userprofile. whenever a new userdata is added to the user table what i want is whenever user post the request. the data should get saved in user table and then the signal creates a record in profile table and then the remaining data should also get populated in there respected fields. As I'm receiving all the data from user at the registration time. views.py def register(request): if request.method == "POST": print(request.POST) first_name = request.POST.get('first-name') <-----user table last_name = request.POST.get('last-name') <-----user table username = request.POST.get('username') <-----user table email = request.POST.get('email') <-----user table gender = request.POST.get('gender') <-----profile table date_of_birth = request.POST.get('date-of-birth') <-----profile table address = request.POST.get('address') <-----profile table phone_number = request.POST.get('mob-number') <-----profile table ans_1 = request.POST.get('ans-1') <-----profile table ans_2 = request.POST.get('ans-2') <-----profile table User.objects.create_user(first_name=first_name, last_name=last_name, email=email, username=username, last_login=timezone.now()) return render(request, 'authentication/register.html') signals.py @receiver(post_save, sender=User) def create_user_info(sender, instance, created, **kwargs): if created: UserInformation.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_info(sender, instance, **kwargs): instance.userinfo.save() -
Django-cron check running proceses
Is there any way to get the crons that are runging and wich one? if any. I'm usign the library Django-Cron: https://django-cron.readthedocs.io/en/latest/index.html ¿Why? I want to allow the user to start a process with an action from Admin site. But if the process is running I will skip the order and deliver the message that there's a process already running. Thank you. -
Django change temporary path while uploading files
By default Django stores all its temp files in "/tmp" when files are uploaded. I tried to change the FILE_UPLOAD_TEMP_DIR in settings.py to give a custom path. But Django fails to take the new path. Tried the following properties in settings.py FILE_UPLOAD_HANDLERS = ( 'django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler', ) FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 FILE_UPLOAD_TEMP_DIR = "/datadrive/test" MEDIA_ROOT = '/datadrive/test' SESSION_FILE_PATH = '/datadrive/test' FILE_UPLOAD_DIRECTORY_PERMISSIONS = 0o644 FILE_UPLOAD_PERMISSION = 0o644 -
I can't view my template with render in django
My template with called hello.html <h1>Hello World</h1> My views.py from django.shortcuts import render from django.http import HttpResponse def say_hello(request): return render(request,'hello.html') Also if i try return HttpResponse('Hello World') it is working. But rander is not working. -
HTML Modal not functioning in Django application
I am trying to implement this codepen into my Django program. I don't know why, but I just can't get it to work. I have all of the classes and everything names correctly, but my program does not do anything. I want the user to be able to click on the view button and have an HTML overlay exactly like the one in the codepen come up, but for some reason nothing is happening when I click on the button. Can someone please take a look and tell me what I am doing wrong? Thank you. HTML: {% extends 'suppliesbase.html' %} {% load static %} {% block content %} <div class="row"> {% for donation in donations %} <div class="col-lg-4"> <img class="thumbnail" src="{{donation.imageURL}}"> <div class="box-element product"> <h6><strong>{{donation.title}}</strong></h6> <hr> <button class="btn btn-outline-success" id="openModalBtn" href="#">View</button> <h4 style="display: inline-block; float: right"><strong>Free!</strong></h4> </div> </div> {% endfor %} </div> <!--Modal Overlay Content --> <div id="modal-overlay"> <div id="modal"> <div class="head"> <a id="close-modal-button" href="javascript:;"></a> </div> <div class="content">Modal content</div> </div> </div> <script> var openModalButton = document.getElementById("open-modal-button"); var closeModalButton = document.getElementById("close-modal-button"); var modalOverlay = document.getElementById("modal-overlay"); var modal = document.getElementById("modal"); // function that open modal and display the overlay openModalButton.addEventListener("click", event => { modalOverlay.classList.add("modal-overlay-visible"); modal.classList.add("modal-visible"); }); // function that closes the … -
Django: Ignore transaction for given update
I have a long-running process that should be atomic (Larger update of an application's data). However, during the update, I'd like to let the user know about the progress. How can I update a model from within the transactioned code, such that it is not part of said transaction? One potential solution would be to use non-DB storage, such as files, or a second DB connection with the same credentials. Both don't feel like the "right" way to do it... -
Django-selenium How to make download button work on a webclient of another website
I am building a website with Django. It displays the content of another website by scraping parts of its HTML with selenium and incorporating that code in my webpage to make it look better. For example, in one page, a table is passed to my website through the context and it's incorporated this way {% extends 'home.html' %} {% block content %} {{ table_name|safe }} {% endblock %} This table also has a download button in each row, and the number of rows changes over time (I don't know if that matters but anyway). In the table the download button is displayed but it doesn't work. Is there any way I can make it work? You should also know that the download button does not redirect to a link. -
Try, Except is not giving required result in django serializers create method. the getobject statements gives required result if put is outside try:
class BeneficiarySerializer(serializers.Serializer): class Meta: model = Beneficiary fields ='__all__' def create(self, validated_data): try: available = Beneficiary.objects.get(coupon_code=validated_data['coupan_code']) raise serializers.ValidationError("The provided coupon code is already utilized") except: return super().create(validated_data) class Coupon(models.Model): sl_no = models.CharField(max_length=50, primary_key=True) c_code = models.CharField(max_length=50, blank=True) def __str__(self): return self.c_code class Beneficiary(models.Model): name = models.CharField(max_length=50) coupon_code = models.ForeignKey(Coupon, on_delete=models.CASCADE) def __str__(self): return self.name purpose is to issue a coupon to only one person, if the same coupon code is issued to another in that case Serializers should raise and error that the key is issued to someone. if i put the code in try and except every time the verification fails, the same coupon code is allotted to many, if use objects.get outside try: statement is return result is found. please let me know if i am not using try: except in proper way or any other way to deal with this situation -
Why Python String auto convert into Date in microsoft excel
I am writing data into a CSV file. file contains data related to student marks like 6/10, which means 6 out of 10. issues are when I open this file with Microsoft excel 6/10 becomes 6-Oct. here is anyone have an idea how can we stop to converting a string to date. need solution from code side not an excel side -
NameError: name 'StudentsSubscription' is not defined IN DJANGO SAVE METHOD
I am trying to filter entries from the child model in parent model save method to show in admin pannel,But getting this error class StudentsSubscription(models.Model): student = models.ForeignKey('student.Student', on_delete=models.CASCADE,blank=True,null=True,help_text = "This Field Is Mandatory") enrolled_activity = models.ForeignKey('student.EnrolledActivity', on_delete=models.CASCADE,blank=True,null=True,help_text = "This Field Is Mandatory") teachers_class = models.ForeignKey('teacher.TeachersClass',on_delete=models.CASCADE,blank=True,null=True,related_name='subscription_name') demo_class = models.BooleanField(default=False,blank=True,null=True) is_finished = models.BooleanField(default=False,blank=True,null=True) channel_name = models.CharField(max_length=250,blank=True,null=True) count = models.IntegerField(default=0,blank=True,null=True) room_id = models.IntegerField(blank=True,null=True) is_active = models.BooleanField(default=False,blank=True,null=True) class TeachersClass(models.Model): class_name = models.CharField(max_length=250,blank=True,null=True) description = models.TextField(blank=True,null=True) batch_size = models.IntegerField(default=0) seats_left=models.IntegerField(default=0) image = models.ImageField(upload_to='teacher/class',blank=True,null=True) teacher = models.ForeignKey(Teacher,on_delete=models.CASCADE,blank=True,null=True,help_text = "This Field Is Mandatory") grade = models.ForeignKey(Grade,on_delete=models.CASCADE,blank=True,null=True,help_text = "This Field Is Mandatory") activity = models.ForeignKey(Activity,on_delete=models.CASCADE,blank=True,null=True,help_text = "This Field Is Mandatory") days = models.ManyToManyField(DaysOfWeek,blank=True) date = models.DateField(blank=True,null=True,help_text = "This Field Is Mandatory") start_time = models.TimeField(blank=True,null=True,help_text = "This Field Is Mandatory") end_time = models.TimeField(blank=True,null=True,help_text = "This Field Is Mandatory") is_active = models.BooleanField(default=False,blank=True,null=True) agora_token = models.CharField(max_length=250,blank=True,null=True) free_trial = models.BooleanField(default=False,blank=True,null=True) background1 = models.CharField(max_length=250,blank=True,null=True) background2 = models.CharField(max_length=250,blank=True,null=True) button_color1 = models.CharField(max_length=250,blank=True,null=True) button_color2 = models.CharField(max_length=250,blank=True,null=True) image = models.ImageField(upload_to='class/image',blank=True,null=True) def save(self, *args, **kwargs): all_admissions=StudentsSubscription.objects.filter(teachers_class__class_name=self.class_name).count() print(all_admissions) super(TeachersClass, self).save(*args, **kwargs) I am unable to figure out the issue -
How to access a file outside from a docker container?
I am using django as my framework. To manage the server we are using docker. When I try to run: docker-compose exec -T web python3 manage.py shell < /data01/ipse/litework/second_level_controller/load.py to load some data I get the following Error: File "/code/second_level_controller/DataBaseLoader.py", line 53, in load_filenames with open(os.path.join(self.data_directory, 'manifest.txt')) as f: FileNotFoundError: [Errno 2] No such file or directory: '/data01/ipse/rawdata/manifest.txt' But the file /data01/ipse/rawdata/manifest.text exists and I can acces the file normally with: nano /data01/ipse/rawdata/manifest.txt How can I access the file correctly?