Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        Django how to write single object query in my exportcsv function?I write this function for export csv file. I am using this query patient = Patient.objects.all() for export all objects. But I have details page for each objects and I want to export each items individually from my details page. how to write query for get single object? here is my code: models.py class Patient(models.Model): patient_name = models.CharField(max_length=150) patient_id = models.CharField(max_length=100,blank=True,null=True) date_of_birth = models.DateField() age = models.CharField(max_length=100,blank=True,null=True) phone = models.CharField(max_length=100) email = models.EmailField(blank=True,null=True) slug = models.SlugField(max_length=255,unique=True,blank=True,null=True) views.py def exportcsv(request): #I am exporting csv file from this view response = HttpResponse(content_type='text/csv') response ['Content-Disposition'] = 'attachment; filename=PatientData'+str(datetime.datetime.now())+'.csv' writer = csv.writer(response) writer.writerow(['patient_name']) patient = Patient.objects.all() for i in patient: print(i.patient_name) writer.writerow([i.patient_name]) return response #this view for showing details info of each items class PatientDeleteView(DeleteView): model = Patient template_name = 'hospital/patient-delete.html' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) messages.add_message(self.request, messages.INFO, 'Patient Deleted Sucessfully') return data success_url = reverse_lazy('hospital:all-patient') #urls.py path('export-csv-patient-data/',views.exportcsv,name='export-csv-patient-data'), path('<slug:slug>/patient-details/',PatientDetails.as_view(),name='patient-details'), Now it's downloading all objects I want it will download only single objects from details page.
- 
        How to get current account id in django models.pyI want to get the id of the current account in django models.py. I know I can get the user object of the current account by adding 'request.user'. However, the function I am using requires the use of the self argument to be used in the condition, so 'request' cannot be used together. Please help. [models.py] class Leave(models.Model): name = models.CharField(max_length=50, blank=True, null=True) kind = models.CharField(choices=KIND_CHOICES, max_length=20, blank=True, null=True) from_date = models.DateField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) @property def get_html_url(self): url = reverse('leave:leave_edit', args=(self.id,)) if self.kind == 'Annual' and self.user.id == self.user_id: return f'<div class="Annual-title"><a href="{url}" style="color:black;"> {self.name} </a></div>' elif self.kind == 'Annual' and self.user.id != self.user_id: return f'<div class="Annual-title" data-toggle="modal" data-target="#leave_{self.id}"> {self.name} </div>' Does the method below work normally? [models.py] class Leave(models.Model): name = models.CharField(max_length=50, blank=True, null=True) kind = models.CharField(choices=KIND_CHOICES, max_length=20, blank=True, null=True) from_date = models.DateField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) def user_id(request): +++ add return request.user @property def get_html_url(self): url = reverse('leave:leave_edit', args=(self.id,)) if self.kind == 'Annual' and self.user.id == Leave.user_id: return f'<div class="Annual-title"><a href="{url}" style="color:black;"> {self.name} </a></div>' elif self.kind == 'Annual' and self.user.id != Leave.user_id: return f'<div class="Annual-title" data-toggle="modal" data-target="#leave_{self.id}"> {self.name} </div>'
