Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fetch error response status is 500 /api/schema/
After adding photos serializer to the serializers and post method to views im getting a fetch error response. Prior to adding photos to serializers everything was working fine. Being that the app is hosted on aws getting details for the error within the server logs is different. class PhotosSerializer(serializers.ModelSerializer): """Serializer for photos model""" class Meta: model = Photos fields = ['report_uuid', 'grounds_photos', 'roof_photos', 'exterior_photos', 'garage_photos', 'kitchen_photos', 'laundry_photos', 'bathroom_photos', 'bedroom_photos', 'interior_photos', 'basement_photos', 'crawl_photos', 'plumbing_photos', 'heating_photos', 'living_room_photos', 'dining_room_photos'] read_only_fields = ['report_uuid'] This serializer is for generating the entirety of the inspection report itself. Is used to pull together all of the other serializers into one serializer. class InspectionReportSerializer(serializers.ModelSerializer): """Serializer for inspection report model.""" report_details = ReportDetailsSerializer( many=False, required=True) overview = OverviewSerializer(many=False, required=False) summary = SummarySerializer(many=False, required=False) receipt_invoice = ReceiptInvoiceSerializer( many=False, required=False) photos = PhotosSerializer(many=False, required=False) grounds = GroundsSerializer(many=False, required=False) roof = RoofSerializer(many=False, required=False) exterior = ExteriorSerializer(many=False, required=False) garage = GarageCarportSerializer(many=False, required=False) kitchen = KitchenSerializer(many=False, required=False) laundry = LaundrySerializer(many=False, required=False) bathroom = BathroomSerializer(many=False, required=False) bedrooms = BedroomSerializer(many=True, required=False) interior = InteriorSerializer(many=False, required=False) basement = BasementSerializer(many=False, required=False) crawlspace = CrawlSpaceSerializer(many=False, required=False) plumbing = PlumbingSerializer(many=False, required=False) waterheater = WaterHeaterSerializer(many=False, required=False) heatingsystem = HeatingSystemSerializer(many=False, required=False) furnace = FurnaceSerializer(many=False, required=False) boiler = BoilerSerializer(many=False, required=False) electricalcoolingsystems = ElectricalCoolingSystemsSerializer( … -
ModuleNotFoundError: No module named 'material'
python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\ROG\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1052, in _bootstrap_inner self.run() File "C:\Users\ROG\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 989, in run self._target(*self.args, **self.kwargs) File "C:\Users\ROG\OneDrive\Bureau\iblogs\venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ROG\OneDrive\Bureau\iblogs\venv\Lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\ROG\OneDrive\Bureau\iblogs\venv\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise exception[1] File "C:\Users\ROG\OneDrive\Bureau\iblogs\venv\Lib\site-packages\django\core\management_init.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\ROG\OneDrive\Bureau\iblogs\venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ROG\OneDrive\Bureau\iblogs\venv\Lib\site-packages\django_init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ROG\OneDrive\Bureau\iblogs\venv\Lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ROG\OneDrive\Bureau\iblogs\venv\Lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Users\ROG\AppData\Local\Programs\Python\Python312\Lib\importlib_init.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ p>", line 1318, in _find_and_load_unlocked ModuleNotFoundError: No module named 'material' nothing ?!!! nothing ?!!! -
Django-HTMX: on form validation error render to diferent target
I'm starting to mess around with HTMX and found a wall I haven't been able to climb on my own: I used HTMX to manage the creation/edition form and post the data to the corresponding view and update the item list. It works marvelously. But when the form raises Validation Errors the list is replaced by the form html. Is there a way to set a different render target for when the form has validation errors? <div class="modal-header"> <h5 class="modal-title" id="Object_ModalLabel">{% if object %}Edit{% else %}Create{% endif %} Object</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form hx-post="{{targetURL}}" hx-target="#Object_List" method="POST"> {% csrf_token %} {{form.as_div}} <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save</button> </div> </form> </div> from django.views.generic import TemplateView, ListView, CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from project.mixins import HtmxRequiredMixin, ResponsePathMixin from .models import Object_ from .forms import Object_Form # Create your views here. class Object_Main(TemplateView): template_name = 'Main.html' class Object_List(HtmxRequiredMixin, ListView): model = Object_ template_name = 'Object_List.html' queryset = Object_.objects.all().order_by('as_group','as_name') class Object_Create(ResponsePathMixin, HtmxRequiredMixin, CreateView): template_name = 'Object_Form.html' model = Object_ form_class = Object_Form success_url = reverse_lazy('list-object') class Object_Update(ResponsePathMixin, HtmxRequiredMixin, UpdateView): template_name = 'Object_Form.html' model = Object_ form_class = Object_Form success_url = reverse_lazy('list-object') Those are … -
Access django translated fields in values
I have a model with translate fields class Certificate(TranslatableModel, BaseModel): enabled = models.BooleanField(default=True) translations = TranslatedFields( certificate_name=models.CharField(max_length=255, blank=True, default=""), description=models.CharField(max_length=400, blank=True, default=""), ) type = models.CharField(max_length=30, null=False, blank=False) When I attempt to query it and get the certificate_name in .values(): certificates_values_list = ( Certificate.objects.filter( enabled=True ) .values( "id", "type", "certificate_name", ) ) It returns an error that the certificate_name is not exists for the certificated model. I also tried: certificates_values_list = ( Certificate.objects.filter( enabled=True ) .values( "id", "type", "translations__certificate_name", ) ) But it returns duplicated instances one for each available translation so that the same certificate id got duplicated twice/thrice based on the available translation. What I need is to get only the objects with the translated fields according to the current language and the fallback if no objects related to the current language. How can I implement this? -
Login with Django doesn't work (?csrfmiddlewaretoken)
I'm working on Django project and I'm working on login form. I have problem, login doesn't go through, page is refreshed and not logged in. I have created login form but I wanted to move from (this part has worked) <form action="{% url 'learning_app:login' %}" method="post"> {{ form.as_p }} {% csrf_token %} <input type="hidden" name="next" value="{{ next }}" /> <p><input type="submit" value="Log-in"></p> </form> I wanted to remove {{ form.as_p }} to apply styling of my liking, and I have done it like this... <!-- Form Input --> <form action="{% url 'learning_app:login' %}" method="post"> {% csrf_token %} <!-- Form Input --> <div class="col-md-12"> <p class="p-sm input-header">Username</p> <input class="form-control email" type="username" name="username"> </div> <!-- Form Input --> <div class="col-md-12"> <p class="p-sm input-header">Password</p> <div class="wrap-input"> <span class="btn-show-pass ico-20"><span class="flaticon-visibility eye-pass"></span></span> <input class="form-control password" type="password" name="password"> </div> </div> <!-- Form Submit Button --> <div class="col-md-12"> <button type="submit" class="btn btn--theme hover--theme submit">Log In</button> </div> </form> this is forms.py class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) This is urls.py app_name = 'learning_app' urlpatterns = [ #home path('', views.home, name='home'), # login / logout urls path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), #dashboard path('dashboard/', views.dashboard, name='dashboard'), ] Also, I have added this to settings.py LOGIN_REDIRECT_URL = 'learning_app:dashboard' … -
Django no such column error while using User
from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) sql look like that CREATE TABLE "blog_post" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(100) NOT NULL, "content" text NOT NULL, "date_posted" datetime NOT NULL, "author_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED); CREATE INDEX "blog_post_author_id_dd7a8485" ON "blog_post" ("author_id"); COMMIT; If i write in shell Post.objects.all() i get this error django.db.utils.OperationalError: no such column: blog_post.author_id i tried deleting migrations folder and doing it again but that didnt work -
Django: No file was submitted. Check the encoding type on the form
I'm trying to implement multiple upload in my Django project. After doing similar as the answer to this question, I get No file was submitted. Check the encoding type on the form. form error on submit(self.errors == <ul class="errorlist"><li>image<ul class="errorlist"><li>No file was submitted. Check the encoding type on the form.</li></ul></li></ul>). What could be the problem? Could you help me please? My models.py: from PIL import Image as I class Galery(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) description = models.TextField(blank=True) def __str__(self): return self.user.userprofile.username + " - " + self.description class Image(models.Model): galery = models.ForeignKey(Galery, on_delete=models.CASCADE) image = models.ImageField(upload_to='photos', blank=True, null=True) def save(self, *args, **kwargs): img = I.open(self.image.name) img.resize(size=(300, 300)) img.save(self.image.name) return super(Image, self).save(*args, **kwargs) My forms.py: class CustomFileInput(forms.ClearableFileInput): allow_multiple_selected = True class AddPhotoForm(forms.ModelForm): description = forms.CharField(widget=forms.Textarea(), required=False) class Meta: model = Galery fields = ['description'] def save(self, commit=True): if commit: post = Galery.objects.create( user=self.instance, description=self.cleaned_data['description'] ) return post class AddImagesForm(AddPhotoForm): image = forms.FileField(widget=CustomFileInput(attrs={'multiple': True}), required=True) class Meta(AddPhotoForm.Meta): fields = AddPhotoForm.Meta.fields + ['image'] My views.py: class AddPhotoView(CreateView): template_name = 'add-photo.html' form_class = AddImagesForm success_url = 'my-space' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, context={'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES, instance=request.user) photos = request.FILES.getlist('image') if … -
<div> tag closing prematurely in django template
I'm having some problems with my html page in django This is the part of the page im having problem with : <form method="post" action=""> <div data-prefill-targets-for="1"> {% csrf_token %} {% for group in grouped_fields %} <tr> {% cycle 'bgcolor1' 'bgcolor2' as row_color silent %} {% for field in group reversed%} {% cycle 'bgcolor1' 'bgcolor2' as cell_color silent %} {% if forloop.first %} <td class="w-12 bigcell {{ row_color }}"> {{ field }} </td> {% else %} <td class="w-11 text-center {{ cell_color }}"> {{ field }} <br> <span>xx</span> </td> {% if forloop.last %} <td class="w-12 bigcell {{ row_color }}">اول</td> {% endif %} {% endif %} {% endfor %} </tr> {% endfor %} </tbody> </table> <br> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> as you can see I have opened and then closed the div at last line just before But in page view : <div data-prefill-targets-for="1"> <input type="hidden" name="csrfmiddlewaretoken" value="2VEsmoNuXje9U9ie4aXGo74ObmD6d6I0WKGSg845XaObSYlTKz9qrkWQrFejAFkB"> </div> it closes itself right after csrf token and doesnt contain rest of my form. this is driving me crazy I dont understand where I went wrong. just FYI this is the only JS code I have running on my page : function handlePrefillForBoundTarget(evt) { const targetRoot = this; const emptyPrefillTarget = … -
Django connection to Postgres in Docker failed
I'm using macOS, building a Django app with Postgres and I want to containerise it with Docker. I have following files: Dockerfile: FROM python:3.11 WORKDIR /medicin_api COPY requirements.txt . RUN pip install -r requirements.txt COPY . . CMD ["python3", "./manage.py", "runserver", "8001"] docker-compose.yaml: version: latest services: db_api: image: postgres:16 restart: always container_name: db_api ports: - "5433:5433" environment: - POSTGRES_USER=api_user - POSTGRES_DB=medicin_patients - POSTGRES_PASSWORD=Baz#Dan&Api! volumes: - postgres:/data/postgres healthcheck: test: ["CMD-SHELL", "pg_isready -U api_user -d medicin_patients"] interval: 5s timeout: 2s retries: 10 api: container_name: api build: . command: python manage.py runserver 0.0.0.0:8001 volumes: - .:/api_volume ports: - "8001:8001" depends_on: db_api: condition: service_healthy volumes: postgres: PostgreSQL setup in django settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'medicin_patients', 'USER': 'api_user', 'PASSWORD': 'Baz#Dan&Api!', 'HOST': 'db_api', 'PORT': '5433' } } When I run the command: docker-compose up -d --build I'm getting two images & containers, where: db_api container is running properly with PostgreSQL database and I can access it via CLI api container is running however it throws me below error which I cannot solve: 2023-12-10 12:32:25 Watching for file changes with StatReloader 2023-12-10 12:32:25 Exception in thread django-main-thread: 2023-12-10 12:32:25 Traceback (most recent call last): 2023-12-10 12:32:25 File "/usr/local/lib/python3.11/site-packages/django/db/backends/base/base.py", line 275, in ensure_connection … -
[Learning map Asking]If I want to be an advanced back-end Web-developer in Python, What should I do?
I am a college student majoring in computer science. My existing knowledges includes foundational understanding of data structures and algorithms (proficient in basic tree structures, graph algorithms, sorting, and search algorithms). basic knowledge of computer organization principles fundamental understanding of TCP/IP (familiar with the main protocols in the 4'layer model, and can provide a general description of their operations). In terms of projects, I have worked on some simple toy projects using C, Java, and Python. Currently, my goal is **to become **a Python backend developer, utilizing frameworks such as Django and Flask. But I has only 5 hours/day in 6 mouths. So I want to find a good way to gain the ability. What level of expertise should I aim for, and what resources, learning paths, and open-source projects do you recommend? Or is it possible? THANKS VERY MUCH! -
Using With template tag in django
I have this code : {% for group in grouped_fields %} <tr> {% if forloop.counter0|divisibleby:2 %} {% with 'bgcolor2' as row_color %} {% else %} {% with 'bgcolor1' as row_color %} {% endif %} {% for field in group %} {% if forloop.first %} <td class="w-12 bigcell {{ row_color }}"> <input maxlength="1" size="1" class="text-center bg-white"> </td> {% else %} {% if forloop.counter0|add:forloop.parentloop.counter0|divisibleby:2 %} {% with 'bgcolor2' as cell_color %} {% else %} {% with 'bgcolor1' as cell_color %} {% endif %} <td class="w-11 text-center {{ cell_color }}"> <input class="text-center" size="4" placeholder="yy"> <br> <span>xx</span> </td> {% if forloop.last and forloop.parentloop.last %} <td class="w-12 bigcell {{ row_color }}">اول</td> {% endif %} {% endif %} {% endfor %} </tr> {% endfor %} that I copied from ChatGPT but it seems it does not include correct form of with. There should be an {%endwith%} somewhere in the code so there wont be an error. I cant figureout how to use the template tag correctly. can someone aid me with this -
social login expects to lead to questions.html via django urlpatterns, instead leads to home page
social login expects to lead to questions.html I am currently learning urlpatterns with django. I expect that when I click on login via google, I will be redirected to questions.html Instead it leads to the home page. debugging steps: I have tried adjusting the hyperlink in the templates/index.html template to point to templates/questions.html <a href="{% provider_login_url 'google' %}?next=/questions.html">Login With Google</a> I have adjusted the user/urls.py file in users app (manages social login) to point to questions.html #users/urls.py urlpatterns = [ path("", views.home), # home page path("questions/", views.logintoquestions), # questions page [...] I have ensured the view function logintoquestions is defined in users/views.py #users/views.py [...] def logintoquestions(request): return redirect("questions.html") migrations are all up to date and the urlpatterns I have tried changing views.home to views.logintoquestions in users/urls.py #users/urls.py urlpatterns = [ path("", views.logintoquestions), # home page path("questions/", views.logintoquestions), # questions page [...] page now redirects to questions.html immediately which is not what I want - I want specifically it to be used when the user logs in via google. Reverted step 4 so that "" is views.home #users/views.py def home(request): return render(request, "index.html") this successfully renders the "" page as index.html, closer to what I want. I have tried updating the … -
how to avoid runserver freeze when database connection error in django
I am trying to intentionally create django.db.utils.OperationalError to make a functionality where the server can handle the requests regardless of improper connection to database, but after running py manage.py runserver command, the terminal is logging the following messages and froze, if I try to send a request using postman, the server is not accepting those requests. I tried to create a file called runserver.py in app_name.management.commands and it looks like this runserver.py from django.core.management.commands.runserver import Command as RunserverCommand from django.db import connections from django.db.utils import OperationalError import logging logger = logging.getLogger(__name__) class Command(RunserverCommand): def handle(self, *args, **options): self.check_database_connection() super().handle(*args, **options) def check_database_connection(self): try: with connections['default'].cursor(): logger.info("Database connection successful") except OperationalError as e: logger.error("Database connection error: %s", e) logger.error("Skipping database-related initialization steps.") when I run py manage.py runserver it is showing above logs, but then the server showing again the default messages and got froze again (.venv) PS C:\Users\vanum\Desktop\ACADEMICS\Web Development\letsbloom\server> py manage.py runserver Database connection error: connection to server at "localhost" (::1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP … -
CORS issue after migrating to HTTPS with Cloudflare
I recently migrated my Django project to HTTPS using Cloudflare. While it worked flawlessly with HTTP, I'm now encountering CSRF verification failed. Request aborted. issues after the migration. When I tried logging into the admin panel CORS_ALLOW_CREDENTIALS = True ALLOW_ALL_ORIGINS = True CORS_ALLOWED_ORIGINS = [ "https://example-domain.live", "https://www.example-domain.live", "www.example-domain.live ] CORS_CSRF_COOKIE_SECURE = True USE_X_FORWARDED_HOST = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') -
why they call ASGI a server while they say it is not in django?
i am studying Channels in Django Frameworke. after that i went to study ASGI specification , but i got confused of : First they say that the ASGI is a server in here. after that they say that the ASGI uses the Daphne as the main server to work in here. now is the ASGI middle ware uses server in it or it is server or what does daphne do in ASGI. second what do they mean by application in ASGI is the application above the consumer that will work after the connection is came into it through a WebSocket Protocol ? i have read a lot and read the whole document but in technology every time there is something missing. thanks -
Slug generator function always return instance.slug = None and creates a new slug even though a slug alredy exist
I have a function for creating slugs for my model Property and everything works fine, expect for whenever I edit/update something which then leads to that the slug variable gets updated as well even though a value exist for the slug variable. My model is called Property and contains some variables: class Property(models.Model): address = models.CharField(max_length=200) city = models.CharField(max_length=200) slug = models.SlugField(max_length=250, null=True, blank=True) I have a pre_save function: @receiver(pre_save, sender=Property) def slug_generator(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) In utils.py: def random_string_generator(size=10, chars=string.digits): return ''.join(random.choice(chars) for _ in range(size)) def unique_slug_generator(instance, new_slug=None): """ This is for a Django project and it assumes your instance has a model with a slug field and a city/address character (char) field. """ if new_slug is not None: slug = new_slug else: randstr=random_string_generator(size=4) slug = slugify(instance.city +"-"+ instance.address + "-" + randstr) Klass = instance.__class__ qs_exists = Klass.objects.filter(slug=slug).exists() if qs_exists: new_slug = "{slug}-{randstr}".format( slug=slug, randstr=random_string_generator(size=4) ) return unique_slug_generator(instance, new_slug=new_slug) return slug Whenever I update a property object I see that instance.slug is always None. So the below part always returns None and unique_slug_generator gets executed. if not instance.slug: instance.slug = unique_slug_generator(instance) Why is it returning None when a slug already exist? … -
"Post / HTTP/1.1" 400 78 Bad Request for POST requst from React to Django
I am trying to connect React js with Django backend and trying to send information from the form with 2 fields "name" and "description" to django. NewSpace.js function NewSpace() { const navigate = useNavigate(); const { mutate } = useMutation({ mutationFn: createNewSpace, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["events"] }); navigate("/events"); }, }); function handleSubmit(formData) { mutate({ event: formData }); } return ( <Modal> <EventForm onuubmit={handleSubmit}> <Link to="../" className="button-text"> Cancel </Link> <button type="submit" className="button"> Create </button> </EventForm> </Modal> ); } export default NewSpace; EventForm.js export default function EventForm({ onuubmit, children }) { function handleSubmit(event) { event.preventDefault(); const formData = new FormData(event.target); const data = Object.fromEntries(formData); onuubmit(data); } return ( <form id="event-form" onSubmit={handleSubmit}> <p className="control"> <label htmlFor="name">Name</label> <input type="text" id="name" name="name" /> </p> <p className="control"> <label htmlFor="description">Description</label> <textarea id="description" name="description" /> </p> <p className="form-actions">{children}</p> </form> ); } I have a POST view where i am trying to get the value and save it. def post(self,request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) But i am recieving below error Bad Request: / [10/Dec/2023 11:19:35] "POST / HTTP/1.1" 400 78 I am really new to both django and react, not sure wheather the error is in the backend or the front end. Please … -
Setup web server for django backend: Nginx and Gunicorn configuration before database migration
Is it possible to setup Nginx and Gunicorn on my web server before executing "python manage.py migrate", since my database server is not ready yet? Chatgpt recommended me to execute first the migration and then the configuration of Nginx and Gunicorn. So I'm unsure if I can proceed without any problems -
Django + Cloud Firestore CRED not working - FileNotFoundError: [Errno 2] No such file or directory // NameError: name 'database' is not defined
Anyone familiar with Django and Firestore? I would highly appreciate help. I'm troubleshooting an Error for hours and I guess I'm not able to fix it. It somehow can't find my cred Certificate altough its 100% located at the given path. XXX = censored firebase=pyrebase.initialize_app(config) authe = firebase.auth() cred = credentials.Certificate("G:\Python Programme\Keys\XXX.json") firebase_admin.initialize_app(cred, {"https://XXX-default-rtdb.europe-west1.firebasedatabase.app"}) database = firestore.client() Now the Error is: FileNotFoundError: [Errno 2] No such file or directory: 'G:\Python Programme\Keys\XXX.json' Now, the weird thing is if I create a try except to see the actual error it works without an Error but I do get a Problem when actually writing into the db: try: cred = credentials.Certificate("G:\Python Programme\Keys\XXX.json") firebase_admin.initialize_app(cred, {"https://XXX-default-rtdb.europe-west1.firebasedatabase.app"}) database = firestore.client() except BaseException as e: print("Error ist: ") print(e) NameError: name 'database' is not defined Django 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) except: message="User exists already - please sign in." return render(request, "signUp.html", {"messg":message}) isBusinessClient=False uid = user['localId'] data = {"name":name, "email":email, "isBusinessClient": isBusinessClient,} #database.child("users").child(uid).child("details").set(data) alter Code doc_ref=database.collection('User').document() doc_ref.set(data) return render(request, "welcome.html", {"e":email}) I was expecting an Error when using try except. I was expecting the view to acutally write into the firestore cloud. -
Unable to open the remote html file in JetBrains client
I'm using JetBrains Client 2023.3 RC. I have django html templates in my project. When I try to open them, the JetBrains client displays the message "Unable to open the remote file". Other files open without problems. enter image description here I have to open these html files in other editors, but sometimes I need to debug them. I don’t know if this is important or not, but for remote development I use WSL, which has Ubuntu 22.04 installed. -
how to solve this page isnt working now in django
i am doing a project in django,and im half way there with login page. and when i run my server and route to logout/ page, the pageenter image description here isnt working[enterenter image description here image description here](https://i.stack.imgur.com/zRQ7z.png) im stuck here for a day with this -
why tests.py Task matching query does not exist?
ERROR: test_task_check_success (tasks.tests.TaskCheckTestCase.test_task_check_success) Traceback (most recent call last): File "C:\Users\gns03\OneDrive\바탕 화면\사전과제\tasks\tests.py", line 119, in test_task_check_success response = self.client.get(self.url, params=self.data1, **header, format='json') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\test.py", line 289, in get response = super().get(path, data=data, **extra) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\test.py", line 206, in get return self.generic('GET', path, **r) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\test.py", line 234, in generic return super().generic( ^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\test\client.py", line 609, in generic return self.request(**r) ^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\test.py", line 286, in request return super().request(**kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\test.py", line 238, in request request = super().request(**kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\test\client.py", line 891, in request self.check_exception(response) File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\test\client.py", line 738, in check_exception raise exc_value File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\OneDrive\바탕 화면\사전과제\tasks\views.py", line 69, in get task_instance = Task.objects.get(id=request.data.get('task')) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File … -
Firebase settings match fcm-django and android app
I try implement push notifications from drf. I did everything with fcm-djabgo documentations and add firebase settings to my project, call test notification from django admin, but still got fell sending: A message failed to send. 1 device was marked as inactive. Is android token enough? Or I have to add some firebase settings to add permissions for notifications to android app? I could not find any information -
Connect multiple Django web applications to a single MySQL database
In order to save costs (I have limited funds at the moment), I hope to connect multiple Django web applications (or one or two with Flask) up to a single MySQL database online. Is this possible? Will it cause problems with the "sessions" tables? Will I need to add additional code to distinguish different applications? -
Django ArrayAgg is returning values in sorted order don't want reordering
So I'm using Django's ArrayAgg, to get array of. Consider below example: Likes = Posts.objects.all().annotate(like_id = ArrayAgg('like__id', distinct=True), like_name = ArrayAgg('like__name', distinct=True) Now, because it is sorting ArrayAgg, hence when I'm trying to match like_id with like_name, its mismatching because both like_id and like_name are returned as sorted by Django. How to tell Django to not sort them. Please help!