Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF: how do I call a class inside another class method?
I have two separate methods: to load and validate a csv file FileUploadView(APIView) [PUT] to add new objects to the database based on their uploaded file data CsvToDatabase [POST] file upload class FileUploadView(APIView): parser_classes = (MultiPartParser, FormParser) permission_classes = (permissions.AllowAny,) def put(self, request, format=None): if 'file' not in request.data: raise ParseError("Empty content") f = request.data['file'] filename = f.name if filename.endswith('.csv'): file = default_storage.save(filename, f) r = csv_file_parser(file) status = 204 else: status = 406 r = "File format error" return Response(r, status=status) create instances class CsvToDatabase(APIView): def post(self, request, format=None): r_data = request.data ... #some logic ... serializer = VendorsCsvSerializer(data=data) try: serializer.is_valid(raise_exception=True) serializer.save() except ValidationError: return Response({"errors": (serializer.errors,)}, status=status.HTTP_400_BAD_REQUEST) else: return Response(request.data, status=status.HTTP_200_OK) urls.py urlpatterns = [ path('csv_upload/', FileUploadView.as_view(), name='csv_upload'), path('from_csv_create/', CsvToDatabase.as_view(), name='csv_vendor_create'),] At the moment I am simply passing manually to Postman the result of the PUT method of FileUploadView class (Response(r, status=status) get me json ) to POST method of CsvToDatabase class. Of course, this option is not suitable for a working application. I would like to know if there is a way to call the POST method automatically inside FileUploadView class after the .csv file is processed and json is received. I know I can transfer a … -
How to make an image responsive after setting its height and width in bootstrap
So I'm building this portfolio, and I found out ways to make the text and other stuff responsive, but I'm unable to make the picture responsive, I have set its height to 325, but when I shrink the page, the image isn't responsive. How should I make it responsive. The original image dimensions are around 1000 x 900, I tried shrinking the image size and using img-fluid but that didn't work as well. When I shrink the page When the page is in full view <img src="{% static 'shetha.jpg' %}" height="325 "/> -
Find nested JS object value from specific script tag with Beautiful Soup
I am scraping a site with beautiful soup to grab image/s, this has worked fine for every site so far and I have even managed to create some custom case-types. But one particular site is causing me issues as iit returns all the images in a JavaScript object wrapped inline in a script tag. The object is quite large as it holds all the product info, the specific bit I am looking for is nested pretty deep in productArticleDetails > [the product id] > normalImages > thumbnail > [the image path]. Like so: <script> var productArticleDetails = { ... '0399310001': { ... 'normalImages': [ { 'thumbnail': '//image-path.jpg', ... } ] } } So I am looking to just extract the image path. It is also not the only thing wrapped in a script tag in the returned 'soup', there are loads of other javascript tags in the code. So far I have saved the HTML to a variable and then run: soup = BeautifulSoup(html) scripts = soup.find_all('script') So I am left with an object that contains all the <script> elements from html Somehow within that scripts object I need to find that specific node in the correct chunk of JS … -
Django - Form returning invalid due to empty form field
In my project, I have a Django form which consists of an ImageField and a CharField. I pass this form to my template, and display it. On the form, I set the method attribute to POST. In my view I handle this request, and return a redirect in return. However form.is_valid() is returning False in my view, and I print the forms errors in the console. Here is the error returned from form.errors: <ul class="errorlist"><li>image<ul class="errorlist"><li>This field is required.</li></ul></li></ul> It is saying my ImageField input field is empty, however I definitely select a file for the ImageField in the browser, therefore I don't know the reason why it's saying that the input field is blank. My code is below. forms.py: class CreatePost(forms.Form): // The field that is not being assigned a file image = forms.ImageField(allow_empty_file=False, required=True, widget=forms.FileInput(attrs={'id': 'image'})) description = forms.CharField(max_length=100, required=False, widget=forms.TextInput(attrs={'placeholder': 'Add a caption:', 'id': 'description'})) views.py: def create(request): context = {} if request.method == "POST": form = CreatePost(request.POST) if form.is_valid(): print("YES") return redirect('home') else: print(form.errors) context['error'] = 'Please enter valid form data' else: form = CreatePost() context['form'] = form return render(request, 'create.html', context) Template: <form action="{% url 'create' %}" method="POST"> {% csrf_token %} {% for field in … -
How to set Current_company_flag using Django
I am creating a model for storing Experience... Here is my model class Experience(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255, blank=True) company = models.CharField(max_length=255, blank=True) current_company = models.BooleanField(default=False) start_date = models.DateField(default=datetime.now) end_date = models.DateField(default=datetime.now) In this current_company is used to showing it is the current company .... This is my form for getting the data from user class ExperienceForm(forms.ModelForm): class Meta: model = Experience exclude = ['user'] This is my view class ExperienceFormView(TemplateView, LoginRequiredMixin): template_name = 'accounts/profile/expereince_form.html' form_class = ExperienceForm def post(self, request, *args, **kwargs): context = self.get_context_data() if context['form'].is_valid(): data = context['form'].save(commit=False) data.user = request.user data.save() return JsonResponse({'status': 'success', 'message': 'Created Successfully'}, status=201, safe=False) return super(ExperienceFormView, self).render_to_response(context) def get_context_data(self, **kwargs): context = super(ExperienceFormView, self).get_context_data(**kwargs) form = ExperienceForm( self.request.POST or None) # instance= None context["form"] = form return context What is the best way to implment the following use cases 1) If I enable my current_company as True then the previous object having current_company becomes False 2)If there is no previous object then ignore the first use case..... -
Django admin how do you add a queryset as a read only linked property field
This is what my admin class looks like: @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): readonly_fields = ('associated_risks',) associated_risks is a queryset property that I have set in the model like so: @property def associated_risks(self): return Risk.objects.filter(control__project__associated_controls__in=self.associated_controls.all()) The isssue is that the admin page it's a read only field shown like this: Would it be possible to set it as an m2m field similar to how other m2m fields in the django admin page are set up? (multi select form) -
Error 10061 connecting to localhost:6397. No connection could be made because the target machine actively refused it
I'm trying to learn Redis with Django framework. My program is intended to count image views but when I click on the image details it gives me above mentioned error. I am unable to make connection with redis. Here's the link to my detail error http://dpaste.com/1TAJ4MF I have installed and run redis cli on WINDOWS 10 and here is a snip of my settings.py code # Configuring Redis database REDIS_HOST = 'localhost' REDIS_PORT = 6397 REDIS_DB = 0 views.py import redis from django.conf import settings def detail(request, id): profile = get_object_or_404(Profile, id=id) # increment total image views by 1 total_views = r.incr('profile:{}:views'.format(profile.id)) return render(request, 'images/detail.html', {'profile': profile, 'total_views': total_views}) detail.html <body> <img src="{{ profile.photo.url }}" width="500" height="500" alt="Image not found"> <br> {{ profile.user.username.title }}. {{ profile.dob }} <br> {{ total_views }} view{{ total_views|pluralize }} </body> -
My Django web app isn't functioning properly
I'm fairly new at Django and I've been making a login and registration form using bootstrap and then connecting the bootstrap template with Django. The form has a sign in and sign-up page which has a smooth transition when you click on each of them. But when I click on the sign-up, nothings happening.I've set up the static files and the website is displaying correctly although not functioning correctly. Can someone help me resolve this problem? I've provided the CSS file here https://easyupload.io/gq48hs. The login and registration page looks like this https://ibb.co/jr4pm3N Bootstrap {% load static %} <!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> <title>Online Timetable - Student Login and registration form</title> <link rel='stylesheet' href='https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css'><link rel="stylesheet" href="{%static 'css/style.css' %}"/> </head> <body> <!-- partial:index.partial.html --> Login & registration Form --> SIGN IN SIGN UP USERNAME PASSWORD Keep me signed in Forgot password? USERNAME E-MAIL PASSWORD CONFIRM PASSWORD I agree </body> <!-- partial --> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script> <script src="{% static 'css/script.js' %}"></script> </body> </html> $('.btn-enregistrer').click(function() { $('.connexion').addClass('remove-section'); $('.enregistrer').removeClass('active-section'); $('.btn-enregistrer').removeClass('active'); $('.btn-connexion').addClass('active'); }); $('.btn-connexion').click(function() { $('.connexion').removeClass('remove-section'); $('.enregistrer').addClass('active-section'); $('.btn-enregistrer').addClass('active'); $('.btn-connexion').removeClass('active'); }); URLS.Py from django.urls import path from .import views urlpatterns = [ path('',views.login), ] Views.py from django.shortcuts import render from django.http import HttpResponse … -
Validar campo antes de salvar model django
Estou criando uma aplicação que recebe o cpf do usuário. Quero validar o CPF antes de salvar. Já tenho a função que faz a validação, mas como chamo antes de salvar? cpf = models.IntegerField(max_length=11, null=False, unique=True) O serializer: class SellerSerializer(serializers.ModelSerializer): class Meta: model = Seller fields = '__all__' O viewset: class SellerViewSet(ModelViewSet): queryset = Seller.objects.all() serializer_class = SellerSerializer -
Heroku Deployment - ModuleNotFoundError: No module named 'eventshow.local_settings' Error while running '$ python manage.py collectstatic --noinput'
I am running into the following issue when trying to deploy my Django-Postgres app on Heroku: >❯git push heroku master Enumerating objects: 246, done. Counting objects: 100% (246/246), done. Delta compression using up to 4 threads Compressing objects: 100% (108/108), done. Writing objects: 100% (246/246), 4.87 MiB | 1.62 MiB/s, done. Total 246 (delta 114), reused 239 (delta 112) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.10 remote: -----> Installing pip remote: -----> Installing SQLite3 remote: Sqlite3 successfully installed. remote: -----> Installing requirements with pip remote: Collecting asgiref==3.2.3 remote: Downloading asgiref-3.2.3-py2.py3-none-any.whl (18 kB) remote: Collecting astroid==2.3.3 remote: Downloading astroid-2.3.3-py3-none-any.whl (205 kB) remote: Collecting autopep8==1.5 remote: Downloading autopep8-1.5.tar.gz (116 kB) remote: Collecting dj-database-url==0.5.0 remote: Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) remote: Collecting Django==3.0.4 remote: Downloading Django-3.0.4-py3-none-any.whl (7.5 MB) remote: Collecting django-extensions==2.2.8 remote: Downloading django_extensions-2.2.8-py2.py3-none-any.whl (224 kB) remote: Collecting django-heroku==0.3.1 remote: Downloading django_heroku-0.3.1-py2.py3-none-any.whl (6.2 kB) remote: Collecting djangorestframework==3.11.0 remote: Downloading djangorestframework-3.11.0-py3-none-any.whl (911 kB) remote: Collecting Faker==4.0.1 remote: Downloading Faker-4.0.1-py3-none-any.whl (994 kB) remote: Collecting gunicorn==20.0.4 remote: Downloading gunicorn-20.0.4-py2.py3-none-any.whl (77 kB) remote: Collecting isort==4.3.21 remote: Downloading isort-4.3.21-py2.py3-none-any.whl (42 kB) remote: Collecting lazy-object-proxy==1.4.3 remote: Downloading lazy_object_proxy-1.4.3-cp36-cp36m-manylinux1_x86_64.whl (55 kB) remote: Collecting mccabe==0.6.1 remote: Downloading mccabe-0.6.1-py2.py3-none-any.whl (8.6 kB) remote: … -
how to get individual user API by using django rest framework knox
Before I implement token authentication, it worked fine to grab each user, GET: http://localhost:8000/users/2/ { "url": "http://localhost:8000/users/2/", "id": 2, "username": "foo", "boards": [ "http://localhost:8000/boards/15/" ] }, After I implement knox token authentication, #settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), } #users/views.py class UserDetail(generics.RetrieveAPIView): permission_classes = [permissions.IsAuthenticated] queryset = User.objects.all() serializer_class = UserSerializer def get_object(self): return self.request.use #users/urls.py app_name = 'users' urlpatterns = [ path('', UserList.as_view(), name='user-list'), path('<int:pk>/', UserDetail.as_view(), name='user-detail'), path('register/', RegistrationAPI.as_view(), name='user-register'), path('login/', LoginAPI.as_view(), name='user-login'), path('logout/', knox_views.LogoutView.as_view(), name='user-logout'), # path('', api_root) ] urlpatterns = format_suffix_patterns(urlpatterns) # users/serializer.py class UserSerializer(serializers.HyperlinkedModelSerializer): boards = serializers.HyperlinkedRelatedField( view_name='board:board-detail', lookup_field='pk', many=True, queryset=Board.objects.all() ) url = serializers.HyperlinkedIdentityField( read_only=True, lookup_field='pk', view_name="users:user-detail") class Meta: model = User fields = ('url', 'id', 'username', 'boards') class CreateSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( read_only=True, lookup_field='pk', view_name="users:user-detail") def create(self, validated_data): user = User.objects.create_user( validated_data['username'], None, validated_data['password'] ) return user class Meta: model = User fields = ('url', 'id', 'username', 'password') class LoginUserSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("unable to log in with provided credential") Now I am getting 401 error, GET: http://localhost:8000/users/2/ { "detail": "Authentication credentials were not provided." } Even, POST:http://localhost:8000/logout/ has the same 401 Unauthorized error. I tried login first … -
django polymorphic dumpdata command fails - django.db.utils.IntegrityError: Problem installing fixtures
I'm using package django-polymorphic==2.1.2 Django==2.2 When trying to dumpdata for testing it fails with this message: Error Traceback (most recent call last): File "/home/federico/Repositories/APC/venv/lib/python3.6/site-packages/django/test/testcases.py", line 1131, in setUpClass call_command('loaddata', *cls.fixtures, **{'verbosity': 0, 'database': db_name}) File "/home/federico/Repositories/APC/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 148, in call_command return command.execute(*args, **defaults) File "/home/federico/Repositories/APC/venv/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/federico/Repositories/APC/venv/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "/home/federico/Repositories/APC/venv/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 122, in loaddata connection.check_constraints(table_names=table_names) File "/home/federico/Repositories/APC/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 318, in check_constraints bad_value, referenced_table_name, referenced_column_name django.db.utils.IntegrityError: Problem installing fixtures: The row in table 'core_faultagv' with primary key '1' has an invalid foreign key: core_faultagv.fault_ptr_id contains a value '1' that does not have a corresponding value in core_fault.id. I tried using "--natural-foreign" and "--natural-primary" as arguments for manage.py dumpdata but it still fails. These are my models: class Fault(PolymorphicModel): active = models.BooleanField(default=False) equipment = models.CharField(choices=EquipmentChoices.choices(), max_length=10) fault_text = models.CharField(max_length=255) start_time = models.DateTimeField(auto_now=True) def get_vehicle_id(self): return None class FaultAGV(Fault): error_code = models.IntegerField() vehicle_id = models.IntegerField() def get_vehicle_id(self): return self.vehicle_id class FaultPLC(Fault): bit = models.IntegerField() index = models.IntegerField() Any suggestion? -
import error in python in django framework
from django.contrib import admin from django.urls import url from . import views urlpatterns = [ # path('admin/', admin.site.urls), url(r'^admin/',admin.site.urls), url(r'^about/$',views.about), url(r'^$',views.homepage), ] this is python code in django framework . i have successfully installed django but i dont know why this is showing an error . actually i was just started with django so have a look in the fault . may be this is because of that it cant reach to urls and contrib directory . please help Thanks in advance . C:\Users\My Loptop\Desktop\django\djangonautic> C:\Users\My Loptop\Desktop\django\djangonautic>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", … -
Filter inline objects based on model foreign key object variable
I am building a relatively simple pizza shop. There is a Pizza model with category choices field. There's also an OrderItem model that refers to Pizza: class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, verbose_name=_('OrderItem|Order', 'Order')) pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE, verbose_name=_('OrderItem|Item', 'Item')) quantity = models.PositiveSmallIntegerField(validators=[MinValueValidator(1)], verbose_name=_('OrderItem|Quantity', 'Quantity')) @property def price(self): return self.pizza.price * self.quantity def __str__(self): return f"{self.pizza.id}" In admin.py there's an inline that uses this model when showing an order: class OrderItemInline(admin.TabularInline): model = OrderItem fields = ('pizza', 'quantity', 'price_admin',) readonly_fields = ('price_admin',) extra = 0 How do I make it filter order items based on pizza category? For example to only be able to select pizzas from one specific category. -
django appending class object on refresh
I have made some class on django views.py. I am having issues with them. The previously loaded data is getting appended on refresh. Instead of deleting the previous objects of the class object it is appending it with new objects. class topic_sub_topic: def __init__(self,request,topic): self.topic = topic sub_topics = topics_to_subtopics.objects.filter(topic = topic) x = [] for sub_topic in sub_topics: x += [sub_topic.subtopic] self.sub_topics = x class course_detail: content = [] def __init__(self,request,course): course = courses.objects.get(slug = course) self.course = course topics = course_to_topics.objects.filter(course = course) if not topics: return for topic in topics: self.content += [topic_sub_topic(request,topic.topic)] def view_course_deatail(request,course): obj = course_detail(request,course) return render(request,'create/coursedetail.html',{'obj':obj}) Whenever I refresh the template django simply appends the older generated class object with new one. -
Contact Form with Django 3, G Suite - email sending error
Goal Deploying a landing page on Digital Ocean built with Django 3. Adding my G suite account to the contact form so people can type in their email, subject, message and send it to me. What I have done I have built my contact from with the following guide. I have tested it and it prints out all the parameters in the terminal as it should Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: helllo From: customeremail@gmail.com To: admin@example.com Date: Tue, 17 Mar 2020 14:29:40 -0000 Message-ID: <12121212121212.1222212121212.1212121212121212@mymachinename.local> This is the message. I have purchased a G Suite subscription that contains G Suite SMTP relay service that can send 10'000 email/day. ERROR I have run it and received the following e-mail: Critical security alert Google <no-reply@accounts.google.com> to me Sign-in attempt was blocked myname@businessemaildomainname.com Someone just used your password to try to sign in to your account from a non-Google app. Google blocked them, but you should check what happened. Review your account activity to make sure no one else has access. Check activity I have looked up a couple of posts but none of them answered my question like G Suite and Django for SMTP Why can not get email … -
Unable to POST data to django function using ajax
I am trying to add data and view data to/from django database through AJAX calls, fetching data works fine but adding data doesnt work. I getting following error: Method Not Allowed (POST): /mymodels/ Method Not Allowed: /mymodels/ [17/Mar/2020 22:27:24] "POST /mymodels/ HTTP/1.1" 405 0 and in browser console: 0: undefined My ajax function: $(document).on('submit', '#myform', function(e){ $.ajax({ type: 'POST', url: `/mymodels/create`, data:{ first_name:$('#first_name').val(), last_name:$('#last_name').val(), age:$('#age').val() }, success:function(json){ console.log("Data submitted"); }, error:function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); } }) }) urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('mymodels/', TemplateView.as_view(template_name='crud_app/main.html'),name='mymodel_main'), path('mymodels/list', views.MyModelList.as_view(), name='mymodel_list'), path('mymodels/create', views.MyModelCreate.as_view(), name='mymodel_create'), path('mymodels/update/<int:pk>', views.MyModelUpdate.as_view(), name='mymodel_update'), path('mymodels/delete/<int:pk>', views.MyModelDelete.as_view(), name='mymodel_delete'), path('mymodels/<int:pk>', views.MyModelDetail.as_view(), name='mymodel_detail'), ] view: class MyModelCreate(CreateView): def post(self,request): data = dict() form = MyModelForm(request.POST) if form.is_valid(): my_model = form.save() data['my_model'] = model_to_dict(my_model) else: data['error'] = 'Form invlaid' return JsonResponse(data) and finally my html form: <form class="form-group" id="myform" method="POST"> {% csrf_token %} <label for="first_name">First Name</label> <input type="text" class="form-control" name="" id="first_name" placeholder=""> <label for="last_name">Last Name</label> <input type="text" class="form-control" name="" id="age_name" placeholder=""> <label for="age">age</label> <input type="text" class="form-control" name="" id="age" placeholder=""> <input type="submit" class="btnSubmit btn btn-primary" value="Submit"> </form> {% endblock %} {% block extrajs %} <script src="{% static 'js/app.js' %}"></script> {% endblock %} -
docker-compose django app cannot find postgresql db
I'm trying to create a Django app in a docker container. The app would use a postgres db with postgis extension, which I have in another database. I'm trying to solve this using docker-compose but can not get it working. I can get the app working without the container with the database containerized just fine. I can also get the app working in a container using a sqlite db (so a file included without external container dependencies). Whatever I do, it can't find the database. My docker-compose file: version: '3.7' services: postgis: image: kartoza/postgis:12.1 volumes: - postgres_data:/var/lib/postgresql/data/ ports: - "${POSTGRES_PORT}:5432" environment: - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_DB=${POSTGRES_DB} env_file: - .env web: build: . # command: sh -c "/wait && python manage.py migrate --no-input && python /code/app/manage.py runserver 0.0.0.0:${APP_PORT}" command: sh -c "python manage.py migrate --no-input && python /code/app/manage.py runserver 0.0.0.0:${APP_PORT}" # restart: on-failure ports: - "${APP_PORT}:8000" volumes: - .:/code depends_on: - postgis env_file: - .env environment: WAIT_HOSTS: 0.0.0.0:${POSTGRES_PORT} volumes: postgres_data: name: ${POSTGRES_VOLUME} My Dockerfile (of the app): # Pull base image FROM python:3.7 LABEL maintainer="yb.leeuwen@portofrotterdam.com" # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies # RUN pip install pipenv RUN pip install pipenv RUN mkdir /code/ … -
Is there any way to connect Athena database to django
I am working to build dashboard on tables of athena. I have tried django-pyodbc in database settings but it is not working. -
Django data not showing on production because of perforamance
I faced a problem with django, I guess this problem is related to latency. I have a views and templates. Everything is working great in my development server. but in production, some data now showing. At first see this views: def servery_company(request,pk): instance = get_object_or_404(Company.objects.filter(pk=pk,is_deleted=False)) company_details = ConDetails.objects.filter(company_details=instance) c = copy.copy(company_details[0]) total_consumption = int(c.jan_amount) + int( c.feb_amount) total_consumption_mean = copy.copy(total_consumption / 12) enery_fare_item_total = FareItem.objects.aggregate(Sum("price"))['price__sum'] enery_fare_item_mean_month = FareItem.objects.aggregate(Avg("price"))['price__avg'] result = (total_consumption_mean * float(enery_fare_item_mean_month) context = { "title": "Company Details:", "instance": instance, "company_details": company_details, "today": datetime.date.today(), "total_consumption": total_consumption, "total_consumption_mean": total_consumption_mean, 'enery_fare_item_total': enery_fare_item_total, "enery_fare_item_mean_tweleve_month": enery_fare_item_mean_tweleve_month, "result": result, } return rende(request 'company.html',context) If you closely look at the views, there is a variable name result you see, all the data is showing both the local server and production server. Only problem is,Only the result variable data not showing in production but it works in local server very well. I am using apache2 server. I am not sure why it is occurring. Can anyone suggest me how to fix this problem? what is the coz of this issue? Your help is much appreciated Thanks -
Unbound Error when having two Django forms in a single HTML page
I have created a simple ToDo List app using Django. Recently I have worked on adding Due Dates to each task/todo. It works fine too. But to add a due date to any task, users will have to go to another URL and then add the date. What I want to do is have a due date Django form right in the Home page below every single task. When I try to accomplish this, I was successfully able to show the due form below each task, but when I input a day and press enter, Django throws an Unbound Local Error. The two forms I am having on my single Home page are the todo_form which is a single input field that is used to create new todos on the Home page and this due_form that will handle Due Dates. This is my views.py home function def home(request): if request.method == "POST": if "due_form" in request.POST: due_form = DueDateForm(request.POST) if due_form.is_valid(): days = due_form.cleaned_data.get("due_date") if days == "today": days = 0 elif days == "tomorrow": days = 1 elif days == "next week": days = 7 elif days == "yesterday": days = -1 elif days == "last week": days = … -
update table in django from json
I have created a webpage with a table (bootstrap) I am reading a json file and displaying it in the table as follows {% extends "blog/base.html"%} {% block content%} <h1>Table Page</h1> <table class="table table-borderless table-dark"> <thead> <tr> <th scope="col">#</th> <th scope="col">Email</th> <th scope="col">Count</th> </tr> </thead> <tbody> {% for post in posts %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{post.Email}}</td> <td>{{post.Count}}</td> </tr> {% endfor %} </tbody> </table> {% endblock content%} it works well, however the JSON file I am reading from keeps updating every 4-5 minutes and I need to constantly update the page, this is my views.py from django.shortcuts import render from django.http import HttpResponse import json with open('/home/usr134/tracker.json') as f: config=json.load(f) def table_test(request): context = {'posts':config} return render(request,'blog/my_table.html',context) I am new to django, I found plenty of ways to update but they use SQL, is there an easy way to do it ? -
Column values depends on another column
Hey i have a table where three columns... Item name, raw weight, product weight... Item weight is already defined so user get the drop down for it... And user have to input raw weight it's decimal... Now for a product weight... I have already data about it... Like for item A product weight = 0.5*raw weight... Like wise for B product weight = 0.7*rawweight... There are so many.... So my q is that how can i define backend side the logic of products weight column... Using offest etc.... Thanks.... -
What is more efficient for web development in Django : to perform calculations in python code or make valuation in MySql?
What is the most efficient way of organising and balancing code provided that the application: has large data as it is analytics web and it is all about calculations and analysis needs faster response smooth functioning of the web Would appreciate your insight and recommendation. -
Display the text in the same line in Django templates
I just started with Django. I rendering the text coming from the database. Even though it is in <li> tag the text is rendering in the new line. I also tried giving class col-md-2 but no use. Thanks in advance. <section class="resume-section p-3 p-lg-5 d-flex align-items-center" id="skills"> <div class="w-100"> <h2 class="mb-3">Skills</h2> {% for skill in skills.all %} <ul class="list-inline dev-icons"> <li class="list-inline-item"> <h5> &emsp;{{skill}} </h5> </li> </ul> {%endfor%} </div> views.py skills = Skills.objects return render(request,'home.html',{'jobs':jobs,'projects':projects, 'skills':skills})