- 
        Vue.js and drf imagesI am currently trying to render images from my DRF to my vue.js template. I can see the image arrays in my console and have been successful using Postman with the get request but I can not seem to render the multiple images in my vue template. Im not sure whether I need to loop through the photos array in the lesson dictionary or link the id to the photo url? Any help on this would be really appreciated. Vue.js <template v-if="activeLesson"> <h2>{{ activeLesson.title }}</h2> {{ activeLesson.long_description }} <figure class="image is-square"> <img v-for="(photo, index) in activeLesson.photos" :src="activeLesson.photo_url" :key="index" /> </figure> <script> import axios from 'axios' export default { data() { return { course: {}, lessons: [], comments: [], activeLesson: null, errors: [], photo_url:'', comment: { name: '', content: '' }, } }, async mounted() { console.log('mounted') const slug = this.$route.params.slug await axios .get(`/api/v1/courses/${slug}/`) .then(response => { console.log(response.data) this.course = response.data.course this.lessons = response.data.lessons this.photos = response.data.photos }) document.title = this.course.title + ' | Relate' }, methods: { submitComment() { console.log('submitComment') this.errors = [] if (this.comment.name === '') { this.errors.push('The name must be filled out') } if (this.comment.content === '') { this.errors.push('The content must be filled out') } if (!this.errors.length) { …
- 
        Is it better to create a OneToOne relation or a custom filed? [DJANGO]I want to create a Venue model and save the location object, here's my code that actually works: class Location(models.Model): latitude = models.FloatField() longitude = models.FloatField() address = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=100, blank=True) class Venue(models.Model): name = models.CharField(max_length=255) location = models.OneToOneField(Location) As you can see, if I delete Venue the corresponding location will not be deleted, because OneToOne works so. Is it better to create a custom field, let's say LocationField, with latitude, longitude... properties and put it inside Venue, or is this the right solution?
- 
        Django - Saving multiple optional objects with a CreateViewI'm working on a real estate app where users can apply to rent a house or apartment. I'm having trouble grasping the concept of saving multiple objects and tying them together. I want the form to allow 1 to 4 people to apply for a single property. I either want 1 page where the user can select the number of applicants and the form save X number of people objects or I'm thinking of adding 2 buttons, on one to save and complete (current person), and another to save and add a new person. Additionally, I want to add all the applicants to a single application table. so I can query my database to view all the applicants on a single application. I'm not sure the best way to handle that. models class Properties(models.Model): property_num = models.IntegerField() property_road = models.CharField(max_length=200) rent = models.IntegerField(default=1000) city = models.CharField(max_length=200) state = models.CharField(choices=STATE_CHOICE, max_length=25) zip = models.IntegerField() bedrooms = models.IntegerField() bathrooms = models.FloatField(max_length=3) sq_foot = models.IntegerField() description = models.TextField(default=bedrooms) is_active = models.BooleanField(default=True) thumbnail = models.ImageField(upload_to='static/images', blank=True) slug = models.SlugField(blank=True, null=True, unique=True, allow_unicode=True) class Person(models.Model): address = models.ForeignKey(Properties, on_delete=models.CASCADE) requested_move_in_date = models.DateField(default=datetime.now) first_name = models.CharField(max_length=200) middle_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) dob = models.CharField(max_length=200) driver_license …
- 
        why module 'polls.views' has no attribute 'results'During the "Django" project, We found an error in the process of showing the results with the .html module. What is the solution to this error? import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def wat_published_recently(self): return self.pub_date >= timezone.now() datetime.timedelta(day=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) # def __str__(self): # return self.choice_text polls/urls.py from django.urls import path from . import views urlpatterns = [ # ex: /polls/ path('', views.index, name='index'), # ex: /polls/5 path('<int:question_id>/', views.detail, name='detail'), # ex: polls/5/results/ path('<int:question_id>/results/', views.results, name='results'), # ex: /polls/5/vote/ path('<int:question_id>vote/', views.vote, name='vote'), # added the word 'specifics' path('specifics/<int:question_id>/', views.detail, name='detail'), ] polls/views.py from django.http import request from django.http.response import Http404 from .models import Question # from django.http import HttpResponse from django.template import loader # from django.shortcuts import render from django.shortcuts import get_object_or_404, render def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/detail.html', {'question': question}) # def detail(request, question_id): # question = get_object_or_404(Question, pk=question_id) # return render(request, 'polls/detail.html', {'question': question}) # template …
- 
        Connecting django app to postgres containerI'm having difficulty to connect my Django container app to my Postgres container. The docker compose statement for the Postgres app is as follows: version: '3' services: database: image: "postgres" # use latest official postgres version restart: unless-stopped env_file: - ./database.env # configure postgres networks: - djangonetwork ports: - "5433:5432" volumes: - database-data:/var/lib/postgresql/data/ # persist data even if container shuts down volumes: database-data: # named volumes can be managed easier using docker-compose networks: djangonetwork: driver: bridge The compose statement for the Django app is as follows: services: app: build: . container_name: app command: > bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" networks: - djangonetwork ports: - 10555:8000 environment: aws_access_key_id: ${aws_access_key_id} aws_secret_access_key: ${aws_secret_access_key} networks: djangonetwork: driver: bridge The difficulty emerges when performing the docker compose up statement. I have attempted a number of different POSTGRES_HOST values (note they are successfully retrieved from Amazon Secrets Manager). I receive the following log output: [+] Running 1/0 ⠿ Container app Created 0.0s Attaching to app app | /usr/local/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py:105: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "postgres" to address: Name or service not known app | …
- 
        How to redirect a wrong url with the same pattern that a user messed up in django, without javascriptassume the following: Your model has: Products.slug urls: path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'), views: products = Products.objects.get(id=id, slug=slug) Someone goes to /products/1/brazil-nuts/, and it goes to the right page. But then someone copy/pastes the url wrong to: /products/1/brazil-nu/ Then you get a DoesNotExist error... Now you could "fix" this by not forcing the slug=slug argument in your query, but then the url is incorrect, and people could link from /products/1/brazil-nu-sjfhkjfg-dfh, which is sloppy. So how would I redirect an incorrect url to the correct one with the same url structure as the correct one (only id and slug arguments), without relying on JavaScript's window.history.pushState(null, null, proper_url); every time the page loads? I've already tried making the same url pattern to redirect, but since django uses the first pattern match, it won't work no matter where you put the url in your list.
- 
        Adding edit photo page to django image gallery app using PythonNewbie...I have an image gallery app in Django that has an upload image page and sends that photo to a gallery page. Also, there's an edit photo page where I want to display the uploaded image and edit it, then submit the edited photo to the gallery page. How can I have the currently uploaded image show up on both the upload image and edit pages? views.py #uploads form for add image page(named addartifact) def addartifact(request): if request.method == 'GET': form = EditorForm() return render(request=request,template_name='addartifact.html', context={'form': form}) if request.method == 'POST': form = EditorForm(request.POST) if form.is_valid(): imgtitle = form.cleaned_data['imgtitle'] imgdesc = form.cleaned_data['imgdesc'] image = form.cleaned_data['image'] artifact = Artifact.objects.create(imgtitle=imgtitle, imgdesc=imgdesc, image=image) return HttpResponseRedirect(reverse('landingpage')) views.py #uploads image to page def image_upload_view(request): """Process images uploaded by users""" if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() # Get the current instance object to display in the template img_obj = form.instance return render(request, 'addartifact.html', {'form': form, 'img_obj': img_obj}) else: form = ImageForm() return render(request, 'addartifact.html', {'form': form}) forms.py class ImageForm(forms.ModelForm): """Form for the image model""" class Meta: model = Artifact fields = ('artifact_id', 'imgtitle', 'imgdesc', 'image') class EditorForm(forms.Form): imgtitle = forms.CharField(max_length=13, required=True, label=False, widget=forms.TextInput(attrs={'style': 'text-transform:lowercase;', 'placeholder': 'enter title'})) imgdesc = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'add …
- 
        Python/Django sorting a queryset by distance in REST frameworkCurrently, I am adding a field, 'distance', to a queryset after it's been created, and then returning it. However, I would like to sort the queryset by distance, if it's possible to annotate it. Currently, my model, GeoCache, has fields latitude and longitude as models.DecimalField(max_digits=15, decimal_places=10, null=True, blank=True). Using geopy, I can add distance to my queryset like this: user_location = (self.request.GET.get('latitude') , self.request.GET.get('longitude')) geocache_list = GeoCache.objects.all() for geocache in geocache_list: geocache.distance = geodesic(user_location, (geocache.latitude, geocache.longitude)).miles return geocache_list However, I would like to sort the queryset by distance, from lowest to greatest. However, when I try to annotate the search as such: geocache_list = GeoCache.objects.all().annotate(distance=geodesic(user_location, ('latitude', 'longitude')).miles) I get the error, "ValueError: could not convert string to float: 'latitude'" Is there a better way to annotate this so that I can sort by distance within the queryset?
- 
        How to update the data of a POST view that I have already updated with the same AJAX function?We used AJAX to launch a POST request with a set of data. We noticed that a piece of data was being sent incorrectly. After fixing it, we sent the request again but the web where we display the data is not updated, despite having checked that the request sends the data correctly. Could someone tell me how can I fix it please? This is my code: //ajax function to send graphs to backend $(document).ready(async function(){ await new Promise(r => setTimeout(r, 1500)); var canvas_elements=document.getElementsByClassName("chartjs-render-monitor") if (canvas_elements.length==2) { $('#bar-chart').addClass(function(){ const csrf_cookie=getCookie('csrftoken'); $.ajax({ url: "graphs/", type: "POST", data:{ type:$('#vot_type').val(), graphs:graphs_images(), }, beforeSend: function(xhr) { xhr.setRequestHeader("X-CSRFToken", csrf_cookie) }, failure: function(data){ console.log(error) } }).done(function(response){ console.log("Hecho") }); }); } }); We checked the console to see if the data was sent correctly, and as we can see, it sends the type and url of the graphs. console But when we check the web, it is not updated. web not being updated Thank you so much in advance.
- 
        How can I list all the solutions to a particular question and how do I make the respective URL for it in Django?I have two models, Question and Solution. One question can have many solutions but a solution can only have one question. Here they are: models.py class Question(models.Model): question_title = models.CharField(max_length = 100) question_description = models.TextField() question_tags = models.TextField() def __str__(self): return self.question_title class Solution(models.Model): user_profile = models.ForeignKey(UserProfile, on_delete = models.SET_NULL) question_id = models.ForeignKey(Question, on_delete = models.CASCADE, blank = False, null = True) solution = models.TextField() date_modified = models.DateTimeField(auto_now_add = True) def __str__(self): return "[SOL] " + self.question_id + "/" + self.user_profile Here's my views.py: class QuestionList(generics.GenericAPIView, mixins.ListModelMixin, mixins.CreateModelMixin): # Used to access all questions and adding one queryset = Question.objects.all() serializer_class = QuestionSerializer def get(self, request): return self.list(request) def post(self, request): return self.create(request) class QuestionDetails(generics.GenericAPIView, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin): queryset = Question.objects.all() serializer_class = QuestionSerializer lookup_field = 'id' def get_question(self, id): try: return Question.objects.get(id = id) except Question.DoesNotExist: raise Http404 def get(self, request, id): question = self.get_question(id) serializer = QuestionSerializer(question) return Response(serializer.data, status.HTTP_200_OK) def put(self, request, id): question = self.get_question(id) serializer = QuestionSerializer(question, data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_201_CREATED) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) def delete(self, request, id): question = self.get_object(id) question.delete() return Response(status = status.HTTP_204_NO_CONTENT) class SolutionList(generics.GenericAPIView, mixins.ListModelMixin,mixins.CreateModelMixin): # Empty because I'm still incredibly confused …
- 
        Django - How Do I Set A Default Value In A Form To Be The Current User?quick beginner Django question because I haven't been able to find an answer that directly solves what i'm after, or doesn't add in a bunch of overcomplicated functionality I don't need with its answer. I have a basic Blog setup, with a model for users and their associated posts, and a form for creating new posts. However all I want is for the "Author" field on the form to be automatically populated with the currently logged in user, rather than being a drop down list of all the registered users. My Model: class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255) site = models.CharField(max_length=255) def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('home') My Form: class PostForm(forms.ModelForm): class Meta: model=Post fields = ('title', 'author', 'category', 'site', 'body') widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'author': forms.Select(attrs={'class': 'form-control' ,'readonly': 'readonly'}), 'category': forms.Select(choices=choice_list,attrs={'class': 'form-control'}), 'site': forms.Select(choices=site_choice_list,attrs={'class': 'form-control'}), 'body': forms.Textarea(attrs={'class': 'form-control'}) } To reiterate, I simply want the 'author' field in the post to be read-only and populated with the current logged in user. Rather than the user being able to select from a list of users. Thank you in …
- 
        my images disappear in heroku app how can i solve itI hosted a web app, where a user can post images, but when user posted an image, the image disappear after 30 minutes or 1 hour and I don't what is happening I installed whitenoise correctly. help me solve this problem please. this is my settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] this is my models.py class Category(models.Model): name = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return self.name class Photo(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True) image = models.ImageField(null=False, blank=False,) description = models.TextField(null=True) def __str__(self): return self.description this is my installed apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.sites', 'itouch', #allauth 'allauth', 'allauth.account', 'allauth.socialaccount', #providers 'allauth.socialaccount.providers.facebook', 'bootstrap5', ] this my static settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIR = (os.path.join(BASE_DIR, 'static'),) STATICFILES_STORAGE = 'whitenoise.storage.CompressedMenifestStaticFilesStorage' STATICFILES_DIR = ( os.path.join(BASE_DIR, 'static'),) STATIC_URL = '/static/' MEDIA_URL ='/images/' STATICFILES_DIR = [ BASE_DIR / 'static' ] MEDIA_ROOT = BASE_DIR / 'static/images' STATIC_ROOT = BASE_DIR / 'staticfiles' this is my templates <div class="col-md-4"> <div class="card my-2"> <img class="image-thumbail" src="{{photo.image.url}}" alt="Card image cap">
- 
        how to set django setting path in docker container app?i'm inside docker container. and getting following error: File "./source/asgi.py", line 14, in <module> from notifications.sockets import routing File "./notifications/sockets/routing.py", line 3, in <module> from . import consumers File "./notifications/sockets/consumers.py", line 7, in <module> from projects.models import Project File "./projects/models.py", line 6, in <module> User = get_user_model() File "/usr/local/lib/python3.8/site-packages/django/contrib/auth/__init__.py", line 160, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 63, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting AUTH_USER_MODEL, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. where my asgi file code is here below: import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from notifications.sockets import routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'source.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns, ) ), }) i don't get it whats wrong here.. please help me out in solving this issue... thank you.
