Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django View Try Exception doesn't work when User SignUp
Anyone could help me out real quick? Everything works (user SignUp success also in DB) except that it somehow doesnt print my Test at the end altough there shouln't be an exception? That means my welcome.html is not being rendered. My landing Page view def postSignUp(request): name = request.POST.get('name') email = request.POST.get('email') passw = request.POST.get('pass') try: user=authe.create_user_with_email_and_password(email,passw) uid = user['localId'] idtoken = request.session['uid'] #data = {"name":name, "status":"1"} #database.child("users").child(uid).child("details").set(data) except: return render(request, "signUp.html") print("Test") return render(request, "welcome.html", {"e":email}) I am expecting that the print("Test") is being executed and the return render(request, "welcome.html", {"e":email}) rendered. I am still landing on the SignUp but the user was created in the DB. -
A readonly and read/write connection to the same postgres db in Django
I'm wanting to use the same Postgres DB with 2 different postgres roles. One of which can write to any table and one that can only write to the django_session table. When I create this in the DATABASES settings, pytest (with xdist) wants to create databases for each set of DATABASE settings and goes boom because the DB already exists and can't be created. I'd like to create ONLY the readwrite DB and NOT the readonly DB, I essentially want it to be considered an externally controlled DB. But there seems to be no setting in DATABASES to indicate that. Only at the model level which of course won't work because I need those tables to be created on the R/W DB Connection Disallowing migrations in the router doesn't help here either, I'm thinking that that part must not be checked until after the connection to the DB is setup and usable and that is failing because the DB already exists. -
Text Editor recommendations for django shell (python manage.py shell)
When performing debugging or adding data to my database from csv files I rely on the django shell (python manage.py shell). I used this during development on a windows PC and although, I hated using it it was somewhat manageable. I could get back to multilined code for example. As I am switching to production I am now running on a Linux Server. The default editor here for the shell is simply unusable. I switched to ipython and at least I can write executable code now but ipython editor seems to have a compatibility problem. If I want to look at my database queryset I get: TypeError: str returned non-string (type NoneType) which seems to be a problem with repr(obj). Can anyone recommend an editor or does anyone know how to find out which one I was using before on windows? Thx and best -
The DRF model serializer returns a dictionary with None values
I'm new to the Django and DRF. My serializer return dict such as: {'Name': None}. I see the same problem, but don't find answer in this. I have the follow model: class Like(models.Model): post_liked = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) like_author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) class Meta: unique_together = ("post_liked", "like_author") def __str__(self): return f'{self.post_liked}, {self.like_author}' I have the follow simple Serializer: class LikeSerializer(serializers.ModelSerializer): class Meta: model = Like fields = '__all__' May be it's not enoufh? My view: class LikeDetail(View): def get(self, request, *args, **kwargs): if request.headers.get('X-Requested-With') == 'XMLHttpRequest': user = request.user post = Post.objects.get(id=kwargs["post_id"]) like = Like.objects.filter(post_liked=post.pk, like_author=user.pk) print(like) obj = LikeSerializer(like).data print(obj) return JsonResponse(obj) return 'if' is always triggered if it matters. You can see that I using js. Js file have fetch, but problem occurs in serialize process. Example: user: testuser post: flowers, Author print(like) => <QuerySet [<Like: flowers, Author, Testuser>]> obj = LikeSerializer(like).data print(obj) => {'post_liked': None, 'like_author': None} I have cheked many sources, but don't find answers. -
I can't get `extra_fields` printend each time a new user is created
I'd like to know why I can't get extra_fields printed each time a new user is created. I'm working with a CustomUserModel and I want to allocate the created object to a specific group based on its role and give it a set of permissions in my application. However, it seems like there's no role in extra_fields given the fact that the if statement is skipped. Here is the code # Manager class CustomUserManager(BaseUserManager): def create_user(self, username, email=None, password=None, **extra_fields): # It's not printed print("Extra fields: ", extra_fields) if email is not None: email = self.normalize_email(email) user = self.model(username=username, email=email, **extra_fields) user.set_password(password) # Skipped if "role" in extra_fields: group, create = Group.objects.get_or_create( name=extra_fields["role"] ) user.groups.add(group) user.save() return user def create_superuser( self, username, email=None, password=None, **extra_fields ): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_active", True) return self.create_user(username, email, password, **extra_fields) # Model class User(AbstractUser): class Roles(models.TextChoices): ADMIN = "ADMIN", "Admin" TEACHER = "TEACHER", "Teacher" STUDENT = "STUDENT", "Student" class Meta: db_table = "user" objects = CustomUserManager() default_role = Roles.ADMIN role = models.CharField(_("role"), max_length=10, choices=Roles.choices) def save(self, *args, **kwargs): if not self.pk: self.role = self.default_role return super().save(*args, **kwargs) What am I missing and where what would be the best approach. -
How to decode session value from Redis cache?
For authentication, I decided to use sessions stored in the Redis cache. In setting.py, I added: CACHES = { "default": { "BACKEND": "django.core.cache.backends.redis.RedisCache", "LOCATION": "redis://127.0.0.1:6379/0", } } SESSION_ENGINE = "django.contrib.sessions.backends.cache" There was a need to read all the sessions that are available. To do this, I run the following code r = redis.StrictRedis('localhost', 6379, db=0, decode_responses=True) for key in r.keys(): print('Key:', key) print('Value:', r.get(key)) If decode_responses=False, everything works, but the response looks like this Key: b':1:django.contrib.sessions.cachec2ynyeuinke4i4815oi7bjjf3jzx100s' Value: b'\x80\x05\x95%\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x0f_session_expiry\x94K<\x8c\x07user_id\x94K\x01u.' Traceback (most recent call last): File "C:\Users\adrian\PyCharmProjects\TestProject\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\adrian\PyCharmProjects\TestProject\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\adrian\PyCharmProjects\TestProject\venv\lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "C:\Users\adrian\PyCharmProjects\TestProject\venv\lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\adrian\PyCharmProjects\TestProject\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\adrian\PyCharmProjects\TestProject\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\adrian\PyCharmProjects\TestProject\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\adrian\PyCharmProjects\TestProject\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\adrian\PyCharmProjects\TestProject\accounts\views.py", line 65, in post print('Value:', r.get(key)) File "C:\Users\adrian\PyCharmProjects\TestProject\venv\lib\site-packages\redis\commands\core.py", line 1829, in get return self.execute_command("GET", name) File "C:\Users\adrian\PyCharmProjects\TestProject\venv\lib\site-packages\redis\client.py", line 536, in execute_command return conn.retry.call_with_retry( File "C:\Users\adrian\PyCharmProjects\TestProject\venv\lib\site-packages\redis\retry.py", line 46, in call_with_retry return do() File "C:\Users\adrian\PyCharmProjects\TestProject\venv\lib\site-packages\redis\client.py", line 537, in lambda: self._send_command_parse_response( File "C:\Users\adrian\PyCharmProjects\TestProject\venv\lib\site-packages\redis\client.py", line … -
In Django ORM, wildcard \b does not work (Postgres database)
All other wildcards work correctly but for example when I want to use "\bsome\b" pattern, it can't find any result however, there are many rows in the database that have a word "some" inside them. Other wild cards like ., +, *, \w and ... work properly. Any idea on what is the problem? Code: regex_pattern = r"\bsome\b" result = tweets.filter(text__regex=regex_pattern) -
Reusing queryset within a view that is called multiple times?
I have a view that is part of a page, I am using HTMX to update this view multiple times (each time is a new question, the user answers, then the next question is shown). The rest of the page does NOT reload. My issue is, every time the view is updated to ask a new question, it hits the database to get all the questions. Is there any way to pass all the questions on to all subsequent views, without hitting the database every time? I tried to pass it to the template, then back to the view, but that seems like a sup-optimal solution, and I could not get it to work anyway (it did not send objects back to the view, just characters). Here is the view.py: @login_required def question(request): questions = Question.objects.all() if request.method == 'POST': ## do stuff with the users answer, get next question answer = (request.POST.get("answer")) return render(request, 'interview/question.html', context) Here is the question.html: <form method="post"> {% csrf_token %} <input class="input" name="answer" type="text"></input><br><br> <input type="submit" value="Next Question" class="is-fullwidth pg-button-secondary" hx-post="{% url 'interview:next_question' %}" hx-target="#questionDiv" hx-include="[name='answer']" hx-vals = '{"questionNumber": "{{ question.question_number}}", "questions": "{{ questions}}"}' hx-swap="innerHTML"></input> </form> -
Need help making a website to find people in my city taking the some courses
I need help making i website where people from the same city meet i learn togother people can chearch for the people in same city or same coures I want people to add name phone number city coure there enrolled in in and people can find them by cheache in coueses or city or name I dont know what to use django or laravel or react -
Page not found (404) Directory indexes are not allowed here. in Django after gives path
enter image description here Using the URLconf defined in ebook.urls, Django tried these URL patterns, in this order: admin/ Guest/ Admin/ BookAuthor/ ^(?P.*)$ The empty path matched the last one. i'm looking for an solutions ... -
Running a Django server application through MATLAB
There is a 'Python Power Electronics' simulator built with a Django server application. The simulator runs on a local server when the 'python manage.py runserver' command is executed in the Anaconda prompt. Using this simulator, one can create and analyze power electronic circuits—an excellent tool. I am attempting to integrate the aforementioned simulator with MATLAB. This involves starting the server, selecting a specific simulation, and then running the simulation on 'Python Power Electronics' through a MATLAB script. My question is: Is it possible to start the Django server through a MATLAB script and choose a specific simulation from the Simulations folder on the server? Note: I've examined the source code of the 'Python Power Electronics' tool, a Python web framework. I have a basic understanding of the 'Run simulation' view in the views.py file, which is responsible for executing specific simulations. Now, my primary task is to start the Django server using MATLAB code before delving into the simulation execution. Any suggestions or answers are welcome. -
Return many forms in one view - Django Project
I'm not advanced in Django yet, so please be understanding. I'm currently working on creating my portfolio app. The idea is to build something similar to https://track.toggl.com. I frequently use this tool, and I thought that replicating this project could be an interesting challenge and a valuable addition to my CV as a beginner programmer. In the Home View, I aim to return a couple of forms: One blank form for creating a new Time Entry record in the project. Multiple forms pre-filled with data from the database. In the template of the Home View, I intend to display a list of all pre-filled forms to the user. This way, users can edit the data according to their preferences without the need for separate views/templates for editing. Now, my question is as follows: is the solution I've prepared suitable? Of course the most important is logic behind create_forms_for_user_data method, and is it properly used in get method. views.py class HomeView(view): template_name = 'pages/home.html' def get(self, request, *args, **kwargs): """ Should return : - User's all time entries - A form to create a new time entry - A list of forms to edit time entries """ user_data = self.get_user_data() blank_form … -
Django-cors-headers not working with Django and Vue
When I try to access my Django rest framework from the frontend I get this error and the data is not passed along Access to fetch at 'http://localhost:8000/api/students' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I tried using django-cors-headers and every setting for it that I could find online; absolutely nothing worked. Here are the settings from my settings.py file (currently commented out) ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'students' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'project.middleware.CustomCorsMiddleware', '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', ] # clickjacking not compatible with corsheaders? CORS_ORIGIN_ALLOW_ALL = True # CORS_ALLOW_CREDENTIALS = True # CORS_ORIGIN_WHITELIST = [ # "http://localhost:8000", # "http://127.0.0.1:8000", # "http://localhost:5173", # "http://127.0.0.1:5173", # ] # CORS_ALLOW_HEADERS = ['*'] # # CSRF_TRUSTED_ORIGINS = [ # "http://localhost:8000", # "http://127.0.0.1:8000", # "http://localhost:5173", # "http://127.0.0.1:5173", # ] I also tried using custom middleware that I found here on stack overflow. class CustomCorsMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, … -
I'm a beginner in django and I'm trying to create a django project "portfolio" and I'm getting this error can someone help me
i have already done these steps python -m venv ./venv .\venv\Scripts\activate pip install django django-admin startproject portfolio and when i did python manage.py startapp portfolio it shows this error (venv) PS C:\Users\Dell\OneDrive\Desktop\portfolio> python manage.py startapp portfolio C:\Users\Dell\AppData\Local\Programs\Python\Python311\python.exe: can't open file 'C:\\Users\\Dell\\OneDrive\\Desktop\\portfolio\\manage.py': [Errno 2] No such file or directory -
Handling JSON user input in a Django Form
This is a part of a school assigment where we have to use a JSON field in a model for our simple Django project. In this "book club" website, the user must have the ability to new submit books to the server. I would like the user input to not require knowing JSON syntax. The model for the book is as follows: class Book(models.Model): #book information name = models.CharField(default='title', max_length=100) #Name of the book authors = models.JSONField() #Author of the book year_published = models.IntegerField() #Year the book was published in date_added = models.DateTimeField(auto_now=True) #Date added (automatic) date_modified = models.DateTimeField(auto_now_add=True) #Date modified (automatic) def __str__(self): #Return the full title of the book with its author and publish year. fullname = f"{self.authors}.{self.name};({self.year_published})" return fullname I'm concerned about the 'authors' field in this case. Now the form into which the user would submit new books: class AddBook(forms.ModelForm): class Meta: model = Book fields = "__all__" And the view for add book functionality: def addbook(request): if request.method != 'POST': #no data submitted form = AddBook() else: form = AddBook(data=request.POST) print(form.errors) if form.is_valid(): form.save(commit=True) return redirect('cbc:books') context = {'form': form} return render(request, 'cbc/addbook.html', context) Now, this all works, but since the "authors" field in in … -
ValueError at watch
This code gave me this error. what's the problem? Field 'id' expected a number but got 'Watchlist object (1)'. thanks for any idea:) @login_required(login_url="login") def watchlist(request, username): products = get_object_or_404(Watchlist, pk=username) return render(request, 'auctions/watchlist.html', {'products': products}) @login_required(login_url="login") def add(request, productid): item = get_object_or_404(List, pk=productid) #user = get_object_or_404(Watchlist, user) user_Watchlist, __ = Watchlist.objects.get_or_create(user=request.user) user_Watchlist.watchitem.add(item) return redirect('watchlist', Watchlist.user) urls.py: path("watchlist/<str:username>/", views.watchlist, name="watchlist"), path("add/<int:productid>/", views.add, name="add"), -
Why are there problems with the django application (database, styles) when running on nginx?
I am practicing running django from luck on the nginx server, I wrote all the necessary configurations to run the application in which the production and developer versions are located and faced the problem that in the developer version everything works fine for me and in the production version the styles on the entire project are not loaded for me ( I have seen many similar questions, but I have everything written down as in the answers to them), and also my Postgres database does not work on production and gives me an error that it does not exist I provide code fragments settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') docker-compose.yml: version: '3.8' services: web: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres:15 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=hello_django - POSTGRES_PASSWORD=hello_django - POSTGRES_DB=hello_django_dev volumes: postgres_data: Dockerfile: # pull official base image FROM python:3.11.4-slim-buster # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install system dependencies RUN apt-get update && apt-get install -y netcat # install dependencies RUN pip install … -
Django models - Set an Foreign key attribute from a Many to Many in an antribute on the same level
AttributeError: type object 'type' has no attribute 'subtipos' I know that isnt working cause the object attribute isnt declared before assigning the attribute subtipo. I would like to know how to get a single subtipo to the Asset class selecting from the subtipos of the AssetType class. class SubAssetType(models.Model): name = models.CharField(max_length=50) slug = models.SlugField() descripcion = models.TextField(null=True, blank=True) class AssetType(models.Model): name = models.CharField(max_length=50) slug = models.SlugField() descripcion = models.TextField(null=True, blank=True) subtipos = models.ManyToManyField(SubAssetType, blank=True) class Asset(models.Model): # Atributos nominales name = models.CharField(max_length=50) slug = models.SlugField() descripcion = models.TextField(null=True, blank=True) # Atributos de valor type = models.ForeignKey(AssetType, on_delete=models.CASCADE) subtipo = models.ForeignKey(type.subtipos, on_delete=models.CASCADE) -
django view not passing context dict to html template
Trying to pass a dict which has various fields from a main table with additional data from the media table. The context is not getting to the html page, cant see why, any help would be appreciated. I have a very similar view using POST request which works without issue. Both test prints in the view return the correct values so must be an issue with the way the context is being passed to the html template. views.py def listing(request, listing_id): if listing_id: print(f"listing id: {listing_id}") results = ListingDetail.objects.filter(listing_id=listing_id).prefetch_related('media_set').all() print(results) return render(request, 'members/listing_detail.html', {'listing': results}) else: return render(request, 'general/search.html', {'listing': 'no data'}) html <div class="card"> listing_id = {{ listing.listing_id }} <div class="card-header"> <div id="carousel_main" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> {% for media_item in listing.media_set.all %} <div class="carousel-item {% if forloop.counter == 1 %}active{% endif %}"> <img src="{{ media_item.media_url }}" class="d-block" alt="" width="100%"> </div> {% endfor %} </div> urls.py urlpatterns = [ path('listing/<int:listing_id>', views.listing, name='listing'), ] -
Nextjs not sending csrf token to my django server
My code is working on localhost and I can see csrf by console log but when deploy on my server https I don't see csrf token and it's null I don't know why I am struggling to solve this problems from past few days and still now don't have any solution. I am not understanding why it's not working on production when deploy on my server but same code working on localhost. here is my react code for axois post const handleClickComment = (main_comment_id)=>{ const csrfToken = cookies.get("csrftoken") axios.post(url,comment_data,{ withCredentials:true, headers: { 'X-CSRFToken': csrfToken, // Adding the CSRF token to the request headers }, my django settings.py AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by email 'allauth.account.auth_backends.AuthenticationBackend', ] CORS_ALLOWED_ORIGINS = [ "http://*", "https://*", "http://localhost:3000", "https://localhost:3000", "http://127.0.0.1:3000", "https://127.0.0.1:3000", ] CORS_ORIGIN_WHITELIST = [ 'http://*', "https://*", "http://localhost:3000", "https://localhost:3000", "http://127.0.0.1:3000", "https://127.0.0.1:3000", ] CSRF_TRUSTED_ORIGINS = [ 'http://*', "https://*", "http://localhost:3000", "https://localhost:3000", "http://127.0.0.1:3000", "https://127.0.0.1:3000", ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = default_headers + ( 'xsrfheadername', 'xsrfcookiename', 'content-type', 'x-csrftoken', ) CSRF_COOKIE_SAMESITE = 'Strict' SESSION_COOKIE_SAMESITE = 'Strict' CSRF_COOKIE_HTTPONLY = False # False since we will grab it via universal-cookies SESSION_COOKIE_HTTPONLY … -
How to query (request) Yahoo Finance API in Django + Python for stock quotes?
What is other alternative to IEX Cloud for free stock quotes?! Shall i use yahoo_fin or yfinance?! I just want free stock quotes for a simple Stock Market API (beginner level). How do i write a query using yahoo_fin or yfinance?! Here is how i´m using IEX Cloud... from django.shortcuts import render, redirect from .models import Stock from .forms import StockForm from django.contrib import messages def home(request): import requests import json if request.method == 'POST': ticker = request.POST['ticker'] api_request = requests.get("https://cloud.iexapis.com/stable/stock/" + ticker + "/quote?token=<your_token>") try: api = json.loads(api_request.content) except Exception as e: api = "Error..." return render(request, 'home.html', {'api': api}) else: return render(request, 'home.html', {'ticker': "Enter a Ticker Symbol Above or Stock Quote..."}) -
Preventing sending some trace logs to Azure with Open-telemetry
I'm sending logs to Azure AppInsights by using Open-telemetry. The library keeps sending trace data constantly not only when the log occurs as shown in the picture. Is there an any way to close this or prevent it to write on trace table? -
weaspyrint does not render uploaded image from database
So here is my html code for the pdf <div class="cont"> <img class="logo1" src="{% static 'upload/' %}{{ wmsu_logo.img_name }}" /> <div> <p>Republic of the Philippines</p> <p>Western Mindanao State University</p> <p>{{ syllabus.college }}</p> <p class="title">DEPARTMENT OF {{ syllabus.department }}</p> </div> <img class="logo2" src="{% static 'upload/' %}{{ course_logo.img_name }}" /> <img class="logo3" src="{% static 'upload/' %}{{ iso_logo.img_name }}" /> </div> and this is the view where it processes things. def pdf(request, id): # ---------- SYLLABUS ---------- syllabus = get_object_or_404(Syllabus, user_id=request.user, id=id) # ---------- SYLLABUS TEMPLATE ---------- syllabus_template = get_object_or_404(Syllabus_Template, user_id=request.user, id=syllabus.syllabus_template_id.id) wmsu_logo = Logo.objects.get(syllabus_template_id=syllabus_template, name='wmsu_logo') course_logo = Logo.objects.get(syllabus_template_id=syllabus_template, name='course_logo') iso_logo = Logo.objects.get(syllabus_template_id=syllabus_template, name='iso_logo') total_term_percentage = midterm.term_percentage + finalterm.term_percentage template = loader.get_template('PDF_template/template.html') # Load HTML template html_string = template.render({ 'wmsu_logo': wmsu_logo, 'course_logo': course_logo, 'iso_logo': iso_logo, }) # Render the template # Generate the PDF using WeasyPrint pdf = HTML(string=html_string, base_url=request.build_absolute_uri()).write_pdf() # Create an HttpResponse with the PDF content response = HttpResponse(pdf, content_type='application/pdf') # Display in the browser response['Content-Disposition'] = 'inline; filename=Syllabus' + str(datetime.datetime.now()) + '.pdf' return response I need the uploaded image in the pdf conversion in weasyprint. I already deployed this in pythonanywhere. When I use the local file the image renders but when I deploy it, it does not render the … -
ProgrammingError: relation does not exist. Django postgresql
What's up some guys! I am trying to fetch data from my postgresql database, but it does not seem to find it. Basically I'm getting "ProgrammingError: relation does not exist" but I will let the errors and code speak for itself, so let's cut to the chase immediately (sorry in advance for a long post, I didn't want to leave any information out). This is the error I'm getting: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\filip\Desktop\WebNutrition\backend\NutriCalc\tests.py", line 13, in test_fetch_nutrition_values print(result) File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 374, in __repr__ data = list(self[: REPR_OUTPUT_SIZE + 1]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 398, in __iter__ self._fetch_all() File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 1881, in _fetch_all self._result_cache = list(self._iterable_class(self)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 208, in __iter__ for row in compiler.results_iter( ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\sql\compiler.py", line 1513, in results_iter results = self.execute_sql( ^^^^^^^^^^^^^^^^^ File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\sql\compiler.py", line 1562, in execute_sql cursor.execute(sql, params) File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 84, in _execute with self.db.wrap_database_errors: File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\filip\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … -
Start gunicorn wiht django and show No module named 'fastapi'
During handling of the above exception, another exception occurred: Nov 28 03:51:54 PM Nov 28 03:51:54 PM Traceback (most recent call last): Nov 28 03:51:54 PM File "/root/.cache/pypoetry/virtualenvs/v-P1yi_rtL-py3.10/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner Nov 28 03:51:54 PM response = get_response(request) Nov 28 03:51:54 PM File "/root/.cache/pypoetry/virtualenvs/v-P1yi_rtL-py3.10/lib/python3.10/site-packages/sentry_sdk/integrations/django/middleware.py", line 175, in call Nov 28 03:51:54 PM return f(*args, **kwargs) Nov 28 03:51:54 PM File "/root/.cache/pypoetry/virtualenvs/v-P1yi_rtL-py3.10/lib/python3.10/site-packages/htmlmin/middleware.py", line 21, in call Nov 28 03:51:54 PM response = self.get_response(request) Nov 28 03:51:54 PM File "/root/.cache/pypoetry/virtualenvs/v-P1yi_rtL-py3.10/lib/python3.10/site-packages/django/core/handlers/exception.py", line 49, in inner Nov 28 03:51:54 PM response = response_for_exception(request, exc) Nov 28 03:51:54 PM File "/root/.cache/pypoetry/virtualenvs/v-P1yi_rtL-py3.10/lib/python3.10/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception Nov 28 03:51:54 PM response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) Nov 28 03:51:54 PM File "/root/.cache/pypoetry/virtualenvs/v-P1yi_rtL-py3.10/lib/python3.10/site-packages/django/core/handlers/exception.py", line 152, in handle_uncaught_exception Nov 28 03:51:54 PM callback = resolver.resolve_error_handler(500) Nov 28 03:51:54 PM File "/root/.cache/pypoetry/virtualenvs/v-P1yi_rtL-py3.10/lib/python3.10/site-packages/django/urls/resolvers.py", line 615, in resolve_error_handler Nov 28 03:51:54 PM callback = getattr(self.urlconf_module, 'handler%s' % view_type, None) Nov 28 03:51:54 PM File "/root/.cache/pypoetry/virtualenvs/v-P1yi_rtL-py3.10/lib/python3.10/site-packages/django/utils/functional.py", line 48, in get Nov 28 03:51:54 PM res = instance.dict[self.name] = self.func(instance) Nov 28 03:51:54 PM File "/root/.cache/pypoetry/virtualenvs/v-P1yi_rtL-py3.10/lib/python3.10/site-packages/django/urls/resolvers.py", line 595, in urlconf_module Nov 28 03:51:54 PM return import_module(self.urlconf_name) Nov 28 03:51:54 PM File "/usr/local/lib/python3.10/importlib/init.py", line 126, in import_module Nov 28 03:51:54 PM return _bootstrap._gcd_import(name[level:], package, …