Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hosting for free without credit card?
is there any web hosting that is atleast has free trial and without a credit card upon hosting. I've tried Heroku but it required credit card upon creating a webapp. The singup is free thou -
my django project works well when deployed on heroku, but it goes down on docker
when deploing my project on heroku with 125 mb ram , with 7$/month it works perfect, and when deploing on docker with server 16 ram and 6 vcpu, it works , buut every 15 or 30 minutes it is being like down , but itsnot . no error in logs, no error on containers log , I don't know where is the roblem is ? this is Dockerfile FROM python:3.10.10-slim-buster ENV PYTHONUNBUFFERED=1 RUN apt-get update && apt-get -y install libpq-dev gcc && pip install psycopg2 WORKDIR /django COPY requirements.text requirements.text COPY . . RUN pip3 install -r requirements.text and this is docker-compose version: "3.9" services: # Django Application app: build: . volumes: - .:/django ports: - 8000:8000 image: app:django restart: always container_name: django_app command: python manage.py runserver 0.0.0.0:8000 depends_on: - db # Database Postgres db: image: postgres restart: always volumes: - .postgres_data:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres container_name: postgres_db volumes: postgres_data: no error on logs and at the moment that server goes down on browsers , but containers still working and without any error , this is resources , any help ?! enter image description here -
Why is my Django app loading CSS from another app no matter what I change in any file?
This is quite the unique problem and I may be doing something completely dumb. I am designing a webapp for job information, payroll, expenses, etc. for a mechanical contractor as my first large project. I have designed a calculator and a todo list with login in the past and never had this problem. I have created two apps so far in this project: login and tickets. login takes care of the homepage and login while tickets makes a list of all service reports with details, displays them, and will soon be able to order/search them once i get this stupid problem fixed. No matter what I change in my tickets app's base.html, the ticket app's css/static is inheriting from the login app's css as shown by get requests. hard refresh does nothing but keep showing "static/login/style.css." I feel my tickets templates are inheriting from the login app's base.html, but I don't know why... STATICFILES_DIRS won't seem to help me here and my STATIC_URL is the default 'static/.' I feel like that could be the problem but I don't know. Any help would be greatly appreciated, thank you Lucas -
convert html to pdf using django
I try to convet html with tailwind style to pdf in django and I use many library like weasyprint, pdfkit and xhtml2pdf but the style doesn't apply so there any solution for this issue -
Image uploading to the Media directory but not showing in web browser in Django
So I am working on this project and I am trying to upload a picture using the Python Web Framework Django. I have configured the following Settings Project Url When i upload the picture it goes to my media directory but doesnt show up in the browser. I'll tag images of my code for the views, url, html and settings The images below show the above mentioned your textMy HTML your textMy views.py your textMy settings.py your textMY project urls.py I have configured everything following the django documentation but when i upload the file this is what i get enter image description here Also I have installed Pillow and all other dependencies.`` -
how can i create a football fantasy website?
I'm trying to work on my project 'creating a football fantasy website for Europe's top five leagues' How can I go about it? I've gotten the ui already but I don't know how to go about it on the backend and part of the frontend too -
Decode django HttpResponse
I am working on calendar view on my project. But I met a problem with not-latin symbols I tried to transfer data to script in template and it worked good, but only with latin symbols. I used HttpResponse like view.py events = [] # place holder for event in user_events: temp = {"title" : str(event.title).encode('utf-8').decode('utf-8'), "start": str(event.startDate)[0:-6], "end": str(event.endDate)[0:-6]} events.append(temp) events.append(',') response = HttpResponse(events, content_type='text/html; charset=utf-8') but i got this after HttpResponse instead of this What i need to do? probably you know other ways to to transfer code-like data to templates? -
What is the equivalent of following query in Django python?
SELECT REPLACE(field1, pattern, 'desk' ), REPLACE(field2, pattern, 'desk') FROM table_name WHERE field1 LIKE pattern OR field2 LIKE pattern; The following is my model. How can I code above sql in django python? class news(models.Model): dbemail = models.CharField(max_length=100) dbsubject = models.CharField(max_length=300) dbdetail = models.CharField(max_length=5000) dbimage = models.CharField(max_length=100) dbdatetime = models.DateTimeField(auto_now_add=True) def __str__(self): return "Email: " + self.dbemail + " | Subject: " + self.dbsubject + " | datetime: " + str(self.dbdatetime) I want to query on subject and detail and replace the founded text with another text This is what I did but it is not doing the job: usernews = news.objects.filter(dbsubject__contains=search).order_by('-dbdatetime').values() -
Django Return Info Message If Database Unavailable
I have Django set up split database mode, with default being the write-primary, and replica1 being a read-only replica. I have routers enabled in Django settings so that writes go to the default db and db_for_read returns the replica1 database. However, when the read replica is down, the server still runs. But requests spin forever and eventually timeout. Is there a way to detect when the database is down, and if so, return an informational response instead of just spinning forever. Maybe a middleware to check the connection or something in the view itself? We don't want to allow read fallback on the primary database. -
Serializing with Django
I am getting very weird behaviour during serialization when retrieving data from Database during GET request. The idea is to get the following information: municipality_id (included in municipality table) municipality_name(included in municipality table) total_population (included in demographics table which is connected to community table and associated with a municipality) municipality_distance (included in municipalityDistance table) I am posting this question as a self check to confirm I have everything I need and to open the analysis on this. Because the highest hierarchy table is Community, so I created hybrid properties to get the above information (Not sure if this is the best approach). The following sections are the models: general.py: class Municipality(models.Model): area_id = models.IntegerField(null=True) name = models.CharField(max_length=127) project.py: class MunicipalityDistance(models.Model): municipality_id = models.ForeignKey(Municipality, on_delete=models.SET_NULL, db_column="municipality_id", null=True) municipality_distance = models.DecimalField(max_digits=16, decimal_places=4, blank=False, null=False) @property def name(self): return self.municipality_id.name class Project(models.Model): project_name = models.TextField(blank=True, null=True) municipality = models.ForeignKey('Municipality', on_delete=models.SET_NULL, blank=True, null=True) nearest_municipalities = models.ManyToManyField(MunicipalityDistance, db_column="nearest_municipalities", blank=True, null=True) class Meta: ordering = ("id", ) demographics.py: class Demographics(models.Model): census_subdivision_id = models.IntegerField(primary_key=True, null=False, blank=False) census_subdivision_name = models.CharField(max_length=127) pop_total = models.IntegerField(null=True) class Meta: ordering = ("census_subdivision_id", ) community.py: class Community(models.Model): place_id = models.CharField(null=True, blank=True, max_length=255, unique=True) place_name = models.CharField(null=True, blank=True, max_length=255) census_subdivision = models.ForeignKey('Demographics', null=True, db_column="census_subdivision_id", … -
unknown shorthand flag: 'r' in -rm
docker-compose run -rm app sh -c "python manage.py startapp core" firstly this command is working wiht -rm flag but not it is showing "unknown shorthand flag: 'r' in -rm" Error i am trying to solve this proble but unable to find something -
Unable to add Styling for Django Template
I have created a HTML page using Django,where I have four different categories of forms named as Live, Report, Planning and Old. These four categories of forms are connected with SQL server to show various sub-forms under these categories. I can get all the forms here and my below code is working fine. The name of the Page is "FORM TRACKING APP".I have added two more logics here which shows the different user names when they logged in and a logout link. Here the user name and logout is in the top right of the page, also below that I have link which creates new form. About the styling I am facing few issues that I want to do. 1.I want to create a fixed Navbar where it shows the page name in the middle and shows user name in the right side of the bar with an image and also with the logout link. 2.Want to replace link for Add new form with a button. 3.Want to create borders for four categories of forms. My code is given below: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Homepage</title> </head> <body> <h1><b><center><u>FORM TRACKING APP</u></center></b></h1> … -
Python: how to schedule a task to happen after 1 hour?
I am creating a user registration that requires an activation code. I want the activation code to expire after 1 hour, so I did this: def register(request): form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.data) if form.is_valid(): email = request.POST.get('email') password = request.POST.get('password') user = get_user_model() user = user_manager.create_user(email=email, password=password) # Generate an activation code and store it in the database code = generate_activation_code() # activation = Activations.objects.create(user=12, code=code) # Schedule the activation code for deletion after 1 hour schedule_activation_code_deletion(user, code) # schedule_activation_code_deletion(user, code) # Send the activation code to the user's email address subject = "Your verification code" message = f"Your verification code is {code}" send_email(subject, message, settings.EMAIL_HOST_USER, email) return Response('User created.') return Response(status=400) def schedule_activation_code_deletion(user_id, code): queue = django_rq.get_queue('default') queue.enqueue_in(datetime.timedelta(minutes=1), test) With this code I get Error while reading from localhost:5432 : (10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None) Is there any other library that works? -
Django crash when installing Tensorflow
I want to use a tensorflow model in a django API deployed with docker Problem : Importing tensorflow in API Django will stop the server view.py: from rest_framework.parsers import MultiPartParser from rest_framework.response import Response from rest_framework.views import APIView from django.http import JsonResponse import random import numpy as np import tensorflow as tf if I comment the tensorflow line it works but if I don't my docker will stop with the following output : terminal: Attaching to web-1 web-1 | Watching for file changes with StatReloader web-1 | Performing system checks... web-1 | web-1 exited with code 252 OS : Ubuntu 22.04 ( VM ) Dockerfile : FROM tensorflow/tensorflow ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ I also tried FROM python:3.9 and RUN pip install tensorflow docker-compose.yml version: '3.9' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 --verbosity 2 volumes: - .:/app ports: - "8000:8000" requirements.txt Django==4.2.1 djangorestframework==3.14.0 pandas==2.0.1 numpy==1.24.3 django-cors-headers==3.14.0 tqdm==4.62.3 I am really stuck with this. I hope I did not forget any critical info if so feel free to ask. I would appreciate any help I probably miss something . Thank you a lot and … -
Django - Paython: TypeError at /news news() got an unexpected keyword argument 'dbemail'
Here is my model: class news(models.Model): dbemail = models.CharField(max_length=100) dbsubject = models.CharField(max_length=300) dbdetail = models.CharField(max_length=5000) dbimage = models.CharField(max_length=100) dbdatetime = models.DateTimeField(auto_now_add=True) def __str__(self): return "Email: " + self.dbemail + " | Subject: " + self.dbsubject + " | datetime: " + self.dbdatetime Here is a function in my view that is responsible for handling post method for the news: def news(request): if 'email' in request.session: email = request.session['email'] if request.method == 'POST' and request.FILES['newsimage']: myfile = request.FILES['newsimage'] fs = FileSystemStorage(location='newsimages/') filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) newsinfo = newsForm(request.POST) if newsinfo.is_valid(): subject = newsinfo.cleaned_data['subject'] detail = newsinfo.cleaned_data['detail'] newsData = news(dbemail = email, dbsubject = subject, dbdetail = detail, dbimage = uploaded_file_url) newsData.save() message = "News has been added" form = newsForm() return render(request, 'news.html', { 'myform': form, 'message': message }) else: form = newsForm() return render(request, 'news.html', {'myform': form}) else: request.session['profileError'] = "You have to sign up or log in first!" return redirect('login') Error is on this line: newsData = news(dbemail = email, dbsubject = subject, dbdetail = detail, dbimage = uploaded_file_url) This is the error detail: TypeError at /news news() got an unexpected keyword argument 'dbemail' Request Method: POST Request URL: http://localhost:8000/news Django Version: 4.2.1 Exception Type: TypeError … -
Exclude duplicate elements with lower priority (Django)
I have the following model: class Action(BaseModel): action_id = models.IntegerField(unique=True, db_index=True) name = models.CharField(max_length=25) object = models.CharField(max_length=25) priority = models.IntegerField(default=0) Suppose there are two 4 objects: {"action_id":1, "name":"read", "object":"post", "priority":1} {"action_id":2, "name":"write", "object":"post", "priority":2} {"action_id":3, "name":"read", "object":"user", "priority":1} {"action_id":4, "name":"update", "object":"user", "priority":2} How can I filter out objects with the same object value, and leave only those with a priority higher in the duplicate set? [{"action_id":2, "name":"write", "object":"post", "priority":2}, {"action_id":4, "name":"update", "object":"user", "priority":2}] I tried filtering methods with - annotate, Max, Count and filter but duplicates are returned if i filter by priority -
Django: How to add data to 2 tables at the same time
Having the following table models, I would like to write data from the form to 2 tables at the same time. class Order(models.Model): department = models.CharField(max_length=20) responsible = models.CharField(max_length=20) month = models.DecimalField(max_digits=2, decimal_places=0, default=0) year = models.DecimalField(max_digits=4, decimal_places=0, default=0) def __str__(self): return str(self.department) class Article(models.Model): name = models.CharField(max_length=20) description = models.CharField(max_length=20) quantity = models.DecimalField(max_digits=5, decimal_places=0, default=0) order_id = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="Order") comments = description = models.CharField(max_length=200) def __str__(self): return str(self.name) I would like a new order to be created simultaneously when the user adds the first item. Then the user would add articles to this order and the data would be saved in one table. In addition, each item would have to have the ID of the order to which it was assigned. In the case of subsequent articles, there will be no problem, how to add this ID to the first added article? My question is: How to write data to 2 tables at once? -
filter feeds containing a similar hashtag using django-taggi
We have the django-taggi library which is related to the user feed, I need to generate the filter by tags according to the library in an example of the documentation is done in this way. Food.objects.filter(tags__name__in=["delicious"]) [<Food: apple>, <Food: pear>, <Food: plum>] Model Feed: class Feed(UUIDModel, TimeStampedModel, mongo_models.Model, TaggitManager): #Other fields class TaggitManager: hashtags = TaggableManager(through=UUIDTaggedItem) class Meta: abstract = True class UUIDTaggedItem(GenericUUIDTaggedItemBase, TaggedItemBase): pass ViewSet @extend_schema(description="", tags=["feed"]) class FeedViewSet(LPCDRModelViewSet): def _check_required_param(self, param_name): param_value = self.request.query_params.get(param_name) if not param_value: return exceptions.ValidationError( {"error": f"params {param_name} is required"} ) return None def get_queryset(self): if self.action == "feed_hashtag_list": error = self._check_required_param("hashtag") if not error: return Feed.objects.filter(hashtags__name__in=["demo", "red"]) When we want to query or filter by a tag we get the following error: django.core.exceptions.FieldError: Cannot resolve keyword 'hashtags' into field. Choices are: background, background_id, blocked, can_audio, can_be_shared_inside, can_be_shared_outside, can_commentary, can_download, can_duos, can_paste_video, comment_feeds, content, count_shared, created, draft, event, exclusive_adult_content, feed_event, feed_private, feed_type, finish_poll, friends_concrete, friends_concrete_id, friends_except, friends_except_id, id, is_announcement, link, link_external, mediafeed, modified, near, parent, parent_duos, parent_duos_feed, parent_duos_id, parent_feed, parent_id, programed, publish, questionfeed, reactions, reactions_feed_relation, reactions_id, special_announcement, sponsors, sponsors_id, state, state_id, time_to_programed, user, user_id, user_tags, user_tags_id -
Why TrigramSimilarity is not working on postgresql
I want change SearchRank with TrigramSimilarity but i got this error ProgrammingError at /search/ function similarity(character varying, unknown) does not exist LINE 1: ...ows_show"."description", '')), 'B')) AS "search", SIMILARITY... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. My code: def search_content(query: str) -> QuerySet | None: if query: search_vector = SearchVector("name", weight="A") + SearchVector("description", weight="B") shows = ( Show.objects.annotate( search=search_vector, similarity=TrigramSimilarity('name', query), ) .filter(similarity__gt=0.4) .values("id", "name", "baner", "release_date", "search", "similarity") ) movies = ( Movie.objects.annotate( search=search_vector, similarity=TrigramSimilarity('name', query), ) .filter(similarity__gt=0.4) .values("id", "name", "baner", "release_date", "search", "similarity") ) episodes = ( Episode.objects.annotate( search=search_vector, similarity=TrigramSimilarity('name', query), ) .filter(similarity__gt=0.4) .values("id", "name", "baner", "release_date", "search", "similarity") ) qs = shows.union(movies, episodes).order_by("-similarity") return qs else: return None -
CORS error on sending API request via browser from a React pod to a Django pod
I've created a basic Django-React web application, and am trying to deploy it through Kubernetes, on my local system. But, while sending an API request from the frontend to the backend, I'm getting the following message alert on the browser: A server/network error occurred. Looks like CORS might be the problem. Sorry about this - we will get it fixed shortly. I have set up ingress to basically deploy the pods, and to connect them. The alert message looks like the following: On clicking the 'OK', the console logs the following: I have already tried setting the CORS headers in the axios request, as well as setting the Django settings as necessary. Here is the axios request: const baseURL = API_SERVER + '/api/'; // API_SERVER resolves to http://127.0.0.1:8000 const axiosInstance = axios.create({ baseURL: baseURL, timeout: 5000, headers: { Authorization: localStorage.getItem('access_token') ? 'JWT ' + localStorage.getItem('access_token') : null, 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', accept: 'application/json', }, }); And the Django settings.py ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ . . . 'corsheaders', . ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', . . . ] CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1", "http://localhost:3000", "http://kubernetes.docker.internal", ] CORS_ALLOW_CREDENTIALS = False CORS_ORIGIN_ALLOW_ALL = True kubernetes.docker.internal is the URL through which I'm … -
Django-Crontab setting up wrong path in Cron table executables on Elastic Beanstalk
I realised my Cron jobs were not running on my server, so I connected to it and issued a crontab -e command, which output: 0 0 * * * /var/app/venv/staging-LQM1lest/bin/python3 /var/app/staging/manage.py crontab run a1d4c02847fcb8cb1b61b437ec1c399d 0 0 * * * /var/app/venv/staging-LQM1lest/bin/python3 /var/app/staging/manage.py crontab run 7332312af81aa515804fd180d12a2294 The problem is that manage.py is not in the /var/app/staging/ folder, that doesn't exist, but in /var/app/current/. Does anybody know where the staging come from and how can I replace it? I don't manipulate my Cron tab directly, but create my Cron jobs by using Django-Crontab and defining them in settings.py: CRONJOBS = [('0 0 * * *', 'app1.cron.task'), ('0 0 * * *', 'app2.cron.task')] (I don't know if this is anyhow related, but staging is indeed the name of one of my environments.) -
Django-tenants difference between django.db.connection.tenant and request.tenant
I am working on a multitenant Django application using django-tenants library. Getting the current tenant object can be done through one of the two ways: This can be used anywhere: from django.db import connection tenant = connection.tenant This can be used in views.py only where the request object is accessible: tenant = request.tenant So, why we have it added to request while it is globally accessible on the connection object? -
How to restrict a user's rights to click on a url, django
In my app, no anonimus uzer can switch to another profile, he only should know the pers_id. How can I forbid doing this? my views.py: @login_required def home(request): pers_id = request.GET.get('pers_id', None) if pers_id is None: return redirect('/') user_profile = Profile.objects.get(profile_id=pers_id) try: user_memories = Memory.objects.get(profile_id=pers_id) except Memory.DoesNotExist: user_memories = False context = {'memories': user_memories, 'user_profile': user_profile} return render(request, 'home.html', context) def vk_callback(request): try: vk_user = UserSocialAuth.objects.get(provider='vk-oauth2', user=request.user) vk_profile = vk_user.extra_data user_info = UserInfoGetter(vk_profile['access_token']) pers_id, first_name, last_name, photo_url = user_info.get_vk_info() try: user_profile = Profile.objects.get(profile_id=pers_id) except Profile.DoesNotExist: user_profile = Profile.objects.create( profile_id=pers_id, first_name=first_name, last_name=last_name, photo_url=photo_url ) user_profile.first_name = first_name user_profile.last_name = last_name user_profile.photo_url = photo_url user_profile.save() return redirect(f'/home?pers_id={pers_id}') except UserSocialAuth.DoesNotExist: pass return redirect(home) When the user take auntification he redirected to /home?pers_id={pers_id}. if authorized user knows the pers_id he can check antoher profiles. How can i fix it? -
I'm trying to make a searcher but when i send a request from my frontend in react Django doesn't get the data sent
Sorry for my English. When I'm trying to get the data sent in the frontend (its seems its working well because is generating a json with the searchValue) the function in django is not getting the data that i sent, the print(search) return None This is my code in Django: views.py: @csrf_exempt def search_locations(request): search = request.POST.get('search') print(search) results = [] if search: locations = Location.objects.filter(name=search) print(locations) for location in locations: results.append({ 'id': location.id, 'name': location.name, 'latitude': location.latitude, 'longitude': location.longitude }) return JsonResponse(results, safe=False) urls.py: urlpatterns = [ path('locations/', LocationsView.as_view(), name='locations'), path('locations/search/', search_locations, name='search_locations'), path('locations/<int:pk>/', location_detail, name='location_detail'), ] React code: const [searchValue, setSearchValue] = useState(""); const handleSearch = async (event) => { event.preventDefault(); await axios .post("http://127.0.0.1:8000/apilocations/locations/search/", { search: searchValue, }) .then((response) => { setPlaces(response.data); console.log(searchValue) console.log(response) console.log(places) }) .catch((error) => { console.error(error); }); }; When i use the searcher search return None -
Trying to access the other side of a ForeignKey in the django admin display
I'm working off the django tutorial, and I was trying to figure out how to call the other side of a ForeignKey. My models right now are just Question and Choice, and under class Choice right now I have: question = models.ForeignKey(Question, related_name="choice", on_delete=models.CASCADE) (the only change I made from the tutorial was adding related_name) Then when creating class QuestionAdmin, I added "choice" to list_display, hoping to show choice for a question. list_display = ["question_text", "choice", "pub_date", "was_published_recently"] In the tutorial, they do something with another class and "inlines" but I'm trying to keep this simple, and I was hoping I could just treat the related_name as another attribute of the Choice model. I've tried changing the name, and I get different error messages depending on which admin function I'm using (list_display, fields, etc.) but I'm mostly seeing this: TypeError at /admin/polls/question/ Is there a way to just access the choices as a regular attribute? Am I doing something wrong?