Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The formview view API in django.views.generic cannot be seen on the swagger page
I am using Django and drf_yasg, and I hope to add this interface to the swagger page when using the form view. However, I have tried several times and cannot achieve it. The code is as follows: class CustomRegisterView(FormView): template_name = "registration/register.html" form_class = RegisterForm success_url = reverse_lazy("home") swagger_schema = { "tags": ["user"], "method": "post", "operation_id": "register_user", "operation_description": "User registration with email and password", "request_body": openapi.Schema( type=openapi.TYPE_OBJECT, properties={ "first_name": openapi.Schema(type=openapi.TYPE_STRING, default=""), "last_name": openapi.Schema(type=openapi.TYPE_STRING, default=""), "username": openapi.Schema(type=openapi.TYPE_STRING), "email": openapi.Schema(type=openapi.FORMAT_EMAIL), "password1": openapi.Schema(type=openapi.FORMAT_PASSWORD), "password2": openapi.Schema(type=openapi.FORMAT_PASSWORD), }, required=["username", "email", "password1", "password2"], ), "responses": { status.HTTP_200_OK: openapi.Response( description="Successfully registered", schema=openapi.Schema( type=openapi.TYPE_OBJECT, properties={"message": openapi.Schema(type=openapi.TYPE_STRING, description="Successfully registered")}, ) ), status.HTTP_400_BAD_REQUEST: openapi.Response( description="Registration failed", schema=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ "detail": openapi.Schema( type=openapi.TYPE_STRING, description="Registration error message", ), }, ), ), }, } def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) It can't help me debug on the swagger page, it is not rendered to the swagger page, what is the main reason? I tried the @swagger_auto_schema decorator, and it didn't work. Is there any other view writing method except drf to the standard API writing method? Can't get the support of drf-yasg? If you want the views in FormView and django.contrib.auth.views to be rendered … -
Django: I can't display any image
I can't get Django to render my images on the site. I'm pretty sure that I'm missing something obvious but I need someone to help me out here. Here are my files: settings.py """ Django settings for elpaj project. Generated by 'django-admin startproject' using Django 4.2. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-9e_h-bf@yn+e(!=fc!vu5v=h-4wi&(ilguai-+cenx(mqls-lq' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store.apps.StoreConfig', ] 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 = 'elpaj.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 = 'elpaj.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password … -
Django invalid tag error is showing up everytime
Hi I am writing a Django template and using some nested loops and conditions in it Here the main snippet of the template: {% for product in products %} {% if product.isVariation == "yes" %} {% for var in product.variations %} <tr> <td><input type="checkbox"></td> {for image in product.images %} <td><img src="{{image}}" style="height:250px; width:200px;"></td> {% endfor %} <td>{{var.sku}} Condition: {{var.condition}}</td> <td>{{product.name}}</td> <td>{{product.CreatedDateTime}}</td> <td><input type="text" class="form-control" id="formGroupExampleInput" placeholder="Amount" value={{var.units}}></td> <td><input type="text" class="form-control" id="formGroupExampleInput" placeholder="PKR" value={{var.price}}></td> <td> <div style="display: flex; justify-content: flex-end"> <button style="width: 100px;" type="button" class="btn btn-primary btn-outline-dark text-white bg-gradient"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-pencil-square" viewBox="0 0 16 16"> <path d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z"/> <path fill-rule="evenodd" d="M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z"/> </svg> Edit</button> <button style="width: 100px;" type="button" class="btn btn-success btn-outline-dark text-white bg-gradient"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-box-arrow-down" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M3.5 10a.5.5 0 0 1-.5-.5v-8a.5.5 0 0 1 .5-.5h9a.5.5 0 0 … -
I am getting the error ModuleNotFoundError: No module named 'celery' ubuntu 20.04 server
I have been trying for 2 days straight to solve this, but, I haven't had any luck I am running celery with supervisor it shows running I can see it in systemctl and supervisor web interface via 9001 port everytime I run a celery related task I get this error. File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/toch/outdoorsy/core/__init__.py", line 3, in <module> from .celery_config import app as celery_app File "/home/toch/outdoorsy/core/celery_config.py", line 3, in <module> from celery import Celery ModuleNotFoundError: No module named 'celery' [2023-05-01 00:18:04,062: INFO/ForkPoolWorker-4] Task dashboard.tasks.run_scrape_outdoorsy[63235a91-79f9-4976-a6ee-773fa2582a31] succeeded in 0.8941846380475909s: None What is even weird is that the task used to run previously and what's even weirder is that last line show task was successfull and it's saved in celery-results admin interface for django Running Django with nginx, gunicorn and celery -
How am I supposed to link the CustomUser model to my Dog model so that when I post a new dog its owner will be the currently logged in user?
I am trying to create a post for a new dog object which will then be added to the database and the owner of it will be the user that is currently logged in. I don't get any errors, but I can't see the new dog in my admin page either. My project has 2 apps: the "petapp" app which is the main one and the "users" app which is for creating Custom Users. I will include my code below: in the AddDog.vue component, here is the script part of it: import {defineComponent} from 'vue'; export default defineComponent({ methods:{ async postDog(event){ event.preventDefault(); let dogFormData=new FormData(); var input=document.getElementById('picture_d2'); var new_picture_d=input.files[0]; console.log(new_picture_d) let new_name_d=document.getElementById('name_d2').value; let new_age_d=document.getElementById('age_d2').value; let new_date_d=document.getElementById('date_d2').value; let new_county_d=document.getElementById('county_d2').value; let new_color_d=document.getElementById('color_d2').value; let new_description_d=document.getElementById('description_d2').value; let new_breed_d=document.getElementById('breed_d2').value; let new_gender_d=document.getElementById('gender_d2').value; let new_status_d=document.getElementById('status_d2').value; let new_entry={ name_d: new_name_d, age_d: new_age_d, date_d: new_date_d, county_d: new_county_d, color_d: new_color_d, description_d: new_description_d, breed_d: new_breed_d, gender_d: new_gender_d, status_d: new_status_d, } console.log(new_entry) dogFormData.append('age_d', new_age_d); dogFormData.append('name_d', new_name_d); dogFormData.append('county_d', new_county_d); dogFormData.append('picture_d', new_picture_d); dogFormData.append('color_d', new_color_d); dogFormData.append('description_d', new_description_d); dogFormData.append('date_d', new_date_d); dogFormData.append('breed_d', new_breed_d); dogFormData.append('gender_d', new_gender_d); dogFormData.append('status_d', new_status_d); console.log("this is form data") console.log(dogFormData) let response=await fetch('http://127.0.0.1:8000/newdog/',{ method: 'POST', body: dogFormData, }); if(response.ok){ document.getElementById('name_d2').value="", document.getElementById('age_d2').value="", document.getElementById('date_d2').value="", document.getElementById('county_d2').value="", document.getElementById('color_d2').value="", document.getElementById('description_d2').value="", document.getElementById('breed_d2').value="", document.getElementById('gender_d2').value="", document.getElementById('status_d2').value="", document.getElementById('picture_d2').value="" this.$router.push('/newdog'); } else alert('Dog cannot be … -
Kubernetes health check always fails for django application
I'm kinda new to kubernetes and I'm trying to figure out how to configure my health check. When I configure my livenessProbe it always returns a 400, but when I remove the probe, exec into the pod, and run curl 127.0.0.1/health I get {"status": "ok"}. (I'm running this locally on a minikube host) Here's my dockerfile FROM python:3.11 # setup env variables ENV PYTHONBUFFERED=1 ENV DockerHOME=/app/django-app # Expose port EXPOSE 8000 # create work dir RUN mkdir -p $DockerHOME # set work dir WORKDIR $DockerHOME # copy code to work dir COPY . $DockerHOME # install dependencies RUN pip install -r requirements.txt # move working dir to where manage.py is WORKDIR $DockerHOME/flag_games # set default command (I thinkk) ENTRYPOINT ["python"] # run commands for app to run CMD ["manage.py", "collectstatic", "--noinput"] CMD ["manage.py", "runserver", "localhost:8000"] Here's my deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: flag-game-deployment labels: app: flag-game-deployment spec: replicas: 3 selector: matchLabels: app: flag-game-deployment template: metadata: labels: app: flag-game-deployment spec: containers: - image: docker-django imagePullPolicy: Never name: docker-django livenessProbe: httpGet: path: /health port: 8000 scheme: HTTP initialDelaySeconds: 5 periodSeconds: 5 Here's the steps to my makebuild minikube-deploy: make docker-build minikube start minikube image load $(IMAGE_NAME) kubectl apply -f "$(PWD)\manifests\deployment.yaml" … -
Django block content not working properly
I have a base.html file with the following code: {% load static %} {% load custom_tags %} <!DOCTYPE html> <html lang="en"> <body> <style> html { scroll-behavior: smooth; } *, body { margin: 0; } body { display:flex; flex-direction:row; background: #030914; background: url('/static/dashimages/map.svg'), #030914;; background-attachment: fixed; overflow-y:scroll; } .nav-container { width: 200px; padding: 20px; position: fixed; top: 0; left: 0; height: 100%; max-height: 100vh; border-right: 2px solid rgba(33, 40, 54, 0.5); overflow: hidden; padding-top: 35px; } .nav-links { display:flex; flex-direction:column; justify-content:center; align-items:center; gap: 25px; margin-top: 30px; } .nav-link { display:flex; flex-direction:row; justify-content: flex-start; width: 110%; padding: 14px 20px; gap: 20px; transform: rotate(5deg); } .nav-link:hover { cursor: pointer; } .nav-link a { font-family: 'Poppins'; font-weight: 700; font-size: 19px; color: rgba(255, 255, 255, 0.15); } .nav-link img { width: 25px; height: 25px; } .nav-active a { background: linear-gradient(90deg, #A2FACF 0%, #64ACFF 101.4%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; text-fill-color: transparent; } .nav-active { background: linear-gradient(90deg, rgba(162, 250, 207, 0.10) 0%, rgba(100, 172, 255, 0.1) 101.4%); } </style> {% block nav %} <div class="nav-container"> <img src="{% static 'levelstatic/assets/coderalogo.svg' %}" style="margin: 0 auto; width: 80%; margin-bottom: 25px;" alt="CODERA"> <div class="nav-links"> <div class="nav-link nav-active"> <img src="{% static '/dashimages/learn.svg' %}" > <a>LEARN</a> </div> <div class="nav-link"> <img src="{% … -
Django Template Language | How to write "model.model_set.FILTER" in a template
I need to filter through a model set in my django template. Basically, instead of model.model_set.all, I need model.model_set.filter(days=today) ALSO. I am aware that a similar question was asked here: How do I perform query filtering in django templates I felt that none of the answers provided sufficient information, and as well as that, some of the most upvoted ones are old and therefore outdated. Any help is greatly appreciated! models.py class Employee(models.Model): employer = models.ForeignKey(Business, on_delete=models.CASCADE) user = models.OneToOneField(Account, on_delete=models.CASCADE, default='', null=True) def __str__(self): return str(self.user) class Time(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, default='', null=True, blank=True) business = models.ForeignKey(Business, on_delete=models.CASCADE, default='', null=True, blank=True) start_time = models.TimeField(blank=True, null=True) finish_time = models.TimeField(blank=True, null=True) days = models.CharField(max_length=9, choices=DAYS_OF_WEEK, default="Monday") def __str__(self): return (f"{self.start_time} - {self.finish_time}") views.py @login_required(login_url="login") def manage_business(request): user_business = Business.objects.get(owner = request.user) employees = Employee.objects.filter(employer = user_business) todays_times = Time.objects.filter(Q(days=datetime.today().strftime("%A")) & Q(business = user_business)) today = datetime.today().strftime("%A") hours = Time.objects.filter(business = user_business) context = {"today":today, "business":user_business, "employees":employees, "hours":hours, "todays_times":todays_times} return render(request, "base/manage_business.html", context) manage_business.html {% for e in employees %} <div class="employee-container"> <div class="flex-item" name="js-jobs"> <div class="main-text-container"> <h1 class="name">{{e.user.name}}</h1> {% for todaytime in e.time_set.all %} {% if todaytime.days == today %} <p class="employee-time">Today | {{todaytime.start_time}} - {{todaytime.finish_time}}</p> {% else %} <p … -
Django request select_related how to access grandparent
I'm constructing a website with a 3-level hierarchy of pages, so my Page model have a foreign key, referring to itself: class Page(models.Model): ... parent = models.ForeignKey('self', on_delete=models.SET_NULL, blank=True, null=True, related_name='subpages', related_query_name='subs') When I get a page in my PageDetailView, I want to get it with its parent (if there is one) and a grandparent (if the parent has its parent). If I needed only a parent, it would be quite simple: page = Page.objects.select_related('parent').get(slug=self.kwargs['slug']) But I need also to select_related "a parent of parent". I cannot figure out how to do it. It could look like following: page = Page.objects.select_related( 'parent', Page.objects.select_related('parent' as 'grandparent') ).get(slug=self.kwargs['slug']) Please give me a hint how to access not only parent but also a grandparent of a page. -
Probelm with implement facebook login with meta for developer [closed]
I follow this step on meta for developer for create my facebook login: craete an app, add the domain name (localhost), add the website url(http://localhost:8000) when i put this url:http://localhost:8000/ i cant save my change cause this error: This must be a valid Site URL in order to be compliant with Facebook Platform. But i see people in old videos that don't have this issue. So i want understand how to fix it I tried to follow some tutorial and also to change settings in django but the result doesn't change.PS: with google login i have no problem and follow the same step of the facebook login tutorial. Hope someone can help me -
How do I get the crtieria from the queryset based on the iteration of the for loop in django?
I am looping through a formset which generates a feedback form for assignments, and I need to add a label to display the criteria of an assignment so the user knows what criteria they are marking. I've got as far as creating a queryset and passing this queryset to the context. The problem comes with trying to access the correct one within the template. The length of the formset and the length of the criteria result set will always be the same so I want to just access the first element on the first iteration and so on. The problem I'm having is an odd one in that I can access the elements manually like so: {{criteria.0}} but whenever I attempt to do so dynamically: {{criteria.forloop.counter}} or {% with curr=forloop.counter0 %} <td>{{ criteria.curr }}</td> Nothing is outputted at all. View Code ( rendering formset): formset = FeedbackFormset(queryset=Feedback.objects.none()) for i, criterion in enumerate(criteria): formset.forms[i].fields['criteriaLevelID'].queryset = criterion.criterialevel_set.all() context = { 'submission': submission, 'formset': formset, 'criteria':criteria } return render(request, 'markingApp/createFeedback.html', context) -
Django Ninja api call from inside a django view
I am just learning Django and Django Ninja API. I have created a simple Api to create and read object(s). models.py class Person (models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) schemas.py class PersonIn(ModelSchema): class Config: model = Person model_fields = ["first_name", "last_name"] class PersonOut(ModelSchema): # Just to make it clear class Config: model = Person model_fields = ["first_name", "last_name"] api.py @router.post("/person") def create_person(request, payload: PersonIn): data = payload.dict() try: person, created = Person.objects.update_or_create(**data) except Exception: return { "mesg": "Some error happened"} @router.get("/persons", response = list[PersonOut]) def get_persons(request): p = get_list_or_404(Person) return p views.py def get_persons_view(request): persons = ??? render(request,"personlist_template.html", {"persons": persons}) If I import the function api, then it returns Person Model object rather than serialized object in the form of PersonOut. I wanted to use the api call in way that it returns the serialized form as being called through API url. This way I am attempting to avoid rewriting that serialization code again. Also, I wanted to use in my template key:value pairs to generate a table for all attributes. I found 2 methods for objective 2. One is using Django Serializers. In this case I need to have separate method, if I am serializing single model isntance. … -
Why after button click GET method instead of POST
my view.py note_detail should show details about note like title and description. note_delete should delete current note. @login_required def note_detail(request: HttpRequest, note_uuid: str) -> HttpResponse: note = get_object_or_404(Note, id=uuid.UUID(note_uuid)) if request.method == "POST": note_form = NoteEditForm(instance=request.user, data=request.POST) if note_form.is_valid(): note_form.save() messages.success(request, "Success") else: messages.error(request, "Error") else: note_form = NoteEditForm( initial={ "title": note.title, "description": note.description, }, ) return render( request, "note/note_detail.html", { "note": note, "note_form": note_form, }, ) @login_required def note_delete(request: HttpRequest, note_uuid: str) -> HttpResponse: note = get_object_or_404(Note, id=uuid.UUID(note_uuid)) if request.method == "POST": note.delete() return redirect(reverse("note:note_list")) return render( request, "note/note_detail.html", { "note": note, }, ) html form <form action="{% url 'note:note_delete' note_uuid=note.id %}" method="post"> {% csrf_token %} <button type="submit" class="btn btn-danger" style="margin-right: 5px;"> Delete </button> </form> urls.ly from django.urls import path from apps.note import views app_name = "note" urlpatterns = [ path("create/", views.note_create, name="note_create"), path("list/", views.note_list, name="note_list"), path("detail/<str:note_uuid>/", views.note_detail, name="note_detail"), path("delete/<str:note_uuid>/", views.note_delete, name="note_delete"), ] logs Im try to search this but could not find an answer. Please tell me why this is happening and help me fix it. -
After using ListView Django cannot find my Template
I writing catalog of shop-site, but i have a problem. I used function ListView at views.py: class BagsListView (generic.ListView): model= Bag Also i have this code at urls.py: urlpatterns = [ ... re_path (r'^bags/$', views.BagsListView.as_view(), name='Bag'),] After runserver, when i go to http://127.0.0.1:8000/bags/ i got this false enter image description here So, it was despite that i have every html files at every directory: enter image description here Can you please help me - where i got mistake?! Thank you in advance.. To fix it i tried to specified template name class BagsListView (generic.ListView): model= Bag template_name = 'templates/bag_list.html' But it still doesnt work -
Unable to filter using django-filters
I have a models.py which looks like this class Product(models.Model): name = models.CharField(max_length = 255, unique = True, null = False, blank = False) brand = models.ForeignKey(Brand, on_delete = models.SET_NULL, null = True, blank = True, related_name = 'products') class Brand(models.Model): name = models.CharField(max_length = 255, unique = True, null = False, blank = False) I want to filter the data of Products based on name field of Brand model. My views.py looks like this class ProductAPIView(generics.GenericAPIView): serializer_class = ProductSerializer queryset = Product.objects.all() filter_backends = (DjangoFilterBackend,) filterset_class = ProductFilter def get(self, request): products = self.filter_queryset(self.get_queryset()) serializer = self.serializer_class(products, many = True) return Response(serializer.data) My filters.py looks like this class ProductFilter(FilterSet): class Meta: model = Product fields = { 'brand__name' : ['iexact', ] } Whatever query params i send for brand, it results with the entire list instead of filtering the required list. Is there something i'm missing out here ? Thanks in advance -
'property' object is not iterable
can someone please help me with this error in django? ERRORS: <class 'members.admin.MemberAdmin'>: (admin.E108) The value of 'list_display[4]' refers to 'age', which is not a callable, an attribute of 'MemberAdmin', or an attribute or method on 'members.Member'. Here are screenshots of my models.py and admin.py models.py admin.py I already tried finding solutions from different sites but until now I can't find the correct solution for my problem. Hoping someone will help. I am expecting to add a computed age field in models in django. -
Docker-Compose Ports
compose file i want to connect my django container to my maria_db container but when i specify port 3306 in django it work fine but when i specify port 3307 to django it fail although my maria_db port sets to "3307:3306" does anybody can explain how that possible?enter image description here try to connect maria_db to my django container with port 3307 -
How to handle many models and queryset in a single template?
I don't know how can I access to multiple models in a single template? in other words, what kind of queryset or template code do I have to use? In my case, I have 3 models: first, Lead, which concerns lead informations, second is leadstatus, which talks about where lead were found and third actions to do with him. in a kind of contact-list view where I use a function def contactList(request):. My goal is to display, in an array, some of the information about this lead, about his status, and about the last action to do with him. So, what kind of queryset do I have to write in the view or what kind of code do I have to use in the template? SO here is my models.py: class Lead (models.Model): #this model only takes private and personal items from the contact user = models.ForeignKey(User, on_delete=models.CASCADE) firstname = models.CharField(max_length=255, null=True, blank=True ) lastname = models.CharField(max_length=255, null=True, blank=True) address = models.CharField(max_length=255, null=True, blank=True) zipcode = models.CharField(max_length=255, null=True, blank=True) city = models.CharField(max_length=255, null=True, blank=True ) email = models.EmailField( verbose_name='adresse email', max_length=255, unique=True, ) phone = models.CharField(max_length=255, null=True, blank=True, unique=True ) FAMILY_SITUATION = [ ("Celib", "Celib"), ("Couple", "Couple"), ("Veuf", "Veuf"), ] … -
What it can be? ModuleNotFoundError [closed]
Working with Django I faced with very strange problem. I wanted to create a request, but url list can't see my path.. I have tried to change pathes, but it didn't helped -
Disable Django to keep only Django Rest Framework for Vue
for a school project, I have to use Django and Vue. Django to provide an API and Vue for the frontend. They are two separate projects that we have mix. For example, I type my-site/clients, it gives me the list of the clients in json format (API). But if I type my-site/home it gives me a Vue page. I tried to run the two servers on the same port, but that is not compatible (Django want to display a page when it has to Vue to display it). So I was thinking to disable the Django to only keep Django Rest Framework for the API. Is it possible ? Thank you ! -
Django & PostgreSQL - backup and restore part of the database
Current Implementation: I have a Django application on one server that uses a PostgreSQL database instance in the same server. This Django app is served using UWSGI as an app server, then NGINX layer on top of it as a web server. This database instance has a complex schema that handles multiple companies' data. Each single row is related to one company. Based on the user's company, he can work on his company's data only. So, an isolation is implemented for each company users. New Business Requirement: A backup should be taken daily from the database mainly because any company may need to rollback to an old version of their data (for example, 3 days back). So, I have done some research and I came up with multiple options: Option 1: having one Django application but with multiple database instances, and controlling the selected database based on the subdomain where each subdomain represents one company. This makes it possible to backup and restore a single instance of the database if needed at any point of time, but it makes it complex in code to separate the selected database by company. Also, it could be harmful for the single application to … -
Processing a file on client side in Django?
I want to build a web application where a user can upload a file, the file is processed and some result is shown to the user (for example the amount of lines of the file). However, since the files might be confidential, the user does not want that the file is stored on the server side. So the file needs to be processed without storing it on the server. Since I am familiar with Python, I wanted to create the website using Django (I want to learn it anyway). But as I understood, Django is a server framework, so is it even achievable using Django what I want to do? How? Or do I need to use React and Django? Or only React? -
Can’t open database while using Django in VSCode
I’m working on a django project and I’m trying to open database in VSCode but I keep getting “failed to open database” error. The sql explorer doesn’t even show up on the explorer pane. I have SQLite extension installed. I’ve also installed sqlite3 on my computer and it works according the cmd prompt. But I’m still getting this error message. I read the Django documentation and I’m not sure if I need to make any changes in settings.py? This is what it looks like ENGINE: ‘django.db.backends.sqlite3’, NAME: BASE_DIR / ‘db.sqlite3’, I’m using a windows 10. Any help would be appreciated. This is my first django project so I’m still learning. -
Django Q object to query vendors near my location within their delivery radius
I am trying to get from a query all vendors in 10km radius and i got it working with: latitude = 51.507506503730866 longitude = -0.12812200560448234 radius = 10 if latitude and longitude and radius: pnt = GEOSGeometry("POINT(%s %s)" %(longitude, latitude)) vendors = Vendor.objects.filter(Q(is_approved=True, user__is_active=True), user_profile__location__distance_lte=(pnt, D(km=radius))).annotate(distance=Distance("user_profile__location", pnt)).order_by("distance") When i loop through vendor i can get the distance between user_profile and vendors with: for v in vendors: print(v) print(v.user_profile.location) No I would like to filter it so only the vendors within the max_delivery_distance in range be listed. I dont now if i have to add it in the same query or do a separeted query for it. I now this is a bit specific but if some one has this know how i would be thankfull for any directions. thank you very much in advance reynaldo -
'function' object has no attribute 'getlist'
I have an error in my Django project my project cannot understand the getlist function what is the problem and what can I do? my code is this: req = request.post.getlist('name1[]') and the error is this: AttributeError at / 'function' object has no attribute 'getlist'