Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I resolve "Serverless Function has exceeded the unzipped maximum size of 250 MB" error on Vercel?
I have a personal project that I am building in Python using Django. When deploying it to Vercel, it worked fine until eventually the amount of libraries that I imported (included in my requirements.txt file) became too large, I assume, and now I face the "Serverless Function has exceeded the unzipped maximum size of 250 MB" error. The library that takes up the most space is Wordcloud (and botocore / boto3). Surely there must be a way around this? As far as I'm aware, paying for a higher tier of Vercel will not resolve this issue. Is there any workaround to this issue, or is the best option to just use a different service other than Vercel? This is my requirements.txt: Django==4.2.8 psycopg2-binary==2.9.8 Pillow==8.2.0 django-storages==1.14.2 boto3==1.34.4 botocore==1.34.4 Pyrebase4==4.7.1 regex==2020.11.13 python-dateutil==2.8.2 textblob==0.17.1 nltk==3.6.3 json5==0.9.14 jsonpath-ng==1.5.3 jsonpointer==2.4 jsonschema==4.19.0 jsonschema-specifications==2023.7.1 wordcloud==1.9.2 matplotlib==3.7.2 matplotlib-inline==0.1.6 Obviously when I remove the libraries from my project that takes up the most space, it does build successfully. So the problem is not with my code itself, and it does build and start up successfully when I open a local instance. I'm still relatively new with Python, so I would appreciate any help, even if it is "basic" - … -
hello I’ve got big problem when I open my site I’ve got “SyntaxError at / invalid syntax (views.py, line 78)” for review
It does not tell me which of my views has this problem. It is strange that there is no problem in http://127.0.0.1:8000/, but there is a problem in the host I bought. I have also talked to the support and they said that it is a python problem and you have to solve this problem with a python programmer here is my project, accounts and blog app views: `from django.shortcuts import render,get_object_or_404,redirect from blog.models import Post from django.utils import timezone from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger from blog.models import Comment from blog.forms import CommentForm from django.contrib import messages from django.urls import reverse from django.http import HttpResponseRedirect def blog_view(request,kwargs): posts=Post.objects.filter(status=1,published_date__lte=timezone.now()) if kwargs.get('cat_name')!=None: posts=posts.filter(category__name=kwargs['cat_name']) if kwargs.get('author_username')!=None: posts=posts.filter(author__username=kwargs['author_username']) if kwargs.get('tag_name')!=None: posts=posts.filter(tags__name__in=[kwargs['tag_name']]) posts=Paginator(posts,4) try: page_number=request.GET.get('page') posts=posts.get_page(page_number) except PageNotAnInteger: posts=posts.get_page(1) except EmptyPage : posts=posts.get_page(1) # return render(request, 'blog/post_detail.html', {'post': post}) # posts=Post.objects.filter(status=0) context={'posts':posts} return render(request,'blog/blog-home.html',context) def blog_single(request,pid): if request.method=='POST': form =CommentForm(request.POST) if form.is_valid(): form.save() messages.add_message(request,messages.SUCCESS,"your comment submited") else: messages.add_message(request,messages.ERROR,"your comment didnt submited") post = get_object_or_404(Post,pk=pid,status=1,published_date__lte=timezone.now()) post.counted_views += 1 post.save() previous_post = Post.objects.filter(id__lt=pid,status=1,published_date__lte=timezone.now()).order_by('-id').first() next_post = Post.objects.filter(id__gt=pid,status=1,published_date__lte=timezone.now()).order_by('id').first() if not post.login_require: comments=Comment.objects.filter(post=post.id,approved=True).order_by('-created_date') form=CommentForm() context={'post':post,'previous_post': previous_post,'next_post': next_post,'comments':comments,'form':form} return render(request,'blog/blog-single.html',context) else: return HttpResponseRedirect(reverse('accounts:login')) def blog_category(request,cat_name): posts=Post.objects.filter(status=1) posts=posts.filter(category__name=cat_name) context={'posts':posts} return render(request,'blog/blog-home.html',context) def blog_search(request): posts=Post.objects.filter(status=1,published_date__lte=timezone.now()) # print(request.__dict__) if request.method=='GET': # print(request.GET.get('s')) if s:=request.GET.get('s'): **that's … -
How to make an ajax jquery request to get data from a Django ListView?
I have a base template in which I have a header and in that header, there are some link buttons that I would like to change the appearance of when clicked, for this it would be necessary to use ajax to avoid reloading the page. The request must be a GET to display the updated page data. That is, the ajax script must be done in my base.html at the button click event, to load the template that extends the base. Right? The view: class HomeListView(ListView): model = Cars template_name = 'cars.html' context_object_name = 'cars' def get_queryset(self): cars = super().get_queryset().order_by('model') return cars The data in the template cars.html (which extends base.html) is processed in this way: <div class="car-grid"> {% if cars %} {% for car in cars %} <div class="car-card"> <img src="{{ car.photo.url }}" alt="{{ car.model }} - {{ car.brand }}"> <h2> {{ car.brand }} {{ car.model }} </h2> <p> {{ car.factory_year }} - $ {{ car.value }} </p> </div> {% endfor %} {% else %} <p class="no-results">No results found. </p> {% endif %} </div> What is the smartest way to make this ajax request to get the updated cars context variable? Is there any way to pass it to … -
How to create a Django queryset based on values of recursive ManyToManyField?
I have a dictionary app where words (Lemma) can be optionally composed of other words. In my models.py, this looks like: cf = models.CharField(max_length=200) #citation form pos = models.ForeignKey(Pos, on_delete=models.CASCADE) #part of speech components = models.ManyToManyField("self", symmetrical=False, blank=True) #component Lemma I want to return two query sets: All compound verbs: Lemma that have values in self.components and where self.pos.term="verb" All unique components of compound verbs that are nouns: Lemmas that are values of some other Lemma's self.component_set() and which themselves have self.pos.term="noun". I want to use views to pass these two lists to a template. I'm able to get queryset 1 pretty easily, but my solutions for queryset 2 are all quite convoluted. The relevant class in my views.py looks like this: model = Lemma queryset = Lemma.objects.filter( Q(pos__term="verb") & ~Q(components=None) ).order_by("cf") #queryset 1, compound verbs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) nouns = self.queryset.values_list("components") nouns = set([Lemma.objects.get(pk=l[0]) for l in nouns]) nouns= [l for l in nouns if l.pos.term == "noun"] context["nouns"] = nouns #queryset 2, nouns that are components of compound verbs return context This also leaves me with a regular list for my verbs variable rather than a proper queryset where I can use the .order_by() method … -
when creating zoom i am getting invalid access token error when my keys are valid
import requests import json API_KEY = 'API KEY' API_SEC = 'SECRET KEY' zoom_api_url = 'https://api.zoom.us/v2/users/me/meetings' meeting_details = { "topic": "The title of your Zoom meeting", "type": 2, "start_time": "2024-02-27T10:00:00", "duration": "45", "timezone": "Europe/Madrid", "agenda": "Test Meeting", "settings": { "host_video": "true", "participant_video": "true", "join_before_host": "False", "mute_upon_entry": "False", "watermark": "true", "audio": "voip", "auto_recording": "cloud" } } headers = { 'Content-Type': 'application/json', } auth = (API_KEY, API_SEC) response = requests.post(zoom_api_url, headers=headers, auth=auth, data=json.dumps(meeting_details)) print(response.json()) after I am getting access token but its saying invalid access token i have added keys and allowed authentication on zoom i have tested it with postman as well as through my django app From every platform i am getting same error ** Invalid Access Token** I tried to create access with jwt.io too but still its not working if anyone can help what is wrong? -
How can I assign a url to a button that redirect users to an external website when the data is split up into two data frames?
I have function in my view that fetches data from multiple spreadsheets and normalizes said data into one single data frame via Pandas. This df1 is eventually rendered and displayed in a webapp in the form of a bootstrap table using Django. For the sake of simplicity, let’s say this table has two columns: “Games” and “Link”. “Games" shows all the soccer matches for today and “link” simply has a button for each of the games. This button does nothing for now. Now, I have another function that fetches data from a different source and again, normalizes the data using Pandas creating a df2 with three columns: “Games”: shows some soccer matches for today (this column has some but not all the games in df1 with exactly the same format). “Id”: a 4-digit identifier that is unique to each of the games above. “Url”: a url that contains the “id” and redirects the user to an external website that provides the user with extra information about that particular match. I’m trying to figure out a way where the users can click on the buttons available in the webapp (which are linked to the games in df1) and get redirected to … -
Django display DateFormat as dd/mm/yyyy
I have a form in Django where the user needs to select the date. When the user selects the date the date is displayed in the following format mm/dd/yyyy (eg. 02/29/2024). I want the date in the form to be displayed as dd/mm/yyyy (eg. 29/02/2024 ). This is the date field in my form: date = forms.DateField( widget=forms.DateInput(format='%d/%m/%Y', attrs={'type': 'date', 'min': str(timezone.now().date()), 'max': str((timezone.now() + timedelta(days=365)).date())}), help_text='Select a date', input_formats=['%d/%m/%Y'], validators=[validate_future_date], ) I also tried: In settings.py: DATE_INPUT_FORMATS = ('%d-%m-%Y',) USE_I18N = True USE_L10N = True In the form: input_formats=settings.DATE_INPUT_FORMATS, After both of these approaches the format was still displayed as dd/mm/yyyy. -
Django View to return template with refreshed modal window
I'm using Django form in modal window where core content (in container) generated by JS. On submit django model instance saved without any issues if form.is_valid() == True a modal window closes with switching focus on current background page. However if form.is_valid() == False the modal content just opens in separate URL instead and takes all browser screen as View renders just a short code fragment in .html file. The goal is to refresh the modal window on current condition in case if form_is_valid() == False with form errors. Template "accounts/profile_settings.html" contains a form and submit button which renders inside <div class="preferences_content"> {% comment %} JS generated dynamic content depends on tab pressed. {% endcomment %} </div> My JS knowldge is very basic so I appreciate any suggestion on this topic. The View : def profile_update_view(request): """ Updates current Profile instance.""" if request.method == "POST": current_profile = request.user.profile profile_form = ProfileUpdateForm(request.POST, request.FILES, instance=current_profile) if profile_form.is_valid(): profile_form.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER', "/")) else: profile_form = ProfileUpdateForm() return render(request, "accounts/profile_settings.html", {'profile_form': profile_form}) else: profile_form = ProfileUpdateForm() return render(request, "accounts/profile_settings.html", {'profile_form': profile_form}) document.addEventListener("DOMContentLoaded", function() { var openModalLink = document.getElementById("openPreferencesModal"); var modal = document.getElementById("preferencesModal"); var span = modal.querySelector(".close"); var preferencesContent = modal.querySelector(".preferences_content"); var tabs = modal.querySelectorAll(".tab"); … -
Django losing session state?
I have a VPS running apache. Apache is serving two domains, my homepage (django, django-cms, zinnia) and a prod site (django, oscar). I use falkon browser. When I change the items in site's admin (I change values in a row, it's list_editable, and then click Save), sometimes (quite often), the response returned is a redirect to login, as if the session cookie is not passed. What is interesting, if I save the POST request as curl and retry it, it succeeds. Since there are several redirects after I hit save, I've seen it failing on the first one (so the item is not saved), or the second one (the item is therefore saved, but I find myself not on the list page, but on the main admin page). How do I debug it? I suspect it may be a browser issue, I'll try mitmproxy now to see what's really hitting the network. But maybe someone has seen this behaviour before. -
Migrate project from Django 1.8 to 1.11 and TemplateDoesNotExist at /accounts/login/
i am beginner in Python and Django. I must update project from Django 1.8 to 1.11 (and in past to 2,3,4). I make update my requirements file and pip. When I write in WSL: ./.venvs/bin/python3 manage.py runserver I have error i browser: TemplateDoesNotExist at /accounts/login/ _accounts/login.html Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/?next=/ Django Version: 1.11 Exception Type: TemplateDoesNotExist Exception Value: _accounts/login.html my urls.py: from django.conf import settings from django.views.generic.base import TemplateView from django.conf.urls import include, url from django.contrib.auth.views import login from go.accounts.decorators import check_login_abuse from go.accounts.forms import AuthenticationForm, PasswordResetForm from go.insurance.views import index urlpatterns = [ url(r'^$', index), url(r'^accounts/login/$', check_login_abuse(login), {'template_name': 'accounts/login.html', 'authentication_form': AuthenticationForm}), url(r'^accounts/logout/$', logout, {'template_name': 'accounts/logout.html'}), ] How can i repair this problem? I use Python 3.8 -
Static files on EC2 instance, AWS
I recently deployed my project to an Ubuntu EC2 instance and I noticed that the static files (css) don't seem to be loading(same with the images from sqLite3-database). For my website I use django: What I'm getting: When I enter my website, my css and media doesn't load. What's more I can't access one of my slug-pages, because I always get 500 bad request: [27/Feb/2024 09:53:36] "GET /about-me/ HTTP/1.1" 500 145 [27/Feb/2024 09:53:58] "GET / HTTP/1.1" 200 12343 [27/Feb/2024 09:53:58] "GET /static/css/home.css?%201709027638 HTTP/1.1" 404 179 [27/Feb/2024 09:53:58] "GET /media/images/Crawler_Post_Picture.png HTTP/1.1" 404 179 *my setup: ├── core ├── db.sqlite3 ├── home ├── manage.py ├── media ├── requirements.txt ├── static ├── staticfiles ├── templates └── venv What I've already tried: collectstatic migrate change my settings.py into: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'staticfiles'), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' 5)urls.py: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) add this in my homepage.html template <head>: <link rel="stylesheet" type="text/css" href="{% static 'css/home.css' %}?{% now " U" %}" /> I'm a newbie, so thanks in advance! -
Django mocking a function in a View does not work
Ok so here is the situation. I'm using Django, DRF and for tests django.test and unitest.mock I have a View which executes a method inside a post request sending a message to Kafka (send_message_to_kafka). This method is not in a viewset and I am trying to mock it. I wrote 2 tests. to call a method wrapper_send_message_to_kafka() which calls send_message_to_kafka inside it. self.client.post("/viewset/", data=payload). Both of these tests mocks the function send_message_to_kafka bypassing the actual publish to Kafka. @mock.patch('utils.send_message_to_kafka', return_value={"success": True, "message": "Message sent to Kafka successfully!"}) But the first works as expected and the second is not mocked. View @api_view(["POST"]) def example_view(request): if request.method == "POST": ... result = send_message_to_kafka(json.dumps((message))) Tests from django.test import TestCase import unittest.mock as mock ... @mock.patch('utils.pubsub.send_message_to_kafka', return_value={"success": True, "message": "Message sent to Kafka successfully!"}) def test_send_message_to_kafka(self, send_message_mock): result = wrapper_send_message_to_kafka() self.assertTrue(result["success"]) @mock.patch('utils.send_message_to_kafka', return_value={"success": True, "message": "Message sent to Kafka successfully!"}) def test_start_run(self, send_message_mock): response = self.client.post( "/execute/", data=payload, format="json", ) -
Django Register View not Saving User Model to Database
I built a registration form + view + template, but when I try to register, the user is not being saved to the database, neither does it log me in. I expected my form to register my user and save it to the database. This is my code (Register form) from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class UserRegistrationForm(forms.ModelForm): email = forms.EmailField() password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email'] def check_password(self): if self.cleaned_data['password'] != self.cleaned_data['password2']: raise forms.ValidationError('Passwords do not match!') return self.cleaned_data['password2'] (Register view) def register_view(request): if request.method == 'POST': register_form = UserRegistrationForm(request.POST) if register_form.is_valid(): user = register_form.save(commit=False) user.set_password = register_form.cleaned_data['password'] # Automatically log in the user after registration username = register_form.cleaned_data['username'] password = register_form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page or home page return redirect('home1:index') # Adjust 'home' to your home page URL name else: register_form = UserRegistrationForm() return render(request, 'register.html', {'register_form': register_form}) (Register Template) <form class="form" method="post"> {% csrf_token %} <label class="label" for="email">Email:</label> <input class="input" type="text" id="email" name="email"> <label class="label" for="username">Username:</label> <input class="input" type="text" id="username" name="username"> <label class="label" for="password">Password:</label> <input … -
I issue with my Django project recognizing mysqlclient module installed with xampp
I got this error on trying to install Xampp: 'Important! Because an activated User Account Control(UAC) on your system some functions of Xampp are possibly restricted. With UAC please avoid to install Xampp to C:\Program Files(missing write permissions). Or deactivate UAC with msconfig after this setup' If i go ahead and install xampp, then mysqlclient module is not seen by the project. I also get the warning that xampp doesn't have admin previledges. If I give xampp admin previledges, I see 'x' mark on my xampp interface against Apache, Mysql & Tomcat. Even installing in another directory hasn't worked either. I don't know what I am doing wrong. If i go ahead and install xampp, then mysqlclient module is not seen by the project. I also get the warning that xampp doesn't have admin previledges. If I give xampp admin previledges, I see 'x' mark on my xampp interface against Apache, Mysql & Tomcat. Even installing in another directory hasn't worked either. I don't know what I am doing wrong. -
Factory boy field for self-referential field in django abstract model
`class BaseOrganization( OrganizationModelMixin, TimeStampedModel, OrganizationWidgetsMixin ): name = models.CharField(max_length=255, verbose_name="Nomlanishi", null=True) juridical_address = models.CharField( max_length=150, verbose_name="Yuridik manzili", null=True, blank=True ) phone_number = models.CharField( max_length=150, verbose_name="Telefon raqami", null=True, blank=True, validators=[phone_regex], ) parent = models.ForeignKey( "self", on_delete=models.SET_NULL, null=True, blank=True, related_name="%(class)s_children", verbose_name="Yuqori tashkilot", ) class Meta: abstract = True class BaseOrganizationFactory(factory.django.DjangoModelFactory): """Base organization factory""" name = factory.Faker("company") juridical_address = factory.Faker("address") phone_number = factory.Faker("phone_number") parent = factory.SubFactory( "myapp.tests.factories.BaseOrganizationFactory", ) @pytest.mark.django_db class TestBaseOrganization: @pytest.fixture(autouse=True) def setup(self): self.base_organization = BaseOrganizationFactory( parent=None ) ` if i call BaseOrganizationFactory in setup method it caused RecursionError: maximum recursion depth exceeded while calling a Python object -
Django web application cannot load a page
I am currently building a Django web app(A toy store). But some pages just won't load. After I log in or register to the web app, and I choose the category of ages 10-14, there appears the toys available, when I click on a toy it is supposed to take me to the details page but, for some reason it keeps loading and never opens. It worked yesterday when I ran it. I run it on localhost. Here is all the code for my project: https://github.com/MosheM123/Toys -
Parsing nested JSON in Django Rest Framework
I am trying to serialize a geometry dict which also contains a location dict and map that dictionaries values to my model. The data comes in two levels deep and is mapped to a single model, because its from an external API. How I've done it so far is with source='*' but this requires a new ModelSerializer for every nested object. Is there a way to "skip" to the nested object I want? For example here is some input data: { ... geometry: { location: { lat: ..., lng: ..., } } ... } Then I map it to a model like this: class MyModel(models.Model): ...other attributes from 1 level deep latitude = CharField() longitude = CharField() And my current serializer do that like this: class GeometrySerializer(serializers.ModelSerializer): latitude = serializers.DecimalField(max_digits=globals.MAX_DECIMAL_DIGITS, decimal_places=globals.MAX_DECIMAL_PLACES) longitude = serializers.DecimalField(max_digits=globals.MAX_DECIMAL_DIGITS, decimal_places=globals.MAX_DECIMAL_PLACES) class Meta: model = models.Location fields = ['latitude', 'longitude'] class GeometryLocationSerializer(serializers.ModelSerializer): location = GeometrySerializer(source='*') class Meta: model = models.Location fields = ['location'] class LocationSerializer(serializers.ModelSerializer): # Nested obj from json req, geometry: { location: { lat: ..., lng: ...} ....} #latitude = serializers.DecimalField(max_digits=globals.MAX_DECIMAL_DIGITS, decimal_places=globals.MAX_DECIMAL_PLACES, source='geometry.location.lat') #longitude = serializers.DecimalField(max_digits=globals.MAX_DECIMAL_DIGITS, decimal_places=globals.MAX_DECIMAL_PLACES, source='geometry.location.lng') geometry = GeometryLocationSerializer(source='*') class Meta: model = models.Location fields = ['id', 'addr_address', 'business_status', 'formatted_address', 'formatted_phone_number', 'icon', … -
DateTime conversion (March 5, 2024, 5:33 a.m. to datetime.datetime(2024, 3, 5, 5, 33))
i have raw date = March 5, 2024, 5:33 a.m. is it possible to convert it in datetime.datetime(2024, 3, 5, 5, 33) using python I have tried from datetime import datetime date_string = "March 5, 2024, 5:33 a.m." date_object = datetime.strptime(date_string, "%B %d, %Y, %I:%M %p") desired_datetime = datetime(2024, 3, 5, 5, 33) print(desired_datetime) -
Expected out is not coming in Django python
I am new to python! I was trying to scrap menu structure of any website! the out is coming fine when I tried in VScode! here is the code for i in menu_items('https://natureshair.com.au/'): print(json.dumps(i, indent=6)) And this is the output, Script can scrap all the menu Now I am trying to collect this website and display results using Django! the strange thing is if I use the same website the output is empty! here is the code : def product(request): finaldata=request.GET["title"] finaldata1=request.GET["title1"] finaldata2=request.GET["title2"] results = list( item #for link in ('https://natureshair.com.au/', 'https://www.trafficradius.com.au/') for link in (finaldata,finaldata1,finaldata2) for item in menu_items(link)) return JsonResponse({'results': results}) Output: Note: it not working for a few websites like 'https://natureshair.com.au/' and this is working fine in VS code! Not sure where I am wrong here is the link to my project My projrct -
module 'django.apps' has no attribute 'get_model'
I am writing a funciton to delete object, with only by sending it's app_name and model_name in from url. here is my function. def deleteobject(request, app_name, model_name, id): print(app_name, model_name, id) print(type(app_name), type(model_name), type(id)) try: model_class = apps.get_model(app_name,model_name) except LookupError: model_class = None print(model_class) if model_class: try: obj = model_class.objects.get(id=id) print(obj) obj.delete() except model_class.DoesNotExist: return HttpResponseBadRequest("Object not found.") else: return HttpResponseBadRequest("Invalid model name.") return redirect(request.META.get('HTTP_REFERER', '/'))` it returns this error message: AttributeError at /projectmanagement/delete/ProjectManagement/task/1 module 'django.apps' has no attribute 'get_model' -
can we apply date range filter on date if date data type or dtype is text or str?
models- `class RocCharge(models.Model):` `charge_id = models.IntegerField(blank=True, null=True)` `chname = models.CharField(max_length=100, blank=True, null=True, db_index=True)` `date_of_creation = models.TextField(default=date.today)` views- `from_date = request.GET.get('fromdate')` `to_date = request.GET.get('Todate')` `if from_date and to_date: combined_data = combined_data.filter(date_of_creation__gte=from_date, date_of_creation__lte=to_date)` my date of creation in mysql as well as in models in text format , but i want to perform date range filter from to range without changing date data type , my date in mysql like-21-12-2019 -
Why am I getting 'OperationalError at /account/me/ no such table: main_enroll' if I have the table clearly in main/models? [duplicate]
This question is getting flagged as a duplicate, however the other question's problem is very different than mine in that the person did not run migrations. I have gotten the error 'Operational Error: No Such Table main_enroll' In Django, and I do not understand why as I have defined it properly: Main/Models.py: from django.contrib.auth.models import AbstractUser from django.conf import settings from django.db import models class Course(models.Model): course_name = models.CharField(max_length=30) course_slug = models.CharField(max_length=70) # Other course-related fields def __str__(self): return self.course_name class Enroll(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) course = models.ForeignKey('main.Course', on_delete=models.CASCADE) Accounts/Models.py: from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): pass Screenshot of error: Copy & Paste view of error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/account/me/ Django Version: 5.0.2 Python Version: 3.11.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'main', 'welcome', 'userprofile', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\db\backends\utils.py", line 105, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\db\backends\sqlite3\base.py", line 329, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The above exception (no such table: main_enroll) was the direct cause of the following exception: File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = … -
Why am I getting 'OperationalError at /account/me/ no such table: main_enroll' if I have the table clearly in main/models? [duplicate]
I have gotten the error 'Operational Error: No Such Table main_enroll' In Django, and I do not understand why as I have defined it properly: Main/Models.py: from django.contrib.auth.models import AbstractUser from django.conf import settings from django.db import models class Course(models.Model): course_name = models.CharField(max_length=30) course_slug = models.CharField(max_length=70) # Other course-related fields def __str__(self): return self.course_name class Enroll(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) course = models.ForeignKey('main.Course', on_delete=models.CASCADE) Accounts/Models.py: from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): pass Screenshot of error: Copy & Paste view of error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/account/me/ Django Version: 5.0.2 Python Version: 3.11.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'main', 'welcome', 'userprofile', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\db\backends\utils.py", line 105, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\db\backends\sqlite3\base.py", line 329, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The above exception (no such table: main_enroll) was the direct cause of the following exception: File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\skeleton\userprofile\views.py", line 19, in account_page Enroll.objects.create(user=user, course=course) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\db\models\query.py", … -
Incoming file from post is "fakepath"
Brand new to react. My file is sending as a fakepath. I know this is for browser sercurity but I expected it to be different in my view. When I deserialize the request.body with json.loads I get this FileNotFound error. fitz.FileNotFoundError: no such file: 'C:\fakepath\HW 3 CPSC 332.pdf' When I deserialize the body with my own serializer it returns that the object is not valid. I am assuming this is due to the same issue with the fake file path. request.body b'{"title":"sdfg","content":"","file":"C:\\\\fakepath\\\\HW 3 CPSC 332.pdf"}' views.py @api_view(['POST']) def createPost(request): serializer = SinglePostSerializer(data=request.body) if serializer.is_valid(): serializer.save() return Response({'message': 'File uploaded successfully'}, status=status.HTTP_201_CREATED) else: return Response({'errors': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) serializers.py class SinglePostSerializer(ModelSerializer): class Meta: model = Post fields = '__all__' models.py # Create your models here. class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=50) likes = models.IntegerField(default=0) comment_count = models.IntegerField(default=0) pdf_file = models.FileField(upload_to='media/pdfs/') images = models.ManyToManyField(SheetMusicImage) comments = models.ManyToManyField('Comment', blank=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.pdf_file.name CreatePostPage.js import React, { useState, useEffect} from 'react' const CreatePostPage = () => { const [formData, setFormData] = useState({ // Initialize form fields here // For example: title: '', content: '', }); const handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value, }); }; … -
Websocket connection doesn't work with redis cluster
I'm trying to establish a websocket connection but it doesn't seem to work due to my redis server which is a cluster from elasticache. Here are the logs: Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/channels/consumer.py",> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: await handler(message) Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/channels/generic/webso> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: await self.connect() Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/shipninja/shipninja/shipninja/consumers.py", line 36, in> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: await self.channel_layer.group_add("inventory", self.channel_name) Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/channels_redis/core.py> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: await connection.zadd(group_key, {channel: time.time()}) Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/redis/asyncio/client.p> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: conn = self.connection or await pool.get_connection(command_name, **optio> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/redis/asyncio/connecti> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: await self.ensure_connection(connection) Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/redis/asyncio/connecti> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: await connection.connect() Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/redis/asyncio/connecti> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: raise ConnectionError(self._error_message(e)) Feb 27 03:54:24 ip-172-31-40-162 python[12684]: redis.exceptions.ConnectionError: Error -2 connecting to rediss://clustercfg.> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: Future exception was never retrieved Feb 27 03:54:24 ip-172-31-40-162 python[12684]: future: <Future finished exception=gaierror(-2, 'Name or service not known')> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: socket.gaierror: [Errno -2] Name or service not known Feb …