Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting total in cart
Guys in my cart part of my project I have registered two people and first is working good, but the second one is getting first user's total sum and it is not changing when i add new product or delete other product -
How can i take user input validate the input using values in a dictionary and then add the corresponding value to the querystring in the API
I am building a web app that takes users' input and then returns the result using Google Finance API. My problem is I do not know how to write this in my views.py file that way when a user types in a currency. someapp/coins.py coins = [ {"Ethereum": "ETH-USD"}, {"Bitcoin": "BIT-USD"}, {"Litcoin": "LIT-USD"}, {"Solona": "SOL-USD"}, {"Binance": "BNB-USD"}, {"Ripple": "XRP-USD"}, {"XRP": "XRP-USD"}, {"Cardano": "ADA-USD"}, {"Dogeoin": "DOGE-USD"}, {"Chainlink": "LINK-USD"} ] this is the file that has the tickers needed to get results from the google finance api. So I am trying to check the users input with one of the keys in this list and then add the value which is the ticker needed for the search api to the querystring used in the the GET request. someapp/views.py from django.shortcuts import render import requests from django.views import generic from django.views.generic import TemplateView from django.http import HttpResponse from coins import coins # Create your views here. def index(request): return render(request, 'index.html') def news(request): if request.method == 'POST': crypto = 'POST' if crypto == coins[0:]: querystring.append() # not sure if this is the right thing to do else: pass url = "https://google-finance4.p.rapidapi.com/ticker/" **querystring = {"t":"ETH-USD","hl":"en","gl":"US"}** headers = { "X-RapidAPI-Key": "31c5541e87msh0684494d7f7396fp117984jsn574856ff6d0c", "X-RapidAPI-Host": "google-finance4.p.rapidapi.com" } response … -
Django celery task repeats every hour, it should be executed only once per day
The course_message_schedule_task runs every day at 04:00:00. In it, we register the course_message_send_task to run at 10:00:00 every day. However, if you look at the log below, course_message_send_task repeats every hour from 04:00:00 to 10:00:00. (businessletter_send_task is being repeated in the same way.) It should be run once every day, I don't know why this task is repeating. settings # ... settings.CELERYBEAT_SCHEDULE.update( { "send-emon-data-task": { "task": "klms.emon_api_task.send_emon_data_task", "schedule": crontab(hour="*", minute="0"), "kwargs": {}, }, "course-message-schedule-task": { "task": "klms.tasks.course_message_schedule_task", "schedule": crontab(hour="4", minute="0"), "kwargs": {}, }, "create-coursereport-task": { "task": "klms.tasks.create_coursereport_task", "schedule": crontab(hour="5", minute="0"), "kwargs": {}, }, "businessletter-schedule-task": { "task": "klms.tasks.businessletter_schedule_task", "schedule": crontab(hour="6", minute="0"), "kwargs": {}, }, } ) # ... tasks @shared_task(base=LoggedPersistOnFailureTask, default_retry_delay=30) def course_message_send_task(): """ today's messages """ # default 10:00:00 time_part = settings.COURSE_MESSAGE_SENDING_SCHEDULE_TIME.split(":") schedule_time = localtime().replace( hour=int(time_part[0]), minute=int(time_part[1]), second=int(time_part[2]), microsecond=0, ) # filter ids = list( MessageService.objects.filter(schedule=schedule_time) .exclude( status__isnull=False, ) .values_list("id", flat=True) ) # send! MessageService.status_handler(ids) @shared_task(base=LoggedPersistOnFailureTask, default_retry_delay=30) def course_message_schedule_task(): """ schedule course messages """ enrollmentinfo = ( EnrollmentInfo.objects.message_context() .filter( # 학습 시작일, n주차, 종료일, 종료 다음날 Q(days_from_study_start=1) | Q(ordinal_in_week=1) | Q(days_to_study_end__in=[0, -1]), # 종료되기 전 과정 days_to_study_end__gt=-1, ) .exclude(email_notification=False, text_notification=False) .distinct() ) messages = [] # default 10:00:00 time_part = settings.COURSE_MESSAGE_SENDING_SCHEDULE_TIME.split(":") schedule_time = localtime().replace( hour=int(time_part[0]), minute=int(time_part[1]), second=int(time_part[2]), microsecond=0, ) for … -
f string changing into multiple variable stiring
params = {"id": f'{[product.id,product2.id]}'} currently output of params is : {'id': "('5', '6')"} but I would like to change it so that it can be ids can be used as /?id=5,6 in a parameter of a url. I think this would be currently used as /?id=('5','6'). How would I change this as such. -
django form not saving to database(no error message)
First of all, I apologize for using a translator because I am not familiar with English. My Views.py def my_create_view(request): if "reg" in request.method == 'POST': first_form = FirstRegForm(request.POST, prefix='firstform') second_form = SecondRegForm(request.POST, prefix='secondform') if all([first_form.is_valid(), second_form.is_valid()]): form = first_form.save(commit=False) form.created_name = request.user.user_name form.save() formm = second_form.save(commit=False) formm.shop_seq = form formm.save() return redirect('someview') else: first_form = FirstRegForm(prefix='store') second_form = SecondRegForm(prefix='input') return render(request, 'app/template.html', {'first_form': first_form, 'second_form': second_form}) My Models.py from django.db.models import Max class My_user(AbstractBaseUser): shop_seq = models.ForeignKey('My_shop', null=True, blank=True, on_delete=models.SET_NULL, db_column="shop_seq") user_name = models.CharField(max_length=50) class My_shop(models.Model): shop_seq = models.CharField(primary_key=True, editable=False, max_length=5) shop_name = models.CharField(max_length=20, null=True) shop_code = models.CharField(max_length=15, null=True, unique=True) shop_address = models.CharField(max_length=40, null=True) shop_tel = models.CharField(max_length=20, null=True) created_name = models.CharField(max_length=100, null=True) def save(self, **kwargs): if not self.shop_seq: max = Rate.objects.aggregate(shop_seq_max=Max('shop_seq'))['shop_seq_max'] + 1 self.shop_seq = "{:05d}".format(max if max is not None else 1) super().save(*kwargs) class My_model(models.Model): model_id = models.BigAutoField(primary_key=True) my_field = models.CharField(max_length=20, null=True) some_field = models.CharField(max_length=20, null=True) shop_seq = models.ForeignKey('My_shop', on_delete=models.SET_NULL, null=True, db_column="shop_seq", related_name="shop_model") My Forms.py class FirstRegForm(forms.ModelForm): class Meta: model = My_shop fields = ('shop_name', 'shop_code', 'shop_address', 'shop_tel',) class SecondRegForm(forms.ModelForm): class Meta: model = My_model fields = ('my_field', 'some_field',) My Template.py <form method="post">{% csrf_token %} {{ first_form.shop_name }} {{ first_form.shop_code }} {{ first_form.shop_address }} {{ first_form.shop_tel }} {{ … -
How to add another chart in Django Plotly Dash app?
So, I have this existing code that generates number of data and updating Realtime. Is it possible to create a new chart like another scatter in the same file or app? I just started using Plotly dash, I'm familiarizing it. app = DjangoDash('SimpleExample') app.layout = html.Div([ # html.H1('Square Root Slider Graph'), dcc.Graph(id='slider-graph', animate=True, style={"color": "#15803D", 'color': '#000000'}), dcc.Interval( id='interval-component', interval=1*2000, # in milliseconds n_intervals=0 ) ]) @app.callback( Output('slider-graph', 'figure'), [Input('interval-component', 'n_intervals')]) def display_value(n_intervals): data = {} now = datetime.now() data["temperature"] = random.randint(23, 25) data["tss"] = random.randint(5, 8) data["vss"] = random.randint(1, 4) data["bod"] = random.randint(1, 7) data["doc"] = random.randint(8, 13) data["cod"] = random.randint(5, 12) data["ph"] = random.randint(2, 13) data["turbidity"] = random.randint(1, 5) data["conductivity"] = random.randint(1, 7) date = now.strftime("%Y/%m/%d %H:%M:%S") gg = list(range(0, len(data))) x = gg y = list(data.values()) graph = go.Scatter( x=x, y=y, # name='Manipulate Graph' ) layout = go.Layout( paper_bgcolor='#ffffff', plot_bgcolor='rgba(0,0,0,0)', xaxis=dict(range=[min(x), max(x)]), yaxis=dict(range=[min(y), max(y)]), font=dict(color='black'), ) return {'data': [graph], 'layout': layout} -
Refresh a page without reloading with Django
I'm making a system to detect presence by QR Code with Django, and I need a way to display a image and text when a QR Code is detected without having to reaload the page, i saw something about HTMX but i couldn't do much with it. There isn't much in the internet about using a if statement to do this. views.py from datetime import datetime from django.http import JsonResponse, StreamingHttpResponse from django.shortcuts import render import cv2 import numpy as np from pyzbar.pyzbar import decode from django.views.decorators import gzip from .models import * def camera_feed(request): stream = CameraStreamingWidget() frames = stream.get_frames() return StreamingHttpResponse(frames, content_type='multipart/x-mixed-replace; boundary=frame') class CameraStreamingWidget: def __init__(self): self.camera = cv2.VideoCapture(int(os.environ.get('CAMERA'))) self.media_path = os.path.join(os.getcwd(), "media", "images") # create "media/images" folder if doesn't exist if not self.media_path: os.mkdir(self.media_path) def get_frames(self): while True: # Capture frame-by-frame success, frame = self.camera.read() if not success: break else: ret, buffer = cv2.imencode('.jpg', frame) # Add text on top of the barcode if there is a barcode in the stream using opencv # convert camera frame to numpy array color_image = np.asanyarray(frame) # decode numpy array to check if there is a barcode in color_image # you can add a custom check here to verify … -
FileNotFound error when trying to download a file in django website
in my index.html I create a link to download a file <ul> {% for fil in listFiles %} <li><a href="{{ fil.csv_file.url }}" download class="btn btn-dark float-right"> {{ fil.csv_file.name }} </a></li> {% endfor %} </ul> the listFiles object is generated from this model from django.db import models from django.conf import settings class CsvDFile(models.Model): csv_file = models.FileField() file_path = models.TextField(max_length=200) userID = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) In the html page the url is like this <li><a href="/uploads/test.csv" download class="btn btn-dark float-right"> test.csv </a></li> However, when I click on it I get this error Not Found: /uploads/test.csv I checked the folder and the file is in there and the folder 'uploads' is inside my app directory Also in settings.py I set MEDIA_URL = 'uploads/' and MEDAI_ROOT = os.path.join(BASE_DIR, 'myapp/uploads') And my urls.py looks like this from django.conf import settings from django.conf.urls.static import static urlpatterns = [..My views..] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_URL) I don't know why it's not recognizing the file -
Django, render with link or remove template dirs when render in view
hai i am newbie in django and sorry for grammar mistake first i have some project to upload file extension .html to AWS S3, so in views.py i want to render a link i've already uploaded to AWS S3. ex: render(request, 'somelink.com', context) , it possible? or any other solution? and also i want to send context parameters why i not using media_url upload to local? cause i have limited disk, and other problem when i do production i cant load media_url, ignore this case, cause i already try many solution -
How do i install exiftool on heroku
i have tried the buildpack but non worked. i got these error when trying to install https://github.com/velizarn/heroku-buildpack-exiftool Installing exiftool 11.36 Fetching https://123456.mycdn.org/downl/Image-ExifTool-11.36.tar.gz gzip: stdin: unexpected end of file tar: Child returned status 1 tar: Error is not recoverable: exiting now ! Push rejected, failed to compile exiftool app. ! Push failed please can someone assist me. my django needs exiftool before it can work. -
get list of all folders in firebase storage using python
i'm using django app and firebase-admin and i have a files and sub folders(nested folders) as shown in image each folder has its own files and folders. i want to get a List of all folders and files inside each root folder , my code is : service_account_key = 'mysak.json' cred = firebase_admin.credentials.Certificate(service_account_key) default_app = firebase_admin.initialize_app(cred, { 'storageBucket': 'myBucketUrl' }) bucket = storage.bucket() blob = list(bucket.list_blobs()) #this is returning all objects and files in storage not for the folder i want for example i want all files in first_stage/math so i can get a url for each file i have also read the docs about firebase storage and there is no such a method -
How can I serialize None from db to empyt object?
I have the following models: class ContentUpload(BaseModel): ... status = models.ForeignKey(CourseStatus, on_delete=models.CASCADE, related_name="content_status", null=True, blank = True) class CourseStatus(BaseModel): status_name = models.CharField(max_length=250) slug = models.SlugField() def save(self, *args, **kwargs): self.slug = slugify(self.status_name) super(CourseStatus, self).save(*args, **kwargs) def __str__(self): return str(self.status_name) The following serializers: class CourseStatusListSerializers(serializers.ModelSerializer): class Meta: model = CourseStatus fields = ('id', 'status_name', 'slug') def get_status(self, obj): return CourseStatusListSerializers(obj.status, context={"request": self.context['request']}).data When the ContentUpload.status is None it returns the following: "status":{"status_name":"","slug":""} My question is that how can I do it to give back an empty object? What is your best practice for this? "status":{} -
django template for loop if nothing found for specific hostname create a blank cell
I am aggregating multiple outputs from models into the same table. So I am looking for a hostname_id, which ties the models together, and then displaying the output. The problem is there may not be data to display which throws off the alignment of the table so I need to create blank cells. {% for y in cpuAverageReport %} {% if x.id == y.hostName_id %} <td>{{ y.average | floatformat:0}}%</td> <td>{{ y.maximum | floatformat:0}}%</td> {% endif %} {% endfor %} So if, at the end of the loop, the if argument is never matched I want to create two blank cells. I tried using {% with var="something" %} to tag when the if argument is matched but the {% endwith %} tag must be before the endif tag rendering it useless... -
Import "taggit.managers" could not be resolved
Im currently learning django with the book "Django 2" by Antonio Melé. I got an error when I import "from taggit.managers import TaggableManager". I already install django-taggit and django-extensions. I also already added 'taggit' to INSTALLED_APPS. Here is my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog.apps.BlogConfig', 'taggit', My models.py (There are more classes but I put the one that im working on): from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from taggit.managers import TaggableManager class Post (models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=150) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') class Meta: ordering = ('-publish',) def __str__(self): return self.title objects = models.Manager() published = PublishedManager() def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) tags = TaggableManager() Image of the error, just in case I ran python manage.py shell and after the following: from blog.models import Post post = Post.objects.get(id=1) post.tag.add('post1', 'blogpost', 'tag1') post.tags.all() And the tags were added successfuly. -
Raise_exception not working with token base authentication
I'm trying to run my tests on status codes while i'm not providing token on POST request So viewset looking like this: class TopicViewSet(viewsets.ModelViewSet): serializer_class = TopicSerializer permission_classes = (IsOwnerOrReadOnly, ) pagination_class = TopicPagination def get_queryset(self): queryset = Topic.objects.all().select_related( 'owner', ) return queryset Permission class i'm using: class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user Test itself: @pytest.mark.django_db def test_topic_post_method_is_not_allowed_unauthenticated_user(api_client, topics_url): response = api_client.post(topics_url, data={'name': 'hello', 'slug': 'hello'}) assert response.status_code == 401 So all i want is just a simple response like: { "detail": "Authentication credentials were not provided." } But i'm getting html django generated page(screenshot from Postman): -
where should i put the instance in django?
I am modifying a table with stored procedures, I made an instance but I need to call it inside the request, where should I put the instance? def modificartarea(request, id): tarea = get_object_or_404(Tarea, id=id) data = { 'tarea': CrearTareaForm(instance=tarea) } if request.method=="POST": if request.POST.get('nombre') and request.POST.get('descripcion') and request.POST.get('inicio') and request.POST.get('termino') and request.POST.get('repetible') and request.POST.get('activo') and request.POST.get('estado') and request.POST.get('creador') and request.POST.get('tarea_anterior'): tareaupdate= Tarea() tareaupdate.nombre=request.POST.get('nombre') tareaupdate.descripcion=request.POST.get('descripcion') tareaupdate.inicio=request.POST.get('inicio') tareaupdate.termino=request.POST.get('termino') tareaupdate.repetible=request.POST.get('repetible') tareaupdate.activo=request.POST.get('activo') tareaupdate.estado=EstadoTarea.objects.get(pk=(request.POST.get('estado'))) tareaupdate.creador=Empleado.objects.get(rut=(request.POST.get('creador'))) tareaupdate.tarea_anterior=Tarea(pk=(request.POST.get('tarea_anterior'))) cursor=connection.cursor() cursor.execute("call SP_modificar_tarea('"+tareaupdate.nombre+"','"+tareaupdate.descripcion+"', '"+tareaupdate.inicio+"', '"+tareaupdate.termino+"', '"+tareaupdate.repetible+"', '"+tareaupdate.activo+"', '"+str(tareaupdate.estado.id)+"', '"+str(tareaupdate.creador.rut)+"', '"+str(tareaupdate.tarea_anterior.id)+"')") messages.success(request, "La tarea "+tareaupdate.nombre+" se edito correctamente ") return render(request, 'app/modificartarea.html', data) else: return render(request, 'app/modificartarea.html', data) -
Is there a way in the django views to make a css transform?
I apologize I am new to Django and trying to wrap my head around some stuff at the moment. I currently have a page that has a central card that when a button is clicked it flips the card all through CSS. I am now also redirecting the page back to its self in views.py is there a way to have the views redirect to the back of the card not the front. I know I could use java-script to achieve this but was wondering if there was a way with out. View.py: from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.views import View from django.contrib.auth.forms import UserCreationForm class login_register(View): def get(self, request): form = UserCreationForm() if "sign-in" in request.GET: username = request.GET.get("username") password = request.GET.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('/admin') else: messages.info(request, 'Login attempt failed.') return redirect('login_register') return render(request, 'index.html', {'form': form}) def post(self, request): if "sign-up" in request.POST: form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) messages.success(request, 'Account has been created succesfully') return redirect('login_register') else: messages.error(request, form.errors) return redirect('login_register') return render(request, 'index.html') HTML … -
how do i create one room for two users in Django channels
so I'm building a listing website that will have a messaging feature, the way i have built the create room function when a user is initiating a conversation is that it's going to collect the current user as a and the listing agent as b then add their IDs, how do i fetch the room for the two users without creating new room again when the agent is the one initiating the conversation. a = str(request.user.id_user) b = str(listing.agent.id_user) room = a[0:13] + "-" + b[0:13] if request.user.is_realtor: if not Room.objects.filter(room_name=room).exists(): Room.objects.create(room_name=room, user1 = request.user, user2 = listing.agent) room = Room.objects.get(room_name=room) else: if not Room.objects.filter(room_name=room).exists(): Room.objects.create(room_name=room, user1 = listing.agent, user2 = request.user) room = Room.objects.get(room_name=room) -
May anyone help me with this problem? Whenever I going to deploy my Django project on heroku.com, I am getting this error. How should I fix it?
(myenv) D:\EventManagementProject\Event_Management_System>git push heroku master Enumerating objects: 352, done. Counting objects: 100% (352/352), done. Delta compression using up to 4 threads Compressing objects: 100% (349/349), done. Writing objects: 100% (352/352), 10.81 MiB | 96.00 KiB/s, done. Total 352 (delta 46), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-22 stack remote: -----> Using buildpack: heroku/python remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 1ca3c9649e1582c82164c7773829c2dad2837277 remote: ! remote: ! We have detected that you have triggered a build from source code with version 1ca3c9649e1582c82164c7773829c2dad2837277 remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku <branchname>:main remote: ! remote: ! This article goes into details on the behavior: remote: ! https://devcenter.heroku.com/articles/duplicate-build-version remote: remote: Verifying deploy... remote: remote: ! Push rejected to eventmanagementbydipu. remote: To https://git.heroku.com/eventmanagementbydipu.git ! [remote rejected] master … -
AttributeError: 'RegisterPatientView' object has no attribute 'object'
When ever I am running the project and try to create register the patient or doctor it is showing this error. error and below it is showing error in return HttpResponseRedirect(self.get_success_url()) and if I try to visit login page it is not rendering. Below is my code. views.py class RegisterPatientView(CreateView): """ Provides the ability to register as a Patient. """ model = User form_class = PatientRegistrationForm template_name = 'accounts/patient/register.html' success_url = '/' extra_context = { 'title': 'Register' } def dispatch(self, request, *args, **kwargs): if self.request.user.is_authenticated: return HttpResponseRedirect(self.get_success_url()) return super().dispatch(self.request, *args, **kwargs) def post(self, request, *args, **kwargs): form = self.form_class(data=request.POST) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get("password1") user.set_password(password) user.save() return redirect('accounts:login') else: return render(request, 'accounts/patient/register.html', {'form': form}) urls.py from django.urls import path from .views import * from appointment.views import * app_name = "accounts" urlpatterns = [ path('patient/register', RegisterPatientView.as_view(), name='patient-register'), path('patient/profile/update/', EditPatientProfileView.as_view(), name='patient-profile-update'), path('doctor/register', RegisterDoctorView.as_view(), name='doctor-register'), path('doctor/profile/update/', EditDoctorProfileView.as_view(), name='doctor-profile-update'), path('login', LoginView.as_view(), name='login'), path('logout', LogoutView.as_view(), name='logout'), ] models.py from accounts.managers import UserManager GENDER_CHOICES = ( ('male', 'Male'), ('female', 'Female')) class User(AbstractUser): username = None role = models.CharField(max_length=12, error_messages={ 'required': "Role must be provided" }) gender = models.CharField(max_length=10, blank=True, null=True, default="") email = models.EmailField(unique=True, blank=False, error_messages={ 'unique': "A user with that email already … -
ModuleNotFoundError: No module named 'django_heroku' even after installation
I set up a Django project in a venv and installed django_heroku in the root folder of my project. When I run 'python manage.py runserver' I get the following error: ../settings.py", line 15, in <module> import django_heroku ModuleNotFoundError: No module named 'django_heroku' This is my requirements.txt, all of these are installed: asgiref==3.5.2 dj-database-url==1.0.0 Django==4.1 django-extensions==3.2.0 django-heroku==0.3.1 gunicorn==20.1.0 psycopg2==2.9.3 psycopg2-binary==2.9.3 python-dateutil==2.8.2 six==1.16.0 sqlparse==0.4.2 whitenoise==6.2.0 Relevant parts of settings.py: import os import django_heroku ... ALLOWED_HOSTS = ['*'] ... STATIC_ROOT = os.path.join(BASE_DIR, 'static') django_heroku.settings(locals()) This is my Procfile: web: gunicorn twatsite.wsgi I have tried changing my Procfile I have checked the venv/lib/site-packages folder and found django_heroku This is the structure of my folders: I have also tried moving the files in Twatter/twatsite/twatsite/.. one folder higher to Twatter/twatsite/.. This did not work and I moved the files back. Any pointers on how to solve or troublehsoot this issue are very welcome. -
Django listview filter related field lookup by date
I want to fetch only the elements of my VM model related to my Hypervisor model based on the current date, but when it finds them I fetch all the elements related to the parent model My Models class Hypervisor(models.Model): name = models.CharField(max_length=200) class VM(models.Model): hypervisor = models.ForeignKey(Hypervisor, on_delete=models.CASCADE) name = models.CharField(max_length=200) cpu = models.CharField(max_length=200) ram = models.CharField(max_length=200) disk = models.CharField(max_length=200) date = models.DateField(null=True) My view class vm(LoginRequiredMixin, ListView): model = Hypervisor template_name = 'vm_list_original.html' ordering = ['name'] def get_queryset(self, *args, **kwargs): return Hypervisor.objects.filter(vm__date=datetime.today().strftime('%Y-%m-%d')).distinct() DDBB sqlite> select * from budget_vm; 280|TC-CLINDE1-HARD001|4|8192|80|2022-09-01|254 281|TC-CLINDE1-HARD001|4|8192|80|2022-09-02|251 My Template <tbody> {% for hyper in object_list %} <tr> <td>{{ hyper.name }}</td> <td> {% for vm in hyper.vm_set.all %} {{ vm.name }} {% endfor %} </td> </tr> {% endfor %} </tbody> The Result -
How may I convert a Many to Many field into JSON Format in Django
I am working with APIs based in REST Architecture. I know Django has a framework to work with this APIs but my homework is do it from scratch. I got an API of a movies site where users can go and search information about a bunch of movies and i am trying to get the data into JSON format from the model Movie which has a Many-to-Many relationship whith the Actor model. I am using Class-based views for this. The code from my models.py and views.py files is nested below: class Actor(models.Model): full_name = models.CharField(max_length=125) role = models.CharField(max_length=125) def __str__(self): return self.full_name class Movie(models.Model): ACTION = 'AC' DRAMA = 'DR' COMEDY = 'CM' SCIENCE_FICTION = 'SF' THRILLER = 'TR' RELIGIOUS = 'RG' GENRE_CHOICES = [ (ACTION, 'Accion'), (DRAMA, 'Drama'), (COMEDY, 'Comedy'), (SCIENCE_FICTION, 'Ciencia Ficcion'), (THRILLER, 'Triler'), (RELIGIOUS, 'Religioso') ] title = models.CharField(max_length=155, blank=False) synopsis = models.TextField(max_length=1000, blank=True) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, default='', blank=False) tag = models.JSONField(default=dict, blank=True) actors = models.ManyToManyField(Actor, related_name='movies', blank=True) def __str__(self): views.py from django.views import View from django.http.response import JsonResponse from .models import Movie from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt import json class MovieView(View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def … -
CORS Problem using Django backend with Angular app
I'm using Django REST as a backend for my Angular app. When I make a call to API, I get CORS error. I set up all the CORS configuration in backend side. In settings.py file like: CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = list(default_methods) CORS_ALLOW_HEADERS = list(default_headers) + [ 'Access-Control-Allow-Origin', 'app-version' ] My CORS origin whitelist url is my angular app url and port = https://localhost.com:8002 Also I added corsheaders to INSTALLED APPS and middleware too. Here is my angular request: const url = 'https://local-django-api.com:8004/get-data'; return this.http.get<GetResponseInterface<any>>(`${url}`, { headers: { 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json', }, }); Note: When I try to make an API call using Postman to the same url, it successfully returns a value. Does anyone have an idea about this problem. Thanks in advance for any help. -
Django template does not output datetime
I'm currently on my way of learning some django version is 4.1. I created a simple page which displays all objects inside a database table. Everything works as wanted, but only on my local machine. On the remote machine only pages without any objects/models which contain at least one datetime database field work. So my question is, how do i find out the error. From the "host" I only get the following response if I use any datetime in the template (first part always changes but the "esponse" part is always the same): ��esponse received from application On the local machine I get a correct list of objects with their attributes. I use the same database, so all schema and data is the same. I tried around like 3 hours now and I'm out of ideas. The /admin page also does not work on the webhost only when I visit the localhost it can display output (my guess is also datetime). The ONLY thing I found out by now is, that if I get an object with a datetime field and I use the following code, I can get the view to render the following: obj = Example.objects.first() field_value = …