- 
        Problem to use @extend_schema over an @actoin in DRFhi I have a @extend_schema of drf_spectacular library in my code I need to use it over my @action to customize the detail in OpenAPI, but I get errors like that Internal Server Error: /api/schema/ Traceback (most recent call last): File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/asgiref/sync.py", line 482, in thread_handler raise exc_info[1] File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 38, in inner response = await get_response(request) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/django/core/handlers/base.py", line 233, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/asgiref/sync.py", line 444, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "/usr/lib/python3.9/asyncio/tasks.py", line 442, in wait_for return await fut File "/usr/lib/python3.9/concurrent/futures/thread.py", line 52, in run result = self.fn(*self.args, **self.kwargs) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/asgiref/sync.py", line 486, in thread_handler return func(*args, **kwargs) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/drf_spectacular/views.py", line 69, in get return self._get_schema_response(request) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/drf_spectacular/views.py", line 77, in _get_schema_response data=generator.get_schema(request=request, public=self.serve_public), File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/drf_spectacular/generators.py", line 262, in get_schema paths=self.parse(request, public), File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/drf_spectacular/generators.py", line 227, in parse assert isinstance(view.schema, AutoSchema), ( AssertionError: Incompatible AutoSchema …
- 
        background_task are not activated every 30 seconds as requestedI have a background task that should run every 30 seconds. The way I set it up is like this: from background_task import background from datetime import datetime import pytz @background() def notify_users(**kwargs): my_datetime = datetime.now(pytz.timezone('US/Eastern')) print ("at the moment its",my_datetime) and the activation: notify_users(repeat=30, repeat_until=None) The output is this: at the moment its 2022-01-02 15:08:25.571196-05:00 at the moment its 2022-01-02 15:08:55.896407-05:00 at the moment its 2022-01-02 15:09:56.408215-05:00 at the moment its 2022-01-02 15:10:56.871663-05:00 at the moment its 2022-01-02 15:11:57.327631-05:00 at the moment its 2022-01-02 15:12:57.857382-05:00 at the moment its 2022-01-02 15:13:28.135571-05:00 at the moment its 2022-01-02 15:14:28.551105-05:00 Note that its not 30 seconds, only the second round, why? what am I missing here?
- 
        Django sending emails and response to Vue/AxiosI am struggling to send emails from Vue3/Axios frontend through Django. in Vue3 I send my form fields using axios: <script lang="ts"> import axios from 'axios'; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; export default { name: "Contact", data() { return { name: '', email: '', phone: '', message: '' }; }, methods: { sendEmail() { axios .post("send_email/", { name: this.name, email: this.email, phone: this.phone, message: this.message, xstfCookieName: 'csrftoken', xsrfHeaderName: 'X-CSRFToken', headers: { 'X-CSRFToken': 'csrftoken', } }) .then((response) => { console.log(response); }) } } }; </script> I can see my fields in the request header without any problems. I could not manage to write a correct view sending email and response the request. def contactView(request): if (request.POST): try: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] name = form.cleaned_data['name'] from_email = form.cleaned_data['email'] message = form.cleaned_data['message'] print(subject) try: send_mail(subject, message, from_email, ['admin@example.com']) return HttpResponse(json.dumps({'response': 'Ok'}), content_type = "application/json") except BadHeaderError: return HttpResponse(json.dumps({'response': 'Ko', 'message': 'invalid header found'}), content_type = "application/json") except: return HttpResponse(json.dumps({'response': 'Ko', 'message': 'Cannot be sent'}), content_type = "application/json") else: return HttpResponse(json.dumps({'response': 'Ko', 'message': 'Cannot be sent'}), content_type = "application/json") Can you help me to fix this ? Thanks
