Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to create API from django rest_framework
Can anyone please help me? I am not able to create API with GET POST PUT DELETE methods. Also when I go to this url: "http://127.0.0.1:8000/api/packages/" I cant see Django default API view. My users API is working fine with all methods but not packages. Models.py class Customer(models.Model): user = models.OneToOneField( User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50, null=True) phone = models.CharField(max_length= 200, null = True) dob = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Packages(models.Model): STATUS = ( ('Drafts', 'Drafts'), ('Published', 'Published'), ) name = models.CharField(max_length=50, null=True) details = models.CharField(max_length=200, null=True) price = models.PositiveIntegerField() days = models.CharField(max_length=10, null=True) nights = models.CharField(max_length=10, null=True) image = models.ImageField(null=True, blank=True) status = models.CharField(max_length=200, null=True, choices=STATUS) def __str__(self): return self.name Views.py @csrf_exempt def packagesAPI(request, id=0): if request.method == 'GET': packages = Packages.objects.all() packages_serializer = PackagesSerializer(packages, many=True) return JsonResponse(packages_serializer.data,safe=False) elif request.method == 'POST': packages_data = JSONParser().parse(request) packages_serializer = PackagesSerializer(data = packages_data) if packages_serializer.is_valid(): packages_serializer.save() return JsonResponse("Added Successfully",safe=False) return JsonResponse("Failed to Add",safe=False) elif request.method == 'PUT': packages_data = JSONParser().parse(request) packages = Packages.objects.get(package_id = packages_data['package_id']) packages_serializer = PackagesSerializer(packages,data = packages_data) if packages_serializer.is_valid(): packages_serializer.save() return JsonResponse("Updated Successfully",safe=False) return JsonResponse("Failed to Update") elif request.method == 'DELETE': packages = Packages.objects.get(package_id=id) packages.delete() return JsonResponse("Deleted Successfully",safe=False) @csrf_exempt def SaveFile(request): file = requestFILES['file'] file_name … -
Trying to connect Docker + Django to Postgres - could not translate host name "db" to address: Name or service not know
I'm trying to Dockerize a Django + Postgres project following this tutorial: https://docs.docker.com/samples/django/ When I run docker-compose up I get: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known Dockerfile # syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ docker-compose.yml version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST'), 'PORT': 5432, } } -
Need to add a search functionality on Django class based view
I have a search function on a function based view that works fine. This is the function based view code: def BlogList(request): blogs = Blog.objects.all() if request.method == 'GET': search = request.GET.get('search', '') blogs = Blog.objects.filter(blog_title__icontains=search) return render(request, 'App_Blog/blog_list.html', context={'search':search, 'blogs':blogs}) But now I want to replace that function based view by implementing it on this class based view. class BlogList(ListView): context_object_name = 'blogs' model = Blog template_name = 'App_Blog/blog_list.html' This is my models.py: class Blog(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author') blog_title = models.CharField(max_length=264, verbose_name="Put a Title") slug = models.SlugField(max_length=264, unique=True) blog_content = models.TextField(verbose_name="What is on your mind?") blog_image = models.ImageField(upload_to='blog_images', verbose_name="Image") publish_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) class Meta: ordering = ['-publish_date',] def __str__(self): return self.blog_title html part for search function: <form class="form-inline ml-auto" method="GET"> <input class="form-control mr-sm-2" type="text" name="search" placeholder="Search the topic"> <button class="btn btn-success" type="submit">Search</button> </form> As I am a newbie, I have tried different solutions but not getting it through. I'll be glad if someone help me on this. -
How to return raw sql queries as json objects?(Django)
I am using the following function to display the sql join query as json: def toggle_query(request,id): obj = DibbsSpiderDibbsMatchedProductFieldsDuplicate.objects.raw('''SELECT * FROM dibbs_spider_solicitation JOIN dibbs_spider_dibbs_matched_product_fields_duplicate ON dibbs_spider_solicitation.nsn = {nsn};'''.format(nsn=id)) context = serializers.serialize('json',obj) return JsonResponse(context,safe=False) This displays data as : "[{\"model\": \"dibbs_spider.dibbsspiderdibbsmatchedproductfieldsduplicate\", \"pk\": 39, \"fields\": {\"nsn\": \"1650011162908\", \"nsn2\": \"6550015746831\", \"cage\": \"34807\", \"part_number\": \"6903A-J\", \"company_name\": null, \"supplier\": \"GraingerOM\", \"cost\": \"18.16\", \"list_price\": \"19.12\", \"gsa_price\": null, \"hash\": \"665\", \"nomenclature\": \"HOUSING, CONTROL MOD\", \"technical_documents\": \"Tech Docs\", \"solicitation\": \"SPE2DS22T1575\", \"status\": \"Awarded \", \"purchase_request\": \"0091648844\\nQty: 5\", \"issued\": \"2021-12-09\", \"return_by\": \"2021-12-14\", \"file\": \"https://dibbs2.bsm.dla.mil/Downloads/RFQ/5/SPE2DS22T1575.PDF\", \"vendor_part_number\": \"269P71\", \"manufacturer_name\": \"LAMOTTE\", \"product_name\": \"Reagent Tablet Type 0 to 4 ppm Range\", \"unit\": \"EA\"}}, {\"model\": How to remove the \ symbol which is not the part of the data here ? -
Python Billiard cannot find project module on restarting Celery worker process
Running Python 2.7, Celery 3.1.23, Billiard 3.3.0.23. I'm getting the Celery workers crashing on any stack trace. Inspecting the workers using celery worker from the shell gives this stack: [2022-01-03 03:39:17,822: ERROR/MainProcess] Unrecoverable error: ImportError('No module named <my project>',) Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/celery/worker/__init__.py", line 206, in start self.blueprint.start(self) File "/usr/local/lib/python2.7/site-packages/celery/bootsteps.py", line 123, in start step.start(parent) File "/usr/local/lib/python2.7/site-packages/celery/bootsteps.py", line 374, in start return self.obj.start() File "/usr/local/lib/python2.7/site-packages/celery/concurrency/base.py", line 131, in start self.on_start() File "/usr/local/lib/python2.7/site-packages/celery/concurrency/prefork.py", line 119, in on_start **self.options) File "/usr/local/lib/python2.7/site-packages/celery/concurrency/asynpool.py", line 401, in __init__ super(AsynPool, self).__init__(processes, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/billiard/pool.py", line 972, in __init__ self._create_worker_process(i) File "/usr/local/lib/python2.7/site-packages/celery/concurrency/asynpool.py", line 415, in _create_worker_process return super(AsynPool, self)._create_worker_process(i) File "/usr/local/lib/python2.7/site-packages/billiard/pool.py", line 1068, in _create_worker_process w.start() File "/usr/local/lib/python2.7/site-packages/billiard/process.py", line 137, in start self._popen = Popen(self) File "/usr/local/lib/python2.7/site-packages/billiard/forking.py", line 91, in __init__ _Django_old_layout_hack__save() File "/usr/local/lib/python2.7/site-packages/billiard/forking.py", line 379, in _Django_old_layout_hack__save project = __import__(project_name) ImportError: No module named <my_project> It looks like Billiard is unable to load in the project module at all. However, you can run a shell on the celery worker by calling celery shell, and running forking._Django_old_layout_hack__save() works just fine. -
A Difficult Object Query
So, I have an e-commerce website that I am building. When the customer clicks "place order", the site creates the order, and the database updates totally fine. The problem lies in displaying the order summary. IF the customer has ordered from the company in the past, that order is stored in the database along with the new one. The site then throws the error "2 objects returned" when I try to access it through the foreign key that relates the order table to the User table. The reason for this is obvious to me so I added a datetime field and set the auto_now_add attribute to TRUE. The problem I'm having is selecting the latest order for that particular customer. Is there a way to use something like this? user = request.user Order.objects.filter(Customer=user).date_placed.latest() The fact that filter() returns a set makes me think that sytax won't execute properly. Maybe with a for loop inside a function that takes User as a parameter? I have no idea how to approach this one and thought I'd reach out. Thanks you guys. View for the request: def orderSummary(request): context = {} if request.user.is_authenticated: owner = request.user.id user = request.user cart = Cart.objects.get(cart_owner=owner) held_items … -
Struggling to display images using django
I am creating a blogging website using django framework and so I am struggling to display images on dynamic pages. Here is my code: models.py: class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'blog_posts') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now=True) status = models.IntegerField(choices=Status, default=0) cover_image = models.ImageField() captioned_image = models.ImageField() caption = models.CharField(max_length=300) class Meta: ordering = ['-created_on'] def __str__(self): return self.title views.py: def post(request, slug): post = Post.objects.get(slug = slug) context = {'post': post} return render(request, template_name='blogger/pages.html', context=context) within my html: <img class="img-fluid" src="{{post.cover_image.url}}" /> I am unsure what I am doing incorrect here as text is correctly displaying in my code dynamically, just unable to work with images. -
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.py
I 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 images
I 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 CreateView
I'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 container
I'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 javascript
assume 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 Python
Newbie...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 framework
Currently, 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 it
I 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 DRF
hi 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 requested
I 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/Axios
I 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