Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Containers in pod won't talk to each other in Kubernetes
I have three containers in a pod: nginx, redis, custom django app. It seems like none of them talk to each other with kubernetes. In docker compose they do but I can't use docker compose in production. The django container gets this error: [2022-06-20 21:45:49,420: ERROR/MainProcess] consumer: Cannot connect to redis://redis:6379/0: Error 111 connecting to redis:6379. Connection refused.. Trying again in 32.00 seconds... (16/100) and the nginx container starts but never shows any traffic. Trying to connect to localhost:8000 gets no reply. Any idea whats wrong with my yml file? apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: creationTimestamp: null name: djangonetwork spec: ingress: - from: - podSelector: matchLabels: io.kompose.network/djangonetwork: "true" podSelector: matchLabels: io.kompose.network/djangonetwork: "true" --- apiVersion: v1 data: DB_HOST: db DB_NAME: django_db DB_PASSWORD: password DB_PORT: "5432" DB_USER: user kind: ConfigMap metadata: creationTimestamp: null labels: io.kompose.service: web name: envs--django --- apiVersion: apps/v1 kind: Deployment metadata: labels: io.kompose.service: web name: web spec: replicas: 1 selector: matchLabels: io.kompose.service: web strategy: type: Recreate template: metadata: labels: io.kompose.network/djangonetwork: "true" io.kompose.service: web spec: containers: - image: nginx:alpine name: nginxcontainer ports: - containerPort: 8000 - image: redis:alpine name: rediscontainer ports: - containerPort: 6379 resources: {} - env: - name: DB_HOST valueFrom: configMapKeyRef: key: DB_HOST name: envs--django - name: DB_NAME … -
If Select choice option is selected shows something in the django
I'm using django forms to make a user registration form and it has two different types of users I want that when selecting one of the types of user, in the html it shows registration information specific to that type of user example: if I choose a doctor I will ask for his medical identification, if I choose a patient with a medical history Like this -
Issue with pip install [Any package] on windows server
Good morning everyone I am having a serious issue with my Django projetc. After typing this : pip install django Here is the outcome : ERROR: Exception: Traceback (most recent call last): File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\cli\base_command.py", line 173, in _main status = self.run(options, args) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\cli\req_command.py", line 203, in wrapper return func(self, options, args) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\commands\install.py", line 315, in run requirement_set = resolver.resolve( File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\resolution\resolvelib\resolver.py", line 94, in resolve result = self._result = resolver.resolve( File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_vendor\resolvelib\resolvers.py", line 472, in resolve state = resolution.resolve(requirements, max_rounds=max_rounds) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_vendor\resolvelib\resolvers.py", line 341, in resolve self._add_to_criteria(self.state.criteria, r, parent=None) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_vendor\resolvelib\resolvers.py", line 172, in _add_to_criteria if not criterion.candidates: File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_vendor\resolvelib\structs.py", line 151, in bool return bool(self._sequence) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\resolution\resolvelib\found_candidates.py", line 140, in bool return any(self) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\resolution\resolvelib\found_candidates.py", line 128, in return (c for c in iterator if id(c) not in self._incompatible_ids) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\resolution\resolvelib\found_candidates.py", line 29, in _iter_built for version, func in infos: File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\resolution\resolvelib\factory.py", line 272, in iter_index_candidate_infos result = self._finder.find_best_candidate( File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\index\package_finder.py", line 851, in find_best_candidate candidates = self.find_all_candidates(project_name) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\index\package_finder.py", line 798, in find_all_candidates page_candidates = list(page_candidates_it) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\index\sources.py", line 134, in page_candidates yield from self._candidates_from_page(self._link) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\index\package_finder.py", line 758, in process_project_url html_page = self._link_collector.fetch_page(project_url) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\index\collector.py", line 490, in fetch_page return _get_html_page(location, session=self.session) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\index\collector.py", line … -
No related, column doesn't exist, None by None
Good night. Can someone explain me what happened in my situation? I have models and databases. When I decided to add some additional field in development, I often have issues like in the title of the question. So what I was doing to fix this. I'm using migrate --fake and deleted with migrations and returned back again with migrations. Obviously it works, but I still can't understand this magic.) But ok it works for me. When I deployed the code in production it displayed me again this errors. And I repeated the steps for production. It can be OK for me, but today I lost my data, it transformed into None by None. Is it because I add to new fields such attributes like null=True, blank=True? Or it happened because I have issues with migrations and I often faked them? -
Pass data from one form to another one in Django forms/views
I'm not too knowledgeable in Django, but I wanted to implement this idea that I have but I can't seem to think how to get there. Now, on my web app, there is a form with a field called "contractor", and it has a button which, when clicked, opens a modal with another form with different fields about the "contractor". I would like it to, when information is submitted about the contractor in the second form, it autofills the field in the first form with the data from the first field of the second form. Also, I want to make it so that when the user starts typing in that "contractor" field in the first form, already submitted data can be chosen. I leave my code here to give you an idea: models.py class Contratos(models.Model): name=models.CharField(max_length=30) contractor=models.ForeignKey(Vendors, on_delete=models.CASCADE, to_field='contractee_vendor') contractee=models.CharField(max_length=30) [......] class Vendors(models.Model): contractee_vendor=models.CharField(max_length=30, unique=True) company=models.CharField(max_length=30) description=models.TextField() [......] views.py def ContractView(request): form=contractsform(request.POST) if form.is_valid(): con =form.save() return redirect('contracts', con.id) else: form = contractsform() return render(request, 'contform.html', {'form': form}) class VendorsModal(BSModalCreateView): template_name = 'vendform.html' form_class = vendorsform success_message = 'Success: Vendor created' success_url = reverse_lazy('new-contract') from my contracts HTML to open modal <form action="" method=POST> {% csrf_token %} <label for="{{ form.subject.id_for_label … -
Django 4.x - Conditional QuerySet for Pagination and a many-to-many relationship
Disclaimer: I have searched and a question tackling this particular challenge could not be found at the time of posting. The Requirement For a Class Based View I need to implement Pagination for a QuerySet derived through a many to many relationship. Here's the requirement with a more concrete description: Many Library Records can belong to many Collections Web pages are required for most (but not necessarily all) Collections, and so I need to build views/templates/urls based on what the client identifies as required Each Collection Page displaying the relevant Library Records requires Pagination, as there may be 100's of records to display. The First Approach And so with this requirement in mind I approached this as I normally would when building a CBV with Pagination. However, this approach did not allow me to meet the requirement. What I quickly discovered was that the Pagination method in the CBV was building the object based on the declared model, but the many to many relationship was not working for me. I explored the use of object in the template, but after a number of attempts I was getting nowhere. I need to display Library Record objects but the many to many … -
Celery not getting ready message not comming
I'm having a bizarre problem when I run my celery it's loading but not giving the ready message, if I run any task it is running the function but not giving any success message within seconds this is my celery.py **from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ontym.settings') app = Celery('ontym') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks()** celery server tasks.py from celery import shared_task @shared_task def hello_task(name): print("hello from task",name) result -
How to add an pre-seleted photo in file-upload filed?
My Form Image I am working on a upload post page which includes images. When I am on update page I want my previously uploaded photo to be chosen already in the file-upload field. I am doing like this in my html file but it is not working <div class="qq-uploader-buttonText-value"> </div> <input type="file" id="input_22" name="photo1" class="form-control-file" data-imagevalidate="yes" data-file-accept="pdf, doc, docx, xls, xlsx, csv, txt, rtf, html, zip, mp3, wma, mpg, flv, avi, jpg, jpeg, png, gif" data-file-maxsize="10854" data-file-minsize="0" data-file-limit="" value="{{Posts.photo1.url}}" data-component="fileupload" /> </div> Can anyone help me how I do this? -
backend doesn't found for apple auth
I use django auth system with this document I set each BACKENDS in settins.py AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.apple.AppleIdAuth', 'social_core.backends.facebook.FacebookOAuth2', ) then try to use url in template. <a href="{% url 'social:begin' 'google-oauth2' %}">Google login</a> <a href="{% url 'social:begin' 'apple' %}">Apple login</a> <a href="{% url 'social:begin' 'facebook' %}">Facebook login</a> google and facebook works correctly, but for apple shows 404 error Page not found (404) Backend not found How can I find the template name for apple?? -
Djnago rest framework how to overwrite update method for allow only update user onw content
I don't want to allow any user update another user object. I want to allow only update user own content. here is my code: models.py class Blog(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) blog_title = models.CharField(max_length=200, unique=True) views.py class BlogViewSet(viewsets.ModelViewSet): queryset = Blog.objects.all() serializer_class = BlogSerializer pagination_class = BlogPagination lookup_field = 'blog_slug' def update(self, request, slug=None): pass -
I was learning django and I dont understand what's happening here, what is the logic
if removepunc == "on": punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' analyzed = "" for char in djtext: if char not in punctuations: analyzed = analyzed + char params = {'purpose':'Removed Punctuations', 'analyzed_text': analyzed} return render(request, 'analyze.html', params) else: return HttpResponse("Error") So basically this removes punctuations from a sentence and I'm not getting the loop part of the program. If anyone could explain, it would be great! Thanks -
Best way to list image URLs in a json
I know this is more of a python question than a fastAPI question. I want to know which method is the best way to list my image urls in a json and how to implement it in my json response. This is my current json data: "imgs_url": [ "http://10.0.2.2:8000/static/product_images/f3e6421737643e583a1d.jpg, http://10.0.2.2:8000/static/product_images/b53bf8aeb27d27a739cc.jpg, http://10.0.2.2:8000/static/product_images/75a80e7c04ebaed3e425.jpg" ] This is the python function i am using to get the firt list: async def create( name: str = Form(...), price: float = Form(...), description: str = Form(...), files: List[UploadFile] = File(...), db: Session = Depends(get_db), current_user: Vendor = Depends(get_current_active_user) ): fileList = [] for file in files: try: FILEPATH = "./static/product_images/" pimage_name = FILEPATH + imghex(file.filename) contents = await file.read() with open(pimage_name, 'wb') as f: f.write(contents) except Exception: return {"message": "There was an error uploading the file(s)"} finally: await file.close() # fileList.append("localhost:8000" + pimage_name[1:]) fileList.append("http://10.0.2.2:8000" + pimage_name[1:]) file_urls = ", ".join(fileList) new_item = Product( name=name, price=price, description=description, imgs_url=[file_urls], owner_id=current_user.id ) db.add(new_item) db.commit() db.refresh(new_item) return new_item How do i change the current list to this: "imgs_url": [ "http://10.0.2.2:8000/static/product_images/f3e6421737643e583a1d.jpg", "http://10.0.2.2:8000/static/product_images/b53bf8aeb27d27a739cc.jpg", "http://10.0.2.2:8000/static/product_images/75a80e7c04ebaed3e425.jpg" ], also this is another option for listing images: "imgs_url" : [ {"url":"https://s3-us-west-2.amazonaws.com/appsdeveloperblog.com/images/cats/cat-1.jpg"}, {"url":"https://s3-us-west-2.amazonaws.com/appsdeveloperblog.com/images/cats/cat-2.jpg"}, {"url":"https://s3-us-west-2.amazonaws.com/appsdeveloperblog.com/images/cats/cat-3.jpg"}, {"url":"https://s3-us-west-2.amazonaws.com/appsdeveloperblog.com/images/cats/cat-4.jpg"}, {"url":"https://s3-us-west-2.amazonaws.com/appsdeveloperblog.com/images/cats/cat-5.jpg"}, {"url":"https://s3-us-west-2.amazonaws.com/appsdeveloperblog.com/images/cats/cat-6.jpg"} ] I have three questions: 1) Please, how do i … -
Django - How Do I Show All Filtered Products With Same Attributes In Template But Only One Common Attribute Needs To Be Shown For Filtering?
How do I combine filtered results with the same value/name into one and display all objects that carry these specific values/names? In my store/views.py I got this: def filter_data(request): """ Using ajax to return products that are being filtered by category. :param request: :return: """ category_ids = request.GET.getlist('category-id[]') product_prices = request.GET.getlist('price[]') variations = request.GET.getlist('variation[]') if request.session['prod_asc'] == 'ascending': products = Product.objects.all().filter(is_available=True).order_by( 'created_date').distinct() else: products = Product.objects.all().filter(is_available=True).order_by( '-created_date').distinct() # Filter products by category if len(category_ids) > 0: products = products.filter(category__id__in=category_ids).distinct() # Filter products by prices if len(product_prices) > 0: products = products.filter(price__in=product_prices).distinct() # Filter products by variations if len(variations) > 0: products = products.filter(variation__id__in=variations).distinct() t = render_to_string('product-list.html', {'data': products[ :AMOUNT_PRODS_SHOW]}) # Default amount of products show for # filtering products based on category is 99 products return JsonResponse({'data': t}) In my js file I got this: $(document).ready(function(){ $(".ajaxLoader").hide(); $(".filter-checkbox").on('click', function(){ var _filterObj={}; $(".filter-checkbox").each(function(index,ele){ var _filterVal=$(this).val(); var _filterKey=$(this).data('filter'); _filterObj[_filterKey]=Array.from(document.querySelectorAll('input[data-filter='+_filterKey+']:checked')).map(function(el){ return el.value; }); }); // Run Ajax $.ajax({ url:'/store/filter_data', data:_filterObj, dataType:'json', beforeSend:function(){ $(".ajaxLoader").show(); }, success:function(res){ $("#filteredProducts").html(res.data); $(".ajaxLoader").hide(); } }); }); }); In my regular store.html template I got this: <div class="single-widget pb-50 mb-50"> <h4 class="widget-title">Filter By Variation</h4> <div class="widget-category-list scroll-box-default"> {% for variation in variations|dictsort:"variation_category" %} <div class="single-widget-category"> <input type="checkbox" data-filter="variation" value="{{ variation.id … -
How to render a form on a Django HTML template using a Viewset's filter_fields in django rest framwork?
I have a Viewset with a custom filterset_class: class CommunityViewset(LoginRequiredMixin, viewsets.ModelViewSet): queryset = ... serializer_class = CommunitySerializer filterset_class = CommunityFilter template_name = ... filter_fields = ('groups', 'person__first_name', ...) def list(self, request, *args, **kwargs): # getting serializer output response = super(CommunityViewset, self).list(request, *args, **kwargs) # default format is html, returning serializer data if json is requested if request.accepted_renderer.format == 'json': return response # if HTML return Response({'data': response.data, 'filter': get_filter_context(self) #!!!! GOING TO REFERENCE THIS BELOW }) I want to display a form on the HTML template to make a filtered GET request (e.g. localhost/community?groups=group1) I have a custom function called get_filter_context() that get the filterest class's fields and renders it in html: def get_filter_context(viewset): ''' create filters dictionary for list views @param {obj} viewset: rest_framework.viewsets.ModelViewSet subclass instance @returns {dic} filters: filters template dictionary ''' f = viewset.filterset_class(viewset.request.GET, viewset.queryset) dic = {'form': f.form} #!!!!! REFERENCING THIS BELOW return dic f.form returns a full django form which isn't serializable. Is there a to render the form without passing it to context? -
How to fix heroku error "python: can't open file 'manage.py': [Errno 2] No such file or directory"?
I've already done to initial steps of connecting my django app to Heroku, but whenever I run the command heroku run python manage.py makemigrations I get the error "python: can't open file 'manage.py': [Errno 2] No such file or directory". I know I am in the directory where manage.py is, but I still get this error. Any idea on how to solve this? wsgi file: web: python manage.py runserver 0.0.0.0:$PORT --noreload -
CommandError: You appear not to have the 'mysql' program installed or on your path
Windows 10, pycharm, django, python 3.x - I get this error when I run python manage.py dbshell -
class SimpleLazyObject(LazyObject): TypeError: Error when calling the metaclass bases 'property' object is not callable
I tried to connect my Django project to my server's domain using this tutorial - https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-centos-7 But after I start the apache server, and trying to access the server's domain, I get "Internal Server Error". I checked the log file but I have no idea where this error comes from - class SimpleLazyObject(LazyObject): TypeError: Error when calling the metaclass bases 'property' object is not callable I would appreciate your help. -
Django: multiple forms how to save this not hidden
I am struggling with validating a form based on damage_type choice field. I show only one DamageTypeForm in the template (other two are hide by js .hide() function). Each DamageTypeForm has got some required=True fields, therefore I cannot save the selected form this way: def createDamage(request): damage_specify_form = DamageSpecify(request.POST or None) damage_type_form1 = DamageTypeForm1(request.POST or None) damage_type_form2 = DamageTypeForm2(request.POST or None) damage_type_form3 = DamageTypeForm3(request.POST or None) if request.method == 'POST': damage_type = request.POST.get('damage_type ') if damage_type == 'DamageType1': if damage_type_form1.is_valid(): damage_type_form1.save() return reverse('damage:type1') elif damage_type == 'DamageType2': if damage_type_form2.is_valid(): damage_type_form2.save() return reverse('damage:type2') elif damage_type == 'DamageType3': if damage_type_form3.is_valid(): damage_type_form3.save() return reverse('damage:type3') else: damage_type_form1 = DamageTypeForm1() damage_type_form2 = DamageTypeForm2() damage_type_form3 = DamageTypeForm3() context = { 'damage_specify_form': damage_specify_form, 'damage_type_form1': damage_type_form1, 'damage_type_form2': damage_type_form2, 'damage_type_form3': damage_type_form3, } return render(request, 'create_damage.html', context) How can I get damage_type in View before submitting the form in the template, to save only desired form?? -
Celery chord callback isn't always launched
I'm trying to use a chord to launch a report update after the update is completed. @shared_task(autoretry_for=(Exception,), retry_backoff=True, retry_kwargs {'max_retries': 5}) def upload(df: pd.DataFrame, **kwargs): ed = EntityDataPoint(df, **kwargs) uploadtasks, source, subtype = ed.upload_database() chord(uploadtasks)(final_report.si(logger=ed.logger, source=source, subtype=subtype, index=ed.index)) With uploadtask being : g = group(unwrap_upload_bulk.s(obj = self, data = self.data.iloc[i:i+chunk_size]) for i in range(0, len(self.data), chunk_size)) When the header of the chord has more than 2 elements, the first two subtasks succeed, and the rest of the tasks in the group and the callback are not launched, without any error being sent anywhere, and without any information in the celery workers logs. After inspecting the workers, with celery inspect active, scheduled, there doesn't seem to be any waiting task in the queue. If the header (the group) has 2 or less elements, there is no problem, the group tasks finishes, the callback is called. It does not seem depend on the size of the elements (if each subtask in the group is sending 100 rows, we still have the same behavior for 1000 rows). If I just launch the group tasks, without the chord and the callback, the tasks succeed without any error. I tried using different syntaxes for the … -
Can we add a method like create_user_with_permission just like create_user in django?
I'm making a django website and I had made groups for the admin page access(Admin, Content Writer, Users). What I want is when a user signs up they should be assigned the specific group based on from which form they are signing in/up. Here is my models.py file for accounts app models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager # Custom User Manager class CustomUserManager(BaseUserManager): def _create_user(self, email, password, first_name, last_name=None, **extra_fields): if (not email): raise ValueError("Email Must Be Provided") if (not password): raise ValueError("Password is not Provided") user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, first_name, last_name=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_active', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, first_name, last_name, **extra_fields) def create_superuser(self, email, password, first_name, last_name=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, first_name, last_name, **extra_fields) # Custom user Model class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True, max_length=254) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255, null=True, blank=True) mobile = models.CharField(max_length=50, null=True, blank=True) address = models.CharField(max_length=250, null=True, blank=True) # profile_pic = models.ImageField(null=True, blank=True) is_staff = models.BooleanField(default=True) is_active … -
Upload image to S3 bucket with django-ckeditor
I have got an Article model with "content" textarea I decided to replace this textarea(i needed an option to insert images inside form) with CK-Editor so I used django-ckeditor package So now I got an issue - when I upload the image with CKEditorUploadingWidget() form, it saves data to local storage, however, S3 storage has been configured, so I have no clue why it doesn't work Here my code: Form: <form method="POST"> {{ form.media }} {{ form|crispy }} {% csrf_token %} <button type="submit" class="btn btn-primary my-3">Add</button> </form> Settings related to this topic: CKEDITOR_CONFIGS = { "default": { 'toolbar': 'full', 'width': 'auto' } } CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_RESTRICT_BY_USER = True CKEDITOR_ALLOW_NONIMAGE_FILES = False AWS_QUERYSTRING_AUTH = False S3_ACCESS_KEY_ID = 'secret' S3_SECRET_ACCESS_KEY = 'secret' S3_FILE_UPLOAD_BUCKET_NAME = 'bucket-name' S3_FILE_UPLOAD_BUCKET_URL = 'some url' -
Python3 Magic for a Django project
I need the python-magic package for a Django project. However, I found out that since I am using python3, I need the python3-magic package, which I can either get using pip3 or using apt-get. I am a macOS user, so I don't have an apt-get, and I cannot install the package using pip3. It gives me the following error when I type: pip3 install python3-magic. ERROR: Could not find a version that satisfies the requirement python3-magic (from versions: none) ERROR: No matching distribution found for python3-magic Is there any way I can get this package for my Django project? No matter what I do, the package appears uninstalled on my VS Code. Any helpful information will be greatly appreciated. -
Way to display user adjustable shapes on webpage in Django
I'm new to Python, and am currently working on web development in Django. I need to have an interface on this website that allows a user to dynamically adjust a rectangular shape that displays this adjustment to them on the website in real time. Does anyone know how I can integrate this using Django or Bootstrap. Pretty much I need a way to display to the user a rectangle that they can drag and drop the lengths of on the screen as they desire. Very similar to the MS Word shape drawing tools where the user can pick the edge of and expand or collapse. -
Django Model unsupported type for timedelta days component: datetime.timedelta
I am facing an error within my Django project, this is a model method that should allow me to increase costs based on inflationary rates stored in my database (this code was largely provided by a reddit user) def calculateCurrentCost(self): """Calculates the cost of a project in current value""" base_cost = self.total_cost today = date.today() time_difference = timedelta(today - self.date_added_to_database).days # get the timediff in days from the timediff object days_since_costing = time_difference inflation = days_since_costing * 0.01 cost_with_inflation = Decimal(base_cost) * Decimal((1 + inflation)) location_adjustment = self.location_premium[self.location] region_adjusted_cost = cost_with_inflation * location_adjustment return region_adjusted_cost however I am running into an issue with the timedelta portion and I am unsure as to what is causing this issue? unsupported type for timedelta days component: datetime.timedelta -
django postgres database in Amazon s3 service
In our company we have 5 services that stores our backend django codes and one front end service that holds react codes and these services communicate with each other in microservice api . we use docker to run projects on each service and in each build two containers are made which one is for the postgresql database and the other is to run the service , this is docker compose file : services: test: build: context: . dockerfile: Dockerfile env_file: - ./envs/development.env volumes: - ./:/app - /store/account/media:/app/media - /store/account/static:/app/static ports: - 8000:8000 command: gunicorn account.wsgi:application --reload --bind 0.0.0.0:8000 account-database: image: postgres:alpine env_file: - ./envs/development.db.env volumes: account-static: account-media: networks: default: name: test the problem is if the docker container is deleted we lost all our data so recently we have decided to move the database to a separated service and we have Amazon s3 in our mind accorrding this tutorial i know how to connect a django project to a live database on s3 but my question is : is it a standard way of doing it or there is a better solution to separated our databases from our source code? can i do still perform delete and update on database …