- 
        my Procfile to deploy django-heroku isn't wrong but errors keep occureddjango-admin startproject minblog python manange.py startapp index and only one template used to test-deploy with Heroku working-tree MINBLOG minblog index minblog setting.py Pipfile requirements.txt git.init //minblog>Progfile web: gunicorn minblog.wsgi --log-file - //minblog>minblog>setting.py import os import django_heroku DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com'] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', ...] # Activate Django-Heroku. django_heroku.settings(locals()) and install gunicorn in virtual entirment ~/Desktop/minblog $pipenv shell $pip install gunicorn whitenoise django-heroku and i still stuck in this error $ heroku ps:scale web=1 Scaling dynos... ! ! Couldn't find that process type (web). which part did i miss?
- 
        Django Python how to implement my custom birth date function in views?I write this python function for calculate age. def age(birthdate): today = date.today() age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day)) return age result: >>> print(age(date(1980, 1, 1))) 42 here is my code: models.py class CalculateAge(models.Model): age = models.IntegerField(max_length=100) date_of_birth = models.DateField() user only pick the date of birth and I want age will be automatically calculate when submitting forms. views.py def CalculateAge(request): if request.method == "POST": patient_from = AddPatientFrom(request.POST or None) if patient_from.is_valid(): patient_from.save() how to implement this age function in my views.py and models.py? I tried this in my views.py but didn't work. if patient_from.is_valid(): pick_date = request.POST['date_of_birth'] find_age = age(date(pick_date)) print(find_age) getting this error: TypeError at /add-patient/ an integer is required (got type str)
