Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Annotate Changes Query Values/Order
I am trying to pull the 8 most recent items from my model and attach their minimum price. When I annotate the 8 most recent items, the items change unless I use order_by(). Is this a bug, or does this make my query more efficient somehow? I'm trying to better understand my queries so that I can make them faster. class Item(ClusterableModel): name = models.CharField(max_length=100) class Meta: ordering = ('-pk',) class StoreInventory(ClusterableModel): item = ParentalKey('Item', on_delete=models.CASCADE) price = models.DecimalField(max_digits=4, decimal_places=2) Undesired newest_items = Item.objects.all()[:8] > Queryset [Item: Item object(100), ..., Item: Item object(93)] newest_items = newest_items.annotate(price = Min('storeinventory__price')) > Queryset [Item: Item object(1), ..., Item: Item object(8)] Desired newest_items = Item.objects.all().order_by('-pk')[:8] > Queryset [Item: Item object(100), ..., Item: Item object(93)] newest_items = newest_items.annotate(price = Min('storeinventory__price')) > Queryset [Item: Item object(100), ..., Item: Item object(93)] -
Create and get the id of a model's attribute in Django
Im working in a project where users can register their shops addresses in a Django model and i can display all those addresses in a google map. For that i need the addresses but also a way to access to that specific user's shop info, how can i create an id linked or pointing to the user's "address" attribute in my extended users models, and how do i call all those ids? models.py class UserProfile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE, related_name='user_profile') address = models.CharField(null=True, blank=True, max_length=150) views.py def test(request): addresses = list(UserProfile.objects.values_list('address')) address_id = ???????? context = { 'address_id': address_id, 'addresses': addresses } return render(request, "test.html", context) -
Create a preview screen in Django
I have a Django form that receives a text (that I copy from Google Classroom: a bunch of student comments). I use these comments to make student's attendance. What I want to achieve is: Accessing /insertion/ url via GET user receive the page form as a response, to choose the class (class01, class02, etc) and to past the text When the user clicks on submit in this form (post method), it is redirect to the same /insertion/ url, but now the form is bound to the data submited, and the page shows a preview page (based on a boolean variable I'm passing through context), showing what students are present and what are absent based on the text informed. At that page, a new submit button will be shown below a text like "if everything's ok, hit the ok button". After click this ok button, a pdf will be generated and the user will be redirected to /files/ url, to see the generated pdf and previous generated pdf. views.py def insertion(request): context = {} if request.method == 'GET': form = AttendanceDataForm() context.update({"form": form}) if request.method == 'POST': form = AttendanceDataForm(request.POST) context.update({"form": form}) if form.is_valid(): lesson = form.cleaned_data['lesson'] raw_text = form.cleaned_data['raw_text'] # … -
Trouble creating unit tests for Django admin action
I am having a bit of trouble figuring out where to mock and patch things and it's not making sense to me. I'm creating an admin action that fetches a token from a third-party API, and then instantiates an instance of a local class (that connects to said API) and makes API calls based on the item id. For example, let's assume that I'm storing restaurant ratings in an external location, accessible via API calls, and I'm storing users locally. I want to create an admin action that goes through each selected user and deletes all restaurant ratings in my external location, which is authenticated via a fetched token. I know this is not an optimal way to do things, but this is obviously not a real example, just an analogue of something a bit more complicated. Here is the structure of my project. from external_class_location import ReviewClass # This is the class that hooks into the restaurant review location from external_function_location import get_token # This is the method that fetches the token from that external location class UserAdmin(admin.ModelAdmin) actions = ['delete_reviews', ] def delete_reviews(self, request, queryset): reviews = ReviewClass(get_token()) for user in queryset: reviews.delete_all_reviews(user) delete_reviews.short_description = "Delete all reviews … -
How Do I Incorporate Ajax into a CreateView?
I have a CreateView...and it works fine in the traditional sense. I'm trying to convert it essentially to an AJAX for submit because the user can attach files to the form, and I'm trying to avoid a form submission failure based on the user's mistakes. Here is my CreateView... class CreateProcedureView(LoginRequiredMixin,CreateView): model = NewProcedure form_class = CreateProcedureForm template_name = 'create_procedure.html' def form_valid(self, form): instance = form.save() def post(self, request, *args, **kwargs): if "cancel" in request.POST: return HttpResponseRedirect(reverse('Procedures:procedure_main_menu')) else: self.object = None user = request.user form_class = self.get_form_class() form = self.get_form(form_class) file_form = NewProcedureFilesForm(request.POST, request.FILES) files = request.FILES.getlist('file[]') if form.is_valid() and file_form.is_valid(): procedure_instance = form.save(commit=False) procedure_instance.user = user procedure_instance.save() list=[] for f in files: procedure_file_instance = NewProcedureFiles(attachments=f, new_procedure=procedure_instance) procedure_file_instance.save() return self.form_valid(form) else: form_class = self.get_form_class() form = self.get_form(form_class) file_form = NewProcedureFilesForm(request.POST, request.FILES) return self.form_invalid(form) As stated it works just fine the way it is. What I'm trying to figure out is how can I best convert this to an AJAX type of approach? Here's what I have so far... Here's my AJAX... $(document).ready(function (){ $("#forms").on('submit', function(event) { event.preventDefault(); var newprocedure = '{{ newprocedure }}'; $.ajax({ type: "POST", url: "{% url 'Procedures:ajax_posting' %}", data:{ newprocedure:newprocedure, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, datatype:'json', success: function(data) { … -
Serving Django App with Apache 2 on Virtual Host
I am learning the Django framework and can run my first app on the development server using: python3 manage.py runserver However, what I really want to do is serve my app with Apache so it can be access from the web. My Apache Virtual Host is: <VirtualHost *:443> ServerName django.example.com DocumentRoot /var/www/django/hello_world/mysite WSGIScriptAlias / /var/www/django/hello_world/mysite/mysite/wsgi.py Include /etc/letsencrypt/options-ssl-apache.conf SSLEngine On SSLCertificateFile /etc/letsencrypt/live/django.example.com/cert.pem SSLCertificateKeyFile /etc/letsencrypt/live/django.example.com/privkey.pem SSLCertificateChainFile /etc/letsencrypt/live/django.example.com/chain.pem WSGIDaemonProcess django.sample.com processes=2 threads=15 display-name=%{GROUP} python-home=/var/www/django/hello_world/mysite/venv/lib/python3.6 WSGIProcessGroup django.sample.com <directory /var/www/django/hello_world/mysite> AllowOverride all Require all granted Options FollowSymlinks </directory> </VirtualHost> I'm getting: My settings.py file is: from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-3b^iz&pognt=yt5m&(!w@keo&*@a9zb&)$n@32v!yj4w%c!k-4' DEBUG = True ALLOWED_HOSTS = [ 'django.sample.com' ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' I'm running … -
What should be my main direction with django?
Heey django masters. I have some questions becouse I don't know which direction to go further. I mastered django on an average/medium level. I want ask you, what is the most important in django and what should I pay attention to. Maybe have you and good tips or tutorials for me? Last my question, when should i learn ajax? Javascript should be first? -
Dictionary not rendering in page
in my view im trying to pass in a dictionary like so rooms = [ {'id': 1, 'name': 'designign'}, {'id': 2, 'name': 'wow'}, {'id': 3, 'name': 'now'}, ] def home(request): context = {'rooms' : rooms} return render(request, 'home.html', context) Then in my home.html page i have this code {% extends 'main.html' %} {% block content %} <h1>Home Template</h1> <div> <div> {% for room in rooms %} <div> <h1>{{room.name}}</h1> </div> {% endfor %} </div> </div> {% endblock content %} but the items in the dictionary are not displaying. the url and path are fine because <h1>Home Template</h1> displays but nothing else displays main.html <body> {% include 'navbar.html' %} {% block content %} {% endblock %} </body> urlpattern if that matters urlpatterns = [ path('', views.home, name="home") ] -
Django/Scrapy/Apache - Error downloading <GET https://example.com>
I've created a web scrapper which runs from Django view and it works as expected when I run it locally but it gives an error when I run it from my (Apache)server. [scrapy.core.scraper] ERROR: Error downloading <GET https://example.com> FYI. I use valid URL addresses for sure and it works locally without any issues. Also, I've set "TELNETCONSOLE_PORT" :None, . Not sure if this is related to the issues but without this parameter it gave me another error. Unable to listen "127.0.0.1: 6023" -
CI/CD pipeline for Django failure
My gitlab ci pipeline keeps failing. It seems am stuck here. Am actually still new to the CI thing so I don't know what am doing wrong. Any help will be appreciated Below is .gitlab-ci.yml file image: python:latest services: - postgres:latest variables: POSTGRES_DB: projectdb # This folder is cached between builds # http://docs.gitlab.com/ee/ci/yaml/README.html#cache cache: paths: - ~/.cache/pip/ before_script: - python -V build: stage: build script: - pip install -r requirements.txt - python manage.py migrate only: - EC-30 In my settings.py file, I have the following settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'thorprojectdb', } } But when I push to gitlab, the build process keeps failing. The - pip install -r requirements.txt runs perfectly but once it gets to - python manage.py migrate, it fails. Below is the error I do get django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? Cleaning up project directory and file based variables ERROR: Job failed: exit code 1 -
How to loop inside Stripe
I have a problem I would like to loop inside Stripe to create dynamic multiple objects in checkout. I can not do that after stripe.checkout.Session.create() because I get an error. Also I can not create JSON object in for loop out of stripe.checkout.Session.create(). Any ideas? How can I use for loop and create multiple line_items? def create_checkout_session(request): if request.method == "GET": try: cart = Cart.objects.get(order_user=request.user) checkout_session = stripe.checkout.Session.create( payment_method_types=['card', 'p24'], line_items=[{ 'price_data': { 'currency': 'eur', 'product_data': { 'name': 'total' }, 'unit_amount': cart.total, }, 'quantity': 1, }], -
How can I extract URL of the video uploaded using Django Embed video
I am using Django Embed Video to upload videos to my website that works perfectly fine. The code below is how I extract the url of the video that I uploaded. HTML TEMPLATE: {% for course in courses %} <div class="name"> <h3>{{course.video}}</h3> </div> {% endfor %} That gives me the url but what i want is the video id for example the url it gives looks like "https://youtu.be/iHkKTGYc6aA" and I just need the "iHkKTGYc6aA". It can be done with the python using the .replace method but whenever I try to use the if tags of django html template i get this error: Could not parse the remainder: The HTML code that I use {% for course in courses %} <div class="name"> {% if text in course.video %} <h3>{{url=course.video.replace("https://youtu.be/", "")}} </h3> {% endif %} </div> {% endfor %} I know it's not the right way of doing it but I shared it just to show what i want to achieve. My views.py: def Courses(request): courses = Video.objects.all() total_uploaded_videos = courses.count() text = "https://youtu.be/" url = "" context = {'courses':courses, 'total_uploaded_videos':total_uploaded_videos, 'text':text, 'url':url} return render(request, 'accounts/Course.html', context) Models.py: class Video(models.Model): name = models.CharField(blank=False, max_length=100, default="", null=False, primary_key=True) video = EmbedVideoField() def __str__(self): … -
How to print host information from Django model while using ModelViewSet of REST Framework
I'm using Django REST Framework that will allow users to save information and generate QR code image which will be URL of the user profile such as: http://127.0.0.1:8000/user/detail/fahad-md-kamal-fd028af3/ Something Like How can I access host address from Django Model so that I can use it to generate QR code? DRF Model class UserInfo(models.Model): def save(self, *args, **kwargs): if not self.slug: self.slug =f'{slugify(self.name)}' qrcode_image = qrcode.make(f"{host}/{self.slug}/") super(UserInfo, self).save(*args, **kwargs) Serializer Class class UserBaseReadSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.UserBase fields = ( 'url', 'phone', 'name', 'address', 'qr_code', 'slug', ) View Class: class UserInfoViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserBaseSerializer queryset = models.UserInfo.objects.all() While I was doing it with standared Django and Functional View I did it like: Functional View: def add_user_info(request): if request.method == 'POST': form_data = UserInfomationForm(request.POST) if form_data.is_valid(): obj = form_data.save(commit=False) obj.save(host =request.META['HTTP_ORIGIN']) Over ridding Model Class's save method class UserInfo(models.Model): def save(self, host=None, *args, **kwargs): if not self.slug: self.slug =f'{slugify(self.name)}-{str(uuid.uuid4())[:8]}' qrcode_image = qrcode.make(f"{host}/{self.slug}/") super(UserInfo, self).save(*args, **kwargs) -
Django: passing context data between html file in different apps
How can I pass the context data (int his case profile_total variable) create in one of my views to the html template of another app? This is my code: app1.views.py def view_profile(request): profile_total = UserProfile.objects.all().count() return render(request, 'profile/user_profile.html', {'profile_total': profile_total}) app2.stats.html <div class="container"> <h1> Show </h1> Profile submitted: {{ profile_total }} </div> Right now it's only displayed a blank space instead that the count of the profile submitted. Thank you all for your helps! -
Implementing a custom authentication in DRF which can read request.data
I have a foreign key on my models like Patient, and Doctor, which point to a Clinic class. So, the Patient and Doctor are supposed to belong to this Clinic alone. Other Clinics should not be able to see any detail of these Models. From my Vue app, I will post using Axios to the django app which uses DRF, and thus get serialized data of Patients and Doctors. It all works fine if I try to use the following sample code in function view: @api_view(['GET', 'POST']) def register_patient_vue(request): if request.method == 'POST': print("POST details", request.data) data = request.data['registration_data'] serializer = customerSpecialSerializer(data=data) if serializer.is_valid(): a = serializer.save() print(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED) else: print("Serializer is notNot valid.") print(serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Sample output: POST details {'registration_data': {'name': 'wczz', 'ageyrs': 21, 'agemonths': '', 'dob': '', 'gender': 'unspecified', 'mobile': '2', 'email': '', 'alternate': '', 'address': '', 'marital': 'unspecified', 'city': '', 'occupation': '', 'linkedclinic': 10}} data: {'name': 'wczz', 'ageyrs': 21, 'agemonths': '', 'dob': '', 'gender': 'unspecified', 'mobile': '2', 'email': '', 'alternate': '', 'address': '', 'marital': 'unspecified', 'city': '', 'occupation': '', 'linkedclinic': 10} However, I need to authenticate the request by special custom authentication. I have another class called UserGroupMap which has Foreign Keys for … -
Get a single string attribute from my user's extended model
i think my question it's simple, but i'm new and i cannot figure it out. I have a user default Django model and my extended user model, and in my views.py i just want to get my logged user's address like a single string, i have been trying with different ways using (UserProfile.objects.values/filter/get etc...) but i just get errors. Thank you for your time! Models.py class UserProfile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) profile_pic = models.ImageField(null=True, blank=True, upload_to="profile_imgs") address = models.CharField(null=True, blank=True, max_length=150) curp = models.CharField(null=True, blank=True, max_length=18) Views.py @login_required(login_url='log') def test(request): address = "answer" context = { 'address': address, } return render(request, "test.html", context) -
How do I get Django to save Twilio Voice DTMF input to db.sqlite3?
I'm building an IVR using Python (3.9.5) Django (3.2.8) and Twilio Python Helper Library (7.1.0). My views.py contains multiple views which use Twilio's Gather verb to collect digits. How do I save this info to db.sqlite3? Example: models.py class Survey(models.Model): question1 = models.CharField(max_length=2) question2 = models.CharField(max_length=2) question3 = models.CharField(max_length=2) caller_id = models.CharField(max_length=12) date_time = models.DateTimeField(auto_now_add=True) Example: views.py def question1(): response = VoiceResponse() gather = Gather(input='dtmf') gather.say('How many cars do you own?') response.redirect('../question2') print(response) def question2(): response = VoiceResponse() gather = Gather(input='dtmf') gather.say('How many homes do you own?') response.redirect('../question3') print(response) def question3(): response = VoiceResponse() gather = Gather(input='dtmf') gather.say('How many boats do you own?') response.redirect('../end') print(response) def end(): response = VoiceResponse() response.say('One moment please.') response.pause(length=1) response.say('Thank you. Your input has been saved.') response.hangup() print(response) How do I save the collected digits to the appropriate fields specified in models.py? I only want to save the data once all 3 questions have been answered. If a caller hangs up before answering all 3 questions then I don't want to save anything. How do I save the caller id and date time to the appropiate fileds specified in models.py? I want this info to be displayed in the admin panel. Please help and thanks … -
How to provide context to django class view get method
I have a class based view which I want supply some context to but I don't know how I can achieve this Below is the views.py class Dashboard(LoginRequiredMixin, View): def get(self, request): if request.user is not None and len(request.user.payment_set.all()): if request.user.is_active and request.user.payment_set.first().active: print(eligible_to_review(self.request)) return render(request, 'main.html') else: return redirect('home') else: return redirect('membership') How can I pass a context to this view in order to use it in the html file -
PYODBC Multiple cursors
I hope you're ok Im writing a django app on py3.9.1 and want to execute multiple cursors on mssql server. Here is my connection to mssql database conn = pypyodbc.connect("....") cursor = conn.cursor() cursor1 = conn.cursor() Here is my views.py @login_required(login_url="user:login") @allowed_users(allowed_permissions=["Management Perm","Boss Perm","Account Perm"]) def bills(request): keyword = request.GET.get("keyword") header = "Faturalar | Mavis Development" company = UserCompany.objects.filter(user = request.user).values_list("company__company",flat=True)[0] role = request.user.groups.all()[0].name if keyword: bills_for_acc = cursor.execute("Select * From bills where mancheck = 0 and acccheck = 0 and company = ? and title = ? order by created_date",(company,keyword,)) bills_for_man = cursor1.execute("Select * From bills where mancheck = 0 and acccheck = 1 and company = ? and title = ? order by last_checked_date",(company,keyword)) content = { "bills_for_man":bills_for_man, "bills_for_acc":bills_for_acc, "header":header, "role":role, } return render(request,"bills.html",content) bills_for_acc = cursor.execute("Select * From bills where (acccheck = 0 and mancheck = 0) and company = ? order by created_date",(company,)) bills_for_man = cursor1.execute("Select * From bills where (mancheck = 0 and acccheck = 1) and company = ? order by last_checked_date",(company,)) content = { "bills_for_man":bills_for_man, "bills_for_acc":bills_for_acc, "header":header, "role":role, } return render(request,"bills.html",content) When I trying to show bills.html i get '('HY000', '[HY000] [Microsoft][ODBC SQL Server Driver]'Connection is busy with results for another hstmt.') On … -
How to add additional field in Django Rest Framework for a model that is a foreign key on another model
I am looking to list out all of the teachers in a certain department in Django rest framework and am unsure of how to do so. I believe this would be done by adding a field to the Department serializer but I am not sure. Is there an easy way of how this can be done. models.py class Department(models.Model): name = models.CharField(max_length=300) def __str__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=300) department = models.ForeignKey(Department, on_delete=models.CASCADE) tenure = models.BooleanField() serializers.py class DepartmentSerializer(serializers.HyperlinkedModelSerializer): #What I believe the serializer field would look like to list teachers connected #with a department teacher = serializers.DjangoModelField( Teacher.objects.filter(department=self.department)) class Meta: model = Department fields = ['url', 'name', 'teacher'] urls.py router = DefaultRouter() router.register(r'teachers', TeacherViewSet) router.register(r'departments', DepartmentViewSet) router.register(r'users', UserViewSet) urlpatterns = [ path('api/', include(router.urls)), ] views.py class TeacherViewSet(viewsets.ModelViewSet): queryset = Teacher.objects.all() serializer_class = TeacherSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] class DepartmentViewSet(viewsets.ModelViewSet): queryset = Department.objects.all() serializer_class = DepartmentSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] -
OpenLDAP docker Osixia - can not authenticate
I've just tried to configure docker-compose.yml file according to YTB video and github, but with any result. version: "2" services: web: # the application's web service (container) will use an image based on our Dockerfile build: "." # map the internal port 80 to port 8000 on the host ports: - "8000:80" # map the host directory to app (which allows us to see and edit files inside the container) volumes: - ".:/app:rw" - "./data:/data:rw" # the default command to run whenever the container is launched # command: python manage.py runserver 0.0.0.0:80 # the URL 'postgres' or 'mysql' will point to the application's db service links: - "database_default" env_file: .env-local database_default: # Select one of the following db configurations for the database image: postgres:9.6-alpine environment: POSTGRES_DB: "db" POSTGRES_HOST_AUTH_METHOD: "trust" SERVICE_MANAGER: "fsm-postgres" volumes: - ".:/app:rw" openldap_service: image: osixia/openldap:1.1.8 ports: - "636:636" volumes: - ".:/data:rw" environment: - LDAP_ORGANISATION=ramhlocal - LDAP_DOMAIN=ramhlocal.com - LDAP_ADMIN_USERNAME=admin - LDAP_ADMIN_PASSWORD=admin_pass - LDAP_CONFIG_PASSWORD=config_pass - "LDAP_BASE_DN=dc=ramhlocal,dc=com" - LDAP_TLS_CRT_FILENAME=server.crt - LDAP_TLS_KEY_FILENAME=server.key - LDAP_TLS_CA_CRT_FILENAME=ramhlocal.com.ca.crt - LDAP_READONLY_USER=true - LDAP_READONLY_USER_USERNAME=user-ro - LDAP_READONLY_USER_PASSWORD=ro_pass phpldapadmin-service: image: osixia/phpldapadmin:0.9.0 environment: - PHPLDAPADMIN_LDAP_HOSTS=127.0.0.1 ports: - "6443:443" volumes: - ".:/data:rw" I can go to the phpldapadmin, but it shows this:enter image description here Would you know, where is the problem? … -
Django & microservices - How can I design microservices in django
I'm learning Microservices and there s requirement to develop like a Amazon filter and there are other filter as well.How could I able to do it with microservices. UI Design specifically has the filters on the right whenever the user select the filter the particular element containing row should be displayed on the right side of the table. For designing the microservices can I take the all data which is provided in microservices and filter in another microservices. I just stuck with the filter part how can I design with django it supposed to be done from the front side ? Or can it be designed through microservices. I design only the api with the microservices or do I make back end functionality for that.i have major doubt if I design only the api how could I call in django template? Is microservices only creating an api.for instance there is an django project where user can like and comment on the post. In like where users can like the post and comment project where user can comment on the post. And both are dockerised as well.Both connected through microservices in order to get a like and comment together in the … -
Deploying Django app : Forbidden You don't have permission to access this resource
I was deploying my django app on my VPS using the apache web server. It works totally fine on http://192.46.209.82:8000/ but when I try to access the same using my IP address, 192.46.209.82. I get Forbidden You don't have permission to access this resource. Apache/2.4.41 (Ubuntu) Server at 192.46.209.82 Port 80 Here is my conf file nano /etc/apache2/sites-available/000-default.conf <VirtualHost *:80> ServerAdmin webmaster@example.com DocumentRoot /root/django/myproject ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /root/django/myproject/static <Directory /root/django/myproject/static> Require all granted </Directory> <Directory /root/django/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/root/django/myproject python-home=/root/django/myprojectenv WSGIProcessGroup myproject WSGIScriptAlias / /root/django/myproject/myproject/wsgi.py </VirtualHost> I am using python's virtual environment, where myprojectenv is my virtual env path and the pwd is /root/django Note : I tried the answer from the question that I was getting as suggestion to this question but that did not work for me. -
How do I install Python web project on Centos
I have created a Python web application using VS2022 (Django Web Project type). It is working as I expect using local url access - executing from VS2022. However, how do I proceed to implementing this as an operating web site on a server. I have a Centos 8 server with complete root control. With simple html pages I can upload this then enter my URL in a browser and all ok. Can anyone give me the broad details of how to achieve the same thing with my Python code. I know I have to install pip, Python (3 in this case) and Django but beyond that I am not sure how to proceed. Apologies as this is such a broad question, I just need some pointers or tutorial type links. thanks in advance -
Django api requests not working on AWS elastic beanstalk
I've created a django application and deployed it using aws elastic beanstalk. The GET requests to fetch the static files are working fine. But any other requests made directed to the django app specifically, is timing out. Here is the commands in .ebextensions folder 01_packages.config packages: yum: postgresql-devel: [] django.config option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "app_server.settings" "PYTHONPATH": "/var/app/current:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: app_server.wsgi:application NumProcesses: 3 NumThreads: 20 aws:elasticbeanstalk:environment:proxy:staticfiles: /static/: "staticfiles/" These are installed apps and middleware settings in settings.py file INSTALLED_APPS = [ 'insta_backend.apps.InstaBackendConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'storages' ] MIDDLEWARE = [ # 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # 'corsheaders.middleware.CorsMiddleware', # "whitenoise.middleware.WhiteNoiseMiddleware", 'django.middleware.common.CommonMiddleware', ] The routes of the django app work fine locally. But when deployed using EB, the requests are timing out or cancelled. The preflight request made here times out. Following is the screenshot of the network requests from chrome dev tools