Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest framework filter on related tables
i need help filtering on a field on a related table. I have tow models Kalas and names, where one (Kalas model) has a one to one relation with the basic User model: class Kalas(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) visitKalas = models.ForeignKey('self', on_delete=models.DO_NOTHING, blank=True, null=True) isActive = models.BooleanField(default=True) capacity = models.IntegerField(default=0) fullName = models.CharField(max_length=100, default="default name") phoneNumber = models.IntegerField() address = models.CharField(max_length=40) postal = models.CharField(max_length=50) time = models.DateTimeField(auto_now_add=True) lat = models.FloatField(default=0) lng = models.FloatField(default=0) def __str__(self): return "user: %s, address: %s %s" % (self.user, self.address, self.postal) class names(models.Model): kalasID = models.ForeignKey(Kalas, on_delete=models.CASCADE, related_name='names') name = models.CharField(max_length=30) and i have made a nested serializer: class NamesMapSerializer(serializers.ModelSerializer): class Meta: model = names fields = ['name'] class KalasMapSerializer(serializers.ModelSerializer): #bruk denne hver gang man vil ha kalas og navn sammen names = NamesMapSerializer(many=True, read_only=True) class Meta: model = Kalas fields = ['id', 'fullName', 'capacity', 'lat', 'lng', 'names'] class MapSerializer(serializers.ModelSerializer): kalas = KalasMapSerializer() class Meta: model = User fields = ['username', 'kalas'] and a view that lists all users and its kalas with names: class MapViewSet(viewsets.ModelViewSet): queryset = User.objects.all() permissions_classes = [permissions.AllowAny] serializer_class = MapSerializer but i dont know how to filter so it only shows users with kalas that i active kalas.isActive=True. i've tried … -
Django - set ONE session_key for every visitor/browser and remember it without logging in
I'm trying to create e-commerce cart in Django and got into trouble with session_key. When I'm logged in the admin page, my session_key is always the same. But after I logout, my session_key is None. So I call request.session.create() but after refreshing the page, session_key is again None. Is there any way how to force Django to remember user's browser? So how could I implement the same logic as is for logged users for not logged users? Thanks! -
How do i solve [Errno 13] Permission denied: 'list.txt'
I recently lunch a small video downloading website.Which has list.txt file inside it.When a user enter a url it was suppose to write a url to that list.txt file and again read from it.It was working fine in localhost but in production it throws error. [Errno 13] Permission denied: 'list.txt' Request Method: GET Django Version: 3.0.2 Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: 'list.txt' I performed several chmod operations but didnt work. -
How to process Javascripts FormData object within Django Post using Ajax and Native Javascript
How can Javascripts FormData object be processed (data extracted from the FormData object) within Django class based view, post method using Ajax and native Javascript, NOT JQuery? // Javascript var form = document.GetElementById('my-form'); var formData = new FormData(form); var request = new XMLHttpRequest(); request.open('POST', 'my/django/url/', true); request.send(formData); Then in Django class based view post method what do I do? # Django / Python if request.is_ajax(): form_data_post = request.POST.get(formData['post'], None) form_data_files = request.FILES.get(formData['files'], None) # Process the formData here I can receive the formData object in request.POST but it's a mess and I can't make sense of it so I'm not sure if I'm sending it correctly or not, or if I need to do something special in Django to process it. I know there is csrftoken and other things to consider in the AJAX call which I haven't included here as that's not my concern. Google hasn't been my friend with this one. -
How to store in and access from , GAE /tmp to Django html?
I found this link that says we can use /tmp to store files for our instance in Google App Engine. https://cloud.google.com/appengine/docs/standard/python3/using-temp-files But the problem is that 1) How do i store to the \tmp folder, is it by just writing the save path as = "\tmp" or something else 2) How will i access those files stored in the \tmp folder in my django html page, currently i can assess the static files using {% static %} tag -
Getting ModuleNotFoundError when trying to load Scrapy settings from environment variable
I am running Scrapy with a Django project and am trying to define the Scrapy settings from outside of the Scrapy project. I am using get_project_settings() which looks for the environment variable SCRAPY_SETTINGS_MODULE. I have managed to set this to scraper.crawling.crawling.settings but when get_project_settings() is run, I am shown the error: ModuleNotFoundError: No module named crawling. This is correct, since crawling is a directory and not the module, settings is, which I am trying to direct it to. Is anyone able to help me such that get_project_settings will correctly find the module settings? Below is the folder structure I am using: ├───django-scraper | ├───django_scraper | | └───settings.py | │ | ├───scraper | │ ├───crawling | │ │ └───crawling | │ │ ├───spiders | │ │ ├───settings.py | | | └───crawler_process.py The following is in my Django settings.py so this is set upon starting the server: os.environ['SCRAPY_SETTINGS_MODULE'] = 'scraper.crawling.crawling.settings' get_project_settings() is called from within crawler_process.py, although I don't think the location is an issue since it is looking at the enviornment variable anyway. My sys.path already has 'C:\\Users\\georg\\Django\\django-scraper' in it, and it appears to access scraping fine but then tries to take scraper.crawling as a module. I hope that's enough information … -
changing elasticsearch default min_term_freq and min_doc_freq
I use this technologies/packages in django for handling search page elasticseach 2 (as search database) elasticseach-py django-haystack (as search tools with elasticseach backend engin) drf-haystack (for using django-haystack in django-rest-framework) where can I change min_term_freq and min_doc_freq default values because my More Like This search not working any other suggestions are welcomed -
link should only be visible to the superuser and the group
I have the below url for in the _base.py which will render a link in the left side when the user hovers a section called Uploads, {'label': 'Upload User Data', 'url': '/admin/user/bulk_user_update/', 'permissions': 'bulkupdate.access_user'}, I want this url only to visble to the superuser and the current permission bulkupdate.access_user How can i achieve this any help is appreciated -
Is 304 error being caused by ManifestStaticFilesStorage
I have recently noticed that I am getting the following when I run my Django project locally: "GET /static/MySearch/css/style.css HTTP/1.1" 304 0 i) I am running it in debug mode. ii) The file is clearly visible within the MySearch static directory, but also within the static directory that is created using collect static iii) I have recently added the following to the settings file: STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' I was wondering if the 304 error was being caused by ManifestStaticFilesStorage and if I needed to worry about it ? Thanks Mark -
Django Model Import Error: ValueError: attempted relative import beyond top-level package
I have created a new app "grn" in my django project and tried to import the models from another app named "packsapp" in the same project like this: Models.py from ..packsapp.models import * But I got the following error: ValueError: attempted relative import beyond top-level package Here's the structure of the app: yantra_packs grn --migrations __init__.py admin.py apps.py models.py tests.py views.py media packsapp --migrations templates templatetags views1 __init__.py apps.py decorators.py forms.py models.py urls.py views.py How can I import the models of the packsapp in the grn ?? -
Probleme with content types and parsers/renders with django rest_framework
I'm using django rest framework to recieve SOAP messages. I create a custom Parser and Render but now I have a problem with content types. My render and parser content_type is 'text/xml' and ONLY accepts this post content type. There is a way to add more content types? I've search in the docs but I've not found anything appart from creating new parsers/renders for any content type. The main is problem is that my client who sends me soap messages change the content type and I would like to accept them all. Thank you! -
Run custom one time script django
I want to run a custom one time script (to read from Excel file and write to DB) the problem is when i run python manage.py shell < poligon/run.py I lose when all data in run.py The project structure is .venv apps/ -- all my apps poligon/ run.py manage.py settings/ -
Unable to upload file from Angular using pre-signed url?
My Backend(Django) generates the presigned URL's as: session = boto3.Session( aws_access_key_id=*****, aws_secret_access_key=*****, region_name=*****, ) s3 = session.client('s3') url_object = s3.generate_presigned_post(Bucket=bucket, Key=key, ExpiresIn=expiry) return url_object I upload file from my Frontend(Angular 8) to the pre-signed URL as follows: this.http.post(url, form).subscribe(result=>{ const presigned_url = result; this.customHttp.post(String(presigned_url["url"]), file, {params: presigned_url["fields"]}).subscribe(); }); This throws the following message: <Error> <Code>MethodNotAllowed</Code> <Message>The specified method is not allowed against this resource.</Message> <Method>POST</Method> <ResourceType>BUCKETPOLICY</ResourceType> <RequestId>4A605D8379FFCDDD</RequestId> <HostId>e8jvo5mJwkXad7Wg0wIvy3E0FYHVPY96mxZeFLhznsVM5cs8uaTfVqiWxekoowqU805g+y+xV3g=</HostId> </Error> Now, when I try to upload file to the pre-signed URL using the following python code, it works: url = url_object['url'] data = url_object['fields'] files = {'file': open('/../../../image.png', 'rb')} requests.post(url, data=data, files=files) Can someone help me with this, as I want to upload the file from my Frontend(Angular) ? -
Keep active tab after reload
I'm trying to keep active tab after reload using bootstrap and JS, but something goes wrong. I don't know whether i put script in wrong place or code is broken. Thanks for help! Code below: HTML_base <!DOCTYPE html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> {% block title %} {% endblock title %} <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> {% load static %} <link rel="stylesheet" type='text/css' href="{% static 'post/style.css' %}"> <script type="text/javascript" src="{% static 'post/javatab.js' %}"></script> </head> <body> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-git.js"></script> </body> </html> HTML_detail <ul class="nav nav-tabs card-header-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="PL-tab" data-toggle="tab" href="#PL" role="tab" aria- controls="PL" aria-selected="true">PL</a> </li> <li class="nav-item"> <a class="nav-link" id="RU-tab" data-toggle="tab" href="#RU" role="tab" aria-controls="RU" aria-selected="false">RU</a> </li> </ul> Javatab $(function() { $('a[data-toggle="tab"]').on('click', function(e) { window.localStorage.setItem('activeTab', $(e.target).attr('href')); }); var activeTab = window.localStorage.getItem('activeTab'); if (activeTab) { $('#myTab a[href="' + activeTab + '"]').tab('show'); window.localStorage.removeItem("activeTab"); } }); SETTINGS.PY STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] -
I am new to django and when I am trying to python manage.py runserver... I was getting an error below... what I have to do now? please let me know
Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '' -
aws lambda django app deployed with zappa - pythin import precendecy
We have a Django application we deploy on AWS Lambda, using Zappa. We use pipenv to manage python packages of the project. Some packages we use (e.g cryptography) need to be compiled with the same configration as the lambda machine. To do that, I've generated wheels for those packages on a similar machine, and included them in a sub folder in the directory. So here is our deployment process now: install packages with pipenv (which also includes those special packages) extract precompiled wheels in a special directory run zappa deploy command So after this, we have two versions of those packages, one installed via pipenv, and one extracted manually from precompiled wheels. The reason for this is, I still want the project to be able to run locally (using the package installed via pipenv, and not using the precompiled ones). So I want local versions of the project to use packages installed via pipenv, but want Lambda to use extracted - precompiled version. I've added the directory where we keep precompiled packages to PYTHONPATH environment variable, but as far as I can see, zappa puts all python packages installed via pipenv in the root folder of the project. Those have … -
Django relationships in Models
I have a big confused of using relationship in models. I have this database that contains Data (see Image) Database organisation image I have many fields. Every field have some element attached to it (wells). Every well is unique and if allocated to one field. The well have many data for every element (Info, Petro, Geo and Tests) Every data is attached to a service that can add and modify. Every Service can manage one data. Every Service has manager and some users. I wrote a code but I don't know when I use relationships types. like ForeignKey, ManyToManyField...... My code : from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.urls import reverse # Create your models here. class Fields(models.Model): Fieldname = models.CharField(max_length=15) DiscoveredDate= models.DateField(max_length=4) #YYYY Mechanisms = models.CharField(max_length=15)# OBSERVATION = models.TextField() post_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.Fieldname def get_absolute_url(self): return reverse('Fields', args=[self.pk]) class Meta: ordering=('-post_date',) class Wells(models.Model): WellID = models.ManyToManyField(max_length=15,related_name='Fields') # or I use ForeignKey TYPE = models.CharField(max_length=35) Startdate = models.DateField(max_length=35) # date with format mm-dd-YY EndDate = models.DateField(max_length=15) # date with format mm-dd-YY Duration = models.IntegerField(max_length=4) # enteger supervisor = models.CharField(max_length=30) OBSERVATION = models.TextField() post_date = models.DateTimeField(default=timezone.now) author = … -
How to add red asterisk to form field if the field fails to validate?
If a form field fails to validate, Django will display a helpful message (e.g. "This field is required"). However, in addition to the helpful message, I also want to display a red asterisk next to the form field itself if there are any validation errors for the field. Something like: Excerpt from my template: <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit"/> </form> I know I can insert the asterisk using manual form rendering, but I am looking for a way to do this without editing the template. Is there a way to do this? Perhaps it can be done by overriding specific form.Form methods? -
input Csv models.FileField into pandas object
I have model Field instance. myCsv = myFile.objects.get(id=1) // myCsv.document is models.FileField and want to put this in pandas. df = pd.read_csv(thred.document.read()) OSError: Expected file path name or file-like object, got <class 'bytes'> type How can I put the cev file to pandas object?? -
How can I fetch object from ForeignKey with date after now in Django?
I have the following models: class Clients(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=200, verbose_name="Morada") nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], unique=True, null=True) mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')]) class Flight(models.Model): date = models.DateTimeField(default=datetime.now, blank=True, verbose_name="Data") flight_id = models.CharField(max_length=10, verbose_name="Ref. Voo") company = models.ForeignKey(AirCompany, null=True, on_delete=models.SET_NULL, verbose_name="Companhia") airport = models.ForeignKey(Airport, null=True, on_delete=models.SET_NULL, verbose_name="Aeroporto") class Trip(models.Model): trip_id = models.CharField(max_length=20, verbose_name="Ref. Viagem", primary_key=True) destination = models.CharField(max_length=200, null=True, verbose_name='Destino') client = models.ForeignKey(Clients, null=True, on_delete=models.CASCADE, verbose_name="Cliente") out_flight = models.ForeignKey(Flight, related_name="outbound_flight" ,null=True, on_delete=models.SET_NULL, verbose_name="Voo Ida") hotel = models.ForeignKey(Hotels, null=True, on_delete=models.SET_NULL, verbose_name="Hotel") in_flight = models.ForeignKey (Flight, related_name="inbound_flight", null=True, on_delete=models.SET_NULL, verbose_name="Voo Regresso") Knowing that both Flight and Clients are a ForeignKey in Trip, how can I fetch all the clients who have flights after now? I used Going = Flight.objects.filter(date__gt=datetime.now()).order_by('date') to get all the flights leaving after now, but I also need to get which clients are going after now. -
Blur image with easy_thumbnails
How to blur an image with this logic in the Django model. @property def get_small_url_port(self): return DOMAIN + get_thumbnailer(self.image).get_thumbnail({ 'size': (75, 100), 'box': self.cropping_port, 'crop': 'smart', # 'upscale': True, }).url -
Django Logging Error in format : KeyError : ‘classname’
Extra context cannot set with given log format which is defined in settings.py and I am using APIs are responding and even logs are generating in the log file if we remove %(classname)s()] %(token)s %(router_macid)s %(user_email)s %(device_macid)s From the format then it is working fine without and error, i am using django==2.1, djangorestframework==3.10.3 Error --- Logging error --- Traceback (most recent call last): File "/usr/lib/python3.6/logging/__init__.py", line 994, in emit msg = self.format(record) File "/usr/lib/python3.6/logging/__init__.py", line 840, in format return fmt.format(record) File "/usr/lib/python3.6/logging/__init__.py", line 580, in format s = self.formatMessage(record) File "/usr/lib/python3.6/logging/__init__.py", line 549, in formatMessage return self._style.format(record) File "/usr/lib/python3.6/logging/__init__.py", line 391, in format return self._fmt % record.__dict__ KeyError: 'classname' Call stack: File "/usr/lib/python3.6/threading.py", line 884, in _bootstrap self._bootstrap_inner() File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/usr/lib/python3.6/socketserver.py", line 654, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.6/socketserver.py", line 364, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.6/socketserver.py", line 724, in __init__ self.handle() File "/usr/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 154, in handle handler.run(self.server.get_app()) File "/usr/lib/python3.6/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/lib/python3.6/wsgiref/handlers.py", line 183, in finish_response self.close() File "/usr/lib/python3.6/wsgiref/simple_server.py", line 35, in close self.status.split(' ',1)[0], self.bytes_sent File "/usr/lib/python3.6/http/server.py", line 536, in log_request self.requestline, str(code), str(size)) File "/usr/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 124, … -
How to render django-easy-audit logs in django template
I recently installed django-easy-audit in my app. At the moment, it is rightly showing all logs in the admin dashboard, however, I wish to have these logs rendered to my django template. Is there a way around this? -
json field in django-haystack with elasticsearch engine
How can I store json in elasticsearch by django-haystack fields now I use this trick: # search_indexes.py class BlogPostIndex(indexes.SearchIndex, indexes.Indexable): author = indexes.CharField() @staticmethod def prepare_author(obj): return json.dumps(serializers.UserMinimalSerializer(obj.author).data) # serializers.py class BlogPostSearchSerializer(HaystackSerializer): author = serializers.SerializerMethodField() @staticmethod def get_author(obj): return json.loads(obj.author) but by this trick search not working in json data -
How to upload files to GAE through form data post in Django?
I have my django webapp that contains a method in one of my models to upload the user chosen file (from form) to a specified file directory. But i am not able to use the model after i have deployed my app on Google App Engine (using gcloud). I am using the Google MySQL db for my django app. Also, I am not able to use os.makedir() method in my app as the server prompts there is Read-Only-Permission MODELS.PY def upload_to(instance, filename): now = timezone_now() base, ext = os.path.splitext(filename) ext = ext.lower() rootpath = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) return rootpath + f"/face_detector/static/face_detector/img/{now:%Y%m%d%H%M%S}{ext}" # Do add the date as it prevents the same file name from occuring twice # the ext is reserved for the file type and don't remove it class PicUpClass(models.Model): picture = models.ImageField(_("picture"), upload_to=upload_to, blank=True, null=True) I am a rookie in python so please suggest me some basic solutions.