- 
        Same AJAX call for multiple button on clicks on the same pageI'm working on a project with django. I have multiple buttons on a page that I want to, upon clicking, be able to get the value of without the page refreshing. With the below code, it does want I want except that it will only return the value of the first button on the page regardless of which button I click. Please note that I have 0 experience with JS which is why I'm struggling. I've looked at many, many threads and I can't figure it out. $(document).on('click', '.testing', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "select" %}', data: { value: $('.testing').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), // action: 'post', success : function(json) { console.log("success"); // another sanity check console.log($('.testing').val()) }, }})}) {% extends "recipe_site/base.html" %} {% load static %} {% block content %} {% block extrascripts %} <script type="text/javascript" src="{% static 'ingredients/ingredients.js' %}"></script> {% endblock extrascripts %} {% for ingredient in ingredients %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <h2>{{ ingredient.group }}</h2> </div> <button id="{{ ingredient.pk }}" class="testing" value="{{ ingredient.food_name }}">{{ ingredient.food_name }}</button> </div> </article> {% endfor %}
- 
        How to configure django-channels to make docker container?I have a django app which works with django channels. Now the problem is everything was working fine without docker containerizing thing. Now I have made the docker container of the app but sockets are not working.. but django CRUD with apis working fine. or we can say gunicorn service is running but daphne service isn't. In entrypoint.sh : #!/bin/sh python manage.py migrate --no-input python manage.py collectstatic --no-input gunicorn source.wsgi:application --bind 0.0.0.0:8000 daphne source.asgi:application --bind 0.0.0.0:8001 settings.py : CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('redis-notif2', 6379)], }, }, } on browser i'm getting the following error: Firefox can’t establish a connection to the server at ws://xx.xx.xxx.xxx:8001/ws/project/admin/. reconnecting-websocket-mjs.js:516
