Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework invert serializers
In Django, I have in models.py models defined like this : class foo1(models.Model): name = models.CharField(max_length=100) class foo2(models.Model): name = models.CharField(max_length=100) .... foo1 = models.ForeignKey(foo1, on_delete=models.SET_NULL, null=True) class foo3(models.Model): name = models.CharField(max_length=100) .... foo2 = models.ForeignKey(foo2, on_delete=models.SET_NULL, null=True) class foo4(models.Model): name = models.CharField(max_length=100) .... foo3 = models.ForeignKey(foo3, on_delete=models.SET_NULL, null=True) .... and what i'm expecting to get is a json format like this : [ { "id": 1, "name": "test1", "foo2": { "id": 1, "name": "test1", "foo3": { "id": 1, "name": "test1", "foo3": { ... } }, .... ] What I have tried so far, and it gives me the opposite result of what I want, here is my serlialize.py : class NestedFoo1Serializer(serializers.ModelSerializer): class Meta: model = Company fields = '__all__' class Nestedfoo2Serializer(serializers.ModelSerializer): foo1= NestedFoo1Serializer(read_only=True) class Meta: model = Facility fields = '__all__' the resault : [ { "id": 1, "name": "test1", "foo4": { "id": 1, "name": "test1", "foo3": { "id": 1, "name": "test1", "foo2": { ... } }, .... ] and here is my view.py : class TreeView(generics.ListAPIView): serializer_class = NestedFoo4Serializer queryset = foo4.objects.all() -
how can I retrieve a specific JSON data
I want to retrieve a specific data after selecting an option form. When I select I got data in JSON format which I can't separated. I have tried obj.purchase_price but got undefined. my following code provide following data [{"model": "acc.productdetails", "pk": 4, "fields": {"purchase_price": "214.00"}}] I want purchase_price value for my form. Please help me to separate the value. My codes are given bellow In Views def priceFilter(request): product_id = request.GET.get('product_id',None) price = { 'data':serializers.serialize("json",ProductDetails.objects.filter(id=product_id), fields=('purchase_price',)) } return JsonResponse(price) In my page, script <script> $("#id_price").change(function () { var form = $(this).closest("form"); $.ajax({ url: form.attr("data-validate-price-url"), data: form.serialize(), dataType: 'json', success: function (price) { if (price.data) { let obj = price.data ; alert(obj) ; } } }); }); </script> I want to show my data here <input type="text" name="price" class="form-control" id="p_price" required> -
ModuleNotFoundError: No module named 'spyder'
I want to use a crawler project inside Django. I've set up celery and beats correctly but when I use the scraper project inside a Django app gives me the error ModuleNotFound even if I have added it to the setting.py file. The structure of the project is the following: |-- celery.log |-- celerybeat-schedule.db |-- db.sqlite3 |-- manage.py |-- requirements.txt |-- scraper | |-- __init__.py | |-- admin.py | |-- apps.py | |-- migrations | | |-- __init__.py | |-- models.py | |-- spyder | | |-- domain.py | | |-- general.py | | |-- link_finder.py | | `-- spider.py | |-- tasks.py | |-- tests.py | |-- urls.py | `-- views.py |-- src | |-- __init__.py | |-- asgi.py | |-- celery.py | |-- settings.py | |-- urls.py | `-- wsgi.py `-- templates `-- index.html The file scraper/spyder/tasks.py initiates the crawler and has the following code: ... from celery import shared_task import threading from queue import Queue from spyder.spider import Spider from spyder.domain import * from spyder.general import * ... -
Django download file using CBV
How to use Class Based Views eg. TemplateView to display Django template with download links? Clicking the link should start downloading selected file. I already know how to do it with Function Based Views. Also - is it good idea to put filename slug as URL parameter (filename) for GET requests or should I use different method? -
why Django favicon reloads on routing pages? (about SSR)
Hi I'm using Django framework and made a simple web application. But on routing each page, I could see favicon reloads (OR maybe it could be loading html file). So here's the question. Is it correct that favicon reloads itself? Or is it because on routing pages, as page needs to be loaded, favicon looks like loading motion? (But if so I'm so curious because literally I had no single code in some_page.html file even tags...) I also made a simple Next.js web application. But on routing pages, favicon stays still and I couldn't see any loading motions. So does it because when requesting routing on Django application, as it needs to return render('index.html') in views.py file, we see loading motions? I suppose this is because Django runs by SSR (just rendering pages. And even it renders ON REQUESTs), Next.js by SSG (pre-rendering pages). If so, I would much prefer JavaScript to Python... Thank you for reading my question! -
django-rest-passwordreset create and send token manually
reading the [django-rest-passwordreset][1] I have not found a way to create and send the reset_password_token manually, meaning without the use of the endpoint created by the package. Currently I have this implementation: urlpatterns = [ ... url(r'^api/password_reset/', include('django_rest_passwordreset.urls', namespace='password_reset')), ... ] Then when a user requests a password reset I send an email using the Signal provided by the package: @receiver(reset_password_token_created) def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs): """ Handles password reset tokens When a token is created, an e-mail needs to be sent to the user :param reset_password_token: Token Model Object :return: """ # send an e-mail to the user context = { 'email': reset_password_token.user.email, 'reset_password_url': f"{BASE_URL}new-password?token={reset_password_token.key}" } send_reset_pwd_to_sendingblue.delay(context) However, in my case, I want to programmatically create the token and send it to the user without the use of the endpoint meaning the user won't reset their password through the endpoint, rather my application will create the token and send it to the user. How can I go about doing that? [1]: https://pypi.org/project/django-rest-passwordreset/ -
How do I change a model after I ran makemigrations and migrate? Django
I made a model ran all the neccesery migrations commands and I want to add a field and change a field. How do i do that? I thought about changing them in models.py and ran makemigrations and migrate again but I dont know if that somehow ruins them. -
Python can't see environment variables from script
I was invited to collaborate on a Django project and now I need to set it up. I am stuck with setting environment variables. In the given project envparse is used. I was provided an .env file, where items look like export EMAIL="12345" Then i run source .env Supposedly it should be enough to start, but when I run python manage.py runserver It throws an error django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. Seemingly Python/Django somehow can't access environmental variables. I wrote a simple script in the same venv to check it and the script leads to the same result. from envparse import env def checker(environment_variable_to_check: str): print(env(environment_variable_to_check)) if __name__ == '__main__': checker('EMAIL') However, if I use python interpreter with basically the same command, I get the correct result >>> from envparse import env >>> print(env('EMAIL')) 12345 >>> I can't figure out what's wrong with it. I totally understand it's some simple newbie issue, and most probably I will get a bunch of downvotes, but I've already wasted two days trying to figure it out and I need some help. -
I want to complete a simple assignment [closed]
I want to crawl data from https://news.ycombinator.com/. After crawling I only need title, links and total comment number. After that I have to save that in database and show that data on the UI. Please help needed -
import "pyrebase" could not be resolve pylance(reportMissingImports)
Installed pyrebase4 in my system but still unable to import in my view.py even tried "import pyrebase4" still the same error, I followed a youtube tutorial for it I followed the exact same things he/she said can any explain me what is that error and how can I resolve it. from django.http.response import HttpResponse from django.shortcuts import render import pyrebase #here is the error from pyrebase.pyrebase import Database config={ "apiKey": "AIzaSyD4P5ITiUyMlb-A3OmjrgNNeqZ2vMqKTow", "authDomain": "filterflare.firebaseapp.com", "projectId": "filterflare", "storageBucket": "filterflare.appspot.com", "messagingSenderId": "828393456186", "appId": "1:828393456186:web:14b075fb0e9ad519926b03", "measurementId": "G-8W3W2ED4RH" } firebase= pyrebase.initialize_app(config) db=firebase.database() def home(request): test=db.child('name').get().val() return render(request,"html/editorhtml.html", {"testname": test}) def download(request): return render(request,"html/finalimage.html") did I missed something in installed apps? INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
In Django raw query selects all my user twice
I have a raw query in my view: SELECT stressz_profile.id, projekt_id, user_name_id, szerv01b AS szervkult01a FROM stressz_szervezetikultura INNER JOIN stressz_profile WHERE stressz_profile.projekt_id=1 I try to get the data from the db but every time it duplicates the results. It selects my users two times like on the image below and I can't figure it out why. -
Error when installing node-django-hashers
In order to implement password hashing on the server side with nodeJS 14.7.4, we selected node-django-hashers so that it can be implemented the same with django website side, but when installing module, we are recieving the following error. docker build -t auth_api_t1 . [+] Building 102.3s (16/16) FINISHED => [internal] load build definition from Dockerfile 0.3s => => transferring dockerfile: 32B 0.0s => [internal] load .dockerignore 0.3s => => transferring context: 2B 0.0s => [internal] load metadata for docker.io/library/ubuntu:latest 0.0s => [internal] load build context 0.2s => => transferring context: 92B 0.0s => [ 1/12] FROM docker.io/library/ubuntu:latest 0.0s => CACHED [ 2/12] WORKDIR /data 0.0s => CACHED [ 3/12] COPY . /data 0.0s => CACHED [ 4/12] RUN apt update && apt install -y python2 && apt install -y python3 && apt install -y curl && 0.0s => [ 5/12] RUN . "/root/.nvm/nvm.sh" && nvm install --lts 38.0s => [ 6/12] RUN . "/root/.nvm/nvm.sh" && nvm use --lts 5.3s => [ 7/12] RUN . "/root/.nvm/nvm.sh" && nvm alias default v14.7.4 4.3s => [ 8/12] RUN node --version 1.8s => [ 9/12] RUN npm --version 1.2s => [10/12] RUN npm install --global yarn 3.8s => [11/12] RUN echo "run 'yarn install'" … -
Single search bar managing all fields using django-filter and django-tables2 through Jquery
I need to manage the django-table2 using django-filter through jquery. Please help me how can i access this via jquery and how do i pass queryset in django-filter I am having my search box in the following way: where I am passing models in a dynamic way since I am using it in generic purpose. <input type="hidden" name="model_name" value="{{view.class_name}}" id="model_name"> <input type="text" name="search_data" id="search_data" class=" search_data form-control pl-4" placeholder="Search..." value="{{search_key}}"> The script I use $('.search_data').keyup(function(){ var search_key = $.trim($(this).val()); model_name = $('#model_name').val(); url = '/org/' + model_name.toLowerCase() + '/?search_key='+search_key window.location = url }); And here I am using the dynamic List view def generate_views(model_type): friendly = model_type.__name__.lower() app_label = model_type._meta.app_label admin_class = admin.site._registry.get(model_type) if admin_class and not admin_class.form == ModelForm: _form_class = admin_class.form else: _form_class = forms.generate_form(model_type) class ListView( mixins.LoginRequiredMixin, mixins.PermissionRequiredMixin, FilterView, ExportMixin, SingleTableView, ): class_name = model_type.__name__ permission_required = [f'{app_label}.view_{friendly}'] template_name = f'generic/object_list.html' model = model_type filterset_class = filters.generate_filterset(model_type) table_class = tables.generate_table(model_type) table_pagination = { 'per_page': settings.DJANGO_TABLES2_PER_PAGE } def get_context_data(self, **kwargs): context = super(ListView, self).get_context_data(**kwargs) search_key = self.request.GET.get('search_key', '') if search_key: context['search_key'] = search_key return context def get_queryset(self): search_key = self.request.GET.get('search_key', '') fields = filters.build_fields(model_type) queryset = model_type.objects.all() if search_key: for field in fields: lookup = "%s__contains" % field … -
Return context variable along with saved form
I have following class based view which creates a project using form and then returns that created form. class ProjectCreateView(LoginRequiredMixin, CreateView): login_url = "registration:login" model = Project # fields = ['name', 'desc', 'start_date', 'end_date'] template_name = 'project/form.html' form_class = ProjectModelForm def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books context['projectCreated'] = True return context def form_valid(self, form): form.instance.user = self.request.user project_name=form.cleaned_data.get('name') print("Project name-------------+++++++++++"+str(project_name)) namesTaken=Project.objects.values_list('name', flat=True) if project_name in namesTaken: return self.render_to_response(self.get_context_data(form=form,projectNameRepeated=True)) ''' else: context={"projectCreated":True,"saved":super().form_valid(form)} return self.render_to_response(context) ''' #context = {'form':super().form_valid(form)} #form=super().form_valid(form) #return self.render_to_response(self.get_context_data(form=form,datasetNameRepeated=True)) return super().form_valid(form) Now I want to return a context which is ProjectCreated=True. This is context is being return even before the form is submitted and the project is created. But I need to return it after the project has been create because then I will display an alert in my template base.html {% elif DatasetCreated %} <script> displayToast("Dataset","Dataset Created Successfully"); </script> {% endif%} following is url code path('create/', views.ProjectCreateView.as_view(), name='create'), So basically I am looking for a way to return a context when the project is saved in database or after form is successfully submitted. Thanks -
'verbose_name': _('Small screens') NameError: name '_' is not defined
After installation django-responsive2 as django-responsive2, i got following error: 'verbose_name': _('Small screens') NameError: name '_' is not defined -
Converting my Django/Python app from App Engine Standard Environment to Flexible Environment
I am trying to convert my Django/Python app from the Google App Engine Standard Environment to the Flexible environment mainly due to the app becoming slow and was constantly hitting a soft memory limit and suggested I upgrade to a larger instance class. I was already at the highest instance class. My problem is when I try to deploy the build is successful but I keep getting an error when Updating service. "Your deployment has failed to become healthy in the allotted time and therefore was rolled back. If you believe this was an error, try adjusting the 'app_start_timeout_sec' setting in the 'readiness_check' section." I've tried adjusting the readiness_check section to allow more time but it just takes longer to give me the same error it seems.I've tried googling this issue and adding more memory but the same error still shows. I'm stuck at this point and I'm not sure where else to look. Here is the app.yaml that successfully deployed on the standard environment entrypoint: gunicorn -b :$PORT xpotools.wsgi instance_class : F4_1G automatic_scaling: min_instances: 5 min_pending_latency: 30ms max_pending_latency: 4s max_concurrent_requests: 20 min_idle_instances: 3 inbound_services: - warmup handlers: - url: /static static_dir: static/ secure: always - url: /.* script: auto … -
How i can wrap json response data for djago-rest-framework?
I use djano rest framework. I have model, serializer and view: class PictureModel(models.Model): id = models.AutoField(primary_key=True) url = models.CharField(max_length=256) class PictureView(mixins.ListModelMixin, generics.GenericAPIView): serializer_class = PictureSerializer queryset = PictureModel.objects.all() def get(self, request): return self.list(request) class PictureSerializer(serializers.ModelSerializer): class Meta: model = PictureModel fields = '__all__' get request return json : [ { "id": 120525, "url": "https://ddd.com/upload/iblock/579/5797cc881f8790926cee4a8fc790d1bd.JPG" }, { "id": 120526, "url": "https://ddd.com/upload/iblock/382/382526e1deee07f60871430bd806aa71.JPG" } ... ] But i need wrap this data to { "success": 1, "data": [ { "id": 120525, "url": "https://ddd.com/upload/iblock/579/5797cc881f8790926cee4a8fc790d1bd.JPG" }, { "id": 120526, "url": "https://ddd.com/upload/iblock/382/382526e1deee07f60871430bd806aa71.JPG" } ... ] How i can do it? I can use middleware for it but i don't know how i can edit response data. Middleware apply for all requests but i need apply it not for all. May be I can use my renderer but I don't know how. P.S. Also I use swagger documentation auto generator. -
How to make a web app with an embedded interactive map?
I work on a project where I have to make a web app. The main idea is for the app to have a map (from OSM preferably) on which you can draw a rectangle and then get lon and lat of each corner. With that I can create a table showing all satellite images from my database in that area. My database is in PostgreSQL and I already have a backend for running queries. It's written with Python. Therefore It would be best if the web app is written with Python as well. I was looking at Django for making the app. I also found some examples how to embed a map in my app. But all examples show how to draw shapes after you provide the coordinate and not the other way around. I also looked at Angular for making the app, but I don't quite know how I would connect my backend in Python with my frontend. I don't have a lot of expericence with web apps nor with GIS so I'm asking for help here. What would be the best way to do this? Can someone please show an example how to make an app with an … -
How to retrieve list of tasks in a queue in Celery on Heroku?
My goal is to retrieve active & reserved tasks on my Celery workers. I'm using a Django-Celery-Redis framework. As suggested here: Retrieve list of tasks in a queue in Celery I have done this to retrieve the tasks: from your_app.celery import app as my_app i = my_app.control.inspect() active_tasks = i.active() reserved_tasks = i.reserved() It works well under my local environment. Online though (I'm using Heroku), it works 5% of the time & 95% of the time I get some errors. I get two types of errors, that randomly appears: raise ConnectionError(str(exc)) from exc kombu.exceptions.OperationalError: Error 0 connecting to THE_REDIS_SERVER. Error. Or I get a None response from my calls. I tried to configure some timeouts because by default control.inspect has timeout = 1.0. from your_app.celery import app as my_app i = my_app.control.inspect(timeout = 4.0) active_tasks = i.active() reserved_tasks = i.reserved() But still I get some connection errors. Any ideas? -
run commands inside docker as non root after running it with exec (shell)
i have a Django project with Docker (in Ubuntu) and MySQL as a database, everything is working .i'm just curious: instead of running the long command like: docker-compose run backend python manage.py startapp myapp // 'backend' is the name of service in docker-compose file i like to open the shell like: docker-compose run backend sh and then run my command: python manage.py startapp myapp but in this case it will be created by root, so i can't modify/save from the outside, (permissions required) i solve this with: sudo chown -R $USER:$USER . but i'm curious if there is any other ways, so that i could run the exec and modify my file from inside as non-root, instead of changing the owner every time. docker-compose: version: '3.9' services: backend: build: . volumes: - .:/backend ports: - 8000:8000 depends_on: - db db: image: mysql:latest environment: MYSQL_DATABASE: 'django-app-db' MYSQL_ROOT_PASSWORD: root volumes: - ./data/mysql/db:/var/lib/mysql Dockerfile: FROM python:3.9 ENV PYTHONUNBUFFERED 1 WORKDIR /backend COPY requirements.txt backend/requirements.txt RUN pip install -r backend/requirements.txt COPY . /backend CMD python manage.py runserver 0.0.0.0:8000 -
How to include images in django templates using an image url?
I am trying to build a web app which is similar to a search engine. Now when a user inputs "Eminem" for example , I need to show him an image of Eminem. Since the search term or query can be anything , it is not possible for me to have hundreds of images stored in my /static folder. I instead have an image url related to every search . For example :"https://images.genius.com/058e2359838c93395c36119b48a2eff6.300x300x1.png". Now is it possible to include this image for each search ?? -
API endpoint for django `Group` model generating excess number of queries
I am trying to build an endpoint for the default django's Group model, which has name and permissions fields:- Here are my view and serializers:- Serializers.py:- class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('id', 'name', 'permissions') def create(self, validated_data): permissions = validated_data.pop('permissions') instance = self.instance or self.Meta.model(**validated_data) instance.full_clean() instance.save() instance.permissions.add(*permissions) return instance def update(self, instance, validated_data): if 'permissions' in validated_data: permissions = validated_data.pop('permissions') instance.permissions.clear() instance.permissions.add(*permissions) instance.full_clean() return super().update(instance, validated_data) Views.py:- class GroupListCreateView(ListCreateAPIView): queryset = Group.objects.all() serializer_class = GroupSerializer class GroupDetailView(RetrieveUpdateDestroyAPIView): queryset = Group.objects.order_by('name') serializer_class = GroupSerializer with this serializers, and views I am facing a issue which is known as N+1 issue, that is the number of queries is really shooting high:- Can I please get any help on this. -
Django Prefetching Nested FKs not working
I have been working on this for a bit but I cannot seem to get prefetching to work correctly in my instance. I am trying to run a nested Prefetch() to prefetch items from a prefetched object, but the attribute is not being stored as usual. Can somebody please show me what I am doing wrong? Here is my code: primary_residents = Resident.objects.filter(property=request.session['property'], type='primary', user__is_active=True).select_related( 'unit', 'unit__building', 'current_balance', 'user').prefetch_related( Prefetch('current_balance', queryset=Balance.objects.filter(is_active=True).prefetch_related( Prefetch('charges', queryset=Charges.objects.filter( date_entered__range=(previous_month, property.close_out_start_date_plus_one()), reversed=False).prefetch_related('code', 'balance'), to_attr='previous_charges' ) ), to_attr='current_balance' ), ) for p in primary_residents: # errors out previous_charges is not on the Balance print(p.current_balance.previous_charges) -
OperationalError at /admin/auctions/listing
Hi new to Django unable to detect the error here, please tell me what I am doing wrong .I am Confused about the flow of the files in DJango also. -
Django application not logging request info in production log file when deployed with gunicorn and Nginx
This is the log settings of my Django application. LOG_DIR = "logs" LOG_DIR_PATH = os.path.join(BASE_DIR, LOG_DIR) if not os.path.exists(LOG_DIR_PATH): os.mkdir(LOG_DIR_PATH) LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "{asctime} {levelname} : {filename} line - {lineno:d} : {message}", "style": "{", "datefmt": "%Y-%m-%d %H:%M:%S", }, }, "filters": { "require_debug_false": { "()": "django.utils.log.RequireDebugFalse", }, "require_debug_true": { "()": "django.utils.log.RequireDebugTrue", }, }, "handlers": { "console": { "level": "INFO", "filters": ["require_debug_true"], "class": "logging.StreamHandler", "formatter": "verbose", }, "production": { "level": "INFO", "filters": ["require_debug_false"], "class": "logging.handlers.RotatingFileHandler", "filename": os.path.join(LOG_DIR_PATH, "production.log"), "maxBytes": 1024 * 1024 * 5, # 5 MB "backupCount": 5, "formatter": "verbose", }, "development": { "level": "INFO", "filters": ["require_debug_true"], "class": "logging.handlers.RotatingFileHandler", "filename": os.path.join(LOG_DIR_PATH, "development.log"), "maxBytes": 1024 * 1024 * 5, # 5 MB "backupCount": 5, "formatter": "verbose", }, "task_handler": { "level": "INFO", "class": "logging.handlers.RotatingFileHandler", "filename": os.path.join(LOG_DIR_PATH, "tasks.log"), "maxBytes": 1024 * 1024 * 10, # 10 MB "backupCount": 10, "formatter": "verbose", }, }, "loggers": { "django": { "handlers": ["console"], }, "py.warnings": { "handlers": ["console"], }, "django.request": { "handlers": ["console"], "level": "ERROR", }, "task_logger": { "handlers": ["task_handler"], "level": "INFO", "propagate": False, }, }, "root": { "handlers": ["production", "development"], "level": "INFO", "propagate": False, }, } So, I'm expecting it to log all the requests info in development.log …