- 
        Error deleting AWS S3 objects from Django Web AppI'm having the following error when I try to delete S3 files from my Python/Django Webapp. ClientError at /eq83/deletephoto An error occurred (AccessDenied) when calling the DeleteObject operation: Access Denied I have no problem viewing or uploading files. Some details on the bucket permissions All block public access boxes are unchecked. Bucket policy is empty and says No policy to display. Access control List(ACL) has all the boxes checked for bucket owner and the rest are unchecked. This is the Cross-origin resource sharing (CORS) [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "POST", "PUT", "DELETE" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] Some details on my application Below is an excerpt from my settings.py file. I have blocked out the secret key and omitted TEMPLATES, MIDDLEWARE, and some INSTALLED_APPS import os import dotenv dotenv.read_dotenv() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXX' DEBUG = True ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ 'tracker.apps.TrackerConfig', ... 'storages' ] WSGI_APPLICATION = 'tracker_django.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR,'tracker', 'static')] DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY', '') AWS_SECRET_ACCESS_KEY …
- 
        Show all record in DjangoI have SQL Server database and I have a table, I've created a stored procedure to retrieve all records from the table and tested it. The stored procedure works properly. However, when I called it in my Django program and tried to write all records on an html page, but it shows the last record only. Here is the loginsdata.html {% block content %} {% for row in rows %} <p> <h3>Name: {{row.name}}</h3> <h3>Email: {{row.email}}</h3> <h3>Username: {{row.userName}}</h3> <h3>Password: {{row.password}}</h3> </p> </br> {% endfor %} {% endblock content %} And here is the views.py from django.shortcuts import render from django.http import HttpResponse from django.db import connection import pyodbc def readLogin(request): command = 'EXEC GetLogin \'\'' cursor = connection.cursor() cursor.execute(command) strHtml = '' while True: row = cursor.fetchone() if not row: break userName = row[0] password = row[1] name = row[2] email = row[3] rows = [] rows.append({'userName': userName, 'password': password, 'name': name, 'email': email}) cursor.close() return render(request, 'login/loginsdata.html', {'rows': rows})
- 
        Djago how to prevent to accept future date?I added this validation in my froms.py for prevent to accept future date. But I am not undersating why it's not working and forms still now submitting with future date. here is my code: import datetime class AddPatientFrom(forms.ModelForm): date_of_birth = forms.DateField(widget=forms.DateInput(attrs={'class': 'form-control','type':'date'}),required=True) class Meta: model = Patient fields = ['date_of_birth'] def clean_date(self): date = self.cleaned_data['date_of_birth'] if date < datetime.date.today(): raise forms.ValidationError("The date cannot be in the past!") return date I also want to know how to disable to pick future date from Django default html calendar?