Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does Django send mail loggers of only 5xx errors?
I want to send an email for the custom logs too. Here's my logging settings. For eg:- Checkout the below code. def function(url): if some_raise_condition: logger = logging.getLogger(__name__) kwargs = {'key1': value} logger.critical(str(e), kwargs) I want an email for the above log. Here's my logging config. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { # HAS BEEN COMMENTED IN CASE YOU WANT TO USE SOME IN FUTURE # 'verbose': { # 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' # }, # 'simple': { # 'format': '%(levelname)s %(message)s' # }, # 'timestampthread': { # 'format': "%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] [%(name)-20.20s] %(message)s", # }, 'keyvalue': { 'format': "APP: %(name)s LEVEL: %(levelname)s PATH: %(pathname)s LINE: %(lineno)d FUNCTION:" "%(funcName)s TIME: %(asctime)s MESSAGE: %(message)s", 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, 'handlers': { 'mail_admins': { 'level': 'INFO', # we don't want to send you mails while in dev mode 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler', 'formatter': 'keyvalue', }, }, 'loggers': { # Mail logger should log message to console as well. 'django_mailer': { 'handlers': ['mail_admins', ], 'propagate': False, 'level': 'INFO', }, }, } How can I send the above logs on my email? PS: I mail … -
How to filter django models with foreign key?
I'm trying to query relational django models I have 3 models a,b, users the relations between them as the following code. what i want to do is : get all records in model B when user is in users in model A. how to say that in filter like this B = B.objects.filter(a__users=self.request.user) ? Class A(models.Model): users = models.ManyToManyField(User, blank=True, related_name='users') class B(models.Model): a = models.ForeignKey(A, on_delete=models.DO_NOTHING, related_name='something', blank=True, null=True) -
Django app generating forms dynamically from JSON?
I'm creating a Django site and I would like to add dynamically generated forms based on JSON description which will come from an external source. E.g. something like this: [ { "name": "first_name", "label": "First Name", "type": "char", "max_length": 30, "required": 1 }, { "name": "last_name", "label": "Last Name", "type": "char", "max_length": 30, "required": 1 }, ] Would then give me a simple Django form with two CharFields which I would display to a user and save the values he/she puts in for further processing. I searched but didn't find any app creating Django forms from JSON like this. I can write such app myself, I just wanted to know if there is anything already. If not, do you at least know about any JSON schema format that would allow to describe forms? Again, I can come up with it myself but I wanted to have a look at some examples so I don't omit important possibilities and have something solid to start with. Thanks! -
How to pass state to react frontend, after clicking email activation link
Using ReactJS and Django REST Framework I am building an app where users can register. Upon submitting the registration form, the user gets an email activation link. Clicking that link will redirect the user back to the front-end, to a message telling them that the email is now activated. After that it will redirect the user to the login screen. Flow A: Submit registration form -> user receives email activation link -> message (new tab) -> login form A new tab opening after clicking on the email activation link is a key aspect, since it means that I am starting over with new state. Now. My to complicate things, the app I am working on gives users the possibility to fill a shopping cart. They can then request a quote. Flow B: Shopping cart -> user clicks "request quote" -> quote overview/confirmation Users need to be logged in to request a quote. When they click to request a quote but are not logged in, they will get the option to log in or to register. Flow C: Shopping cart -> user clicks "request quote" -> page asking user to log in or register When they choose the registration option, they … -
PhoneNumberField() cannot find ref
I have installed pip install django-phonenumber-field pip install phonenumbers with pipenv. But when i am going to use it in my models.py file it says Cannot find reference 'PhoneNumberField' in '__init__.py' in PyCharm I have imported PhoneNumberField from modelfield. Any help pls? -
How to speed up parsing json and writing in the database?
I need to parse json file size of 200MB, at the end I would like to write data from the file in sqlite3 database. I have a working python code, but it takes around 9 minutes to complete the task. with open('file.json') as f: data = json.load(f) cve_items = data['CVE_Items'] for i in range(len(cve_items)): database_object = Data() for vendor_data in cve_items[i]['cve']['affects']['vendor']['vendor_data']: database_object.vendor_name = vendor_data['vendor_name'] for description_data in cve_items[i]['cve']['description']['description_data']: database_object.description = description_data['value'] for product_data in vendor_data['product']['product_data']: database_object.product_name = product_data['product_name'] database_object.save() for version_data in product_data['version']['version_data']: if version_data['version_value'] != '-': database_object.versions_set.create(version=version_data['version_value']) Is it possible to speed up the process? -
Django chaining prefetch_related and select_related
Let's say I have following models class Foo(models.Model): ... class Prop(models.Model): ... class Bar(models.Model): foo: models.ForeignKey(Foo, related_name='bars', ...) prop: models.ForeignKey(Prop, ...) Now I want to make the following query. foos = Foo.objects.prefetch_related('bars__prop').all() Does the above query makes 3 Database calls or only 2 (select_related for prop from bar), given that only one prop is associated with bar If it takes 3 calls then, is there a way to make it 2 calls by using selected_related for bar -> prop -
Hosting requirements for ticket booking app using django 2 and angular 7
I have a ticket booking web app which is currently hosted on aws 2gb server. It has angular and django both running and is extremely slow. It doesn't even have users yet. It takes approximately 15-30 seconds to load on a good connection. The code is well optimised imho. Will upgrading the server help or is there another way to make it faster? Also, i have powerful servers at home. Would it be wise to host the complete web app on my servers and what is the procedure to set them up? -
Cannot embed a django website into another html page
I am trying to embed a locally hosted django website in another html page placed in the same system. But the embed section is showing connection refused error. <embed src="http://127.0.0.1:8080/scheduleselect/" style="width:1000px; height: 500px;"> -
Populate form field with AJAX query
I would like to populate a django form field each time a dropdown value is selected inside a specific field. Example : I have a list of businesses (business A, business B, ...) and a list of countries. Each business is located in a specific country. Business A --> France Business B --> Germany Business C --> England In my form, when I select a specific business in my dropdown list, I would like to populate immediatly the country field with the associated country. If the business change, the associated country too. I'm using Django 1.11.18 The context : In my code, MemberState corresponds to the Country as my example above and RBI corresponds to the business. My Model : class MemberState(models.Model): name = models.CharField(max_length=256, verbose_name=_('Name')) code = models.CharField(max_length=256, verbose_name=_('Code')) class RBI(models.Model): short_name = models.CharField(max_length=256, verbose_name=_('Short name'), unique=True) member_state = models.ForeignKey(MemberState, verbose_name=_('Member State')) ... My Form : class FinalProductSearchForm(forms.Form): releasing_body = ShortNameModelChoiceField(queryset=RBI.objects.filter(active=True).order_by('short_name'), required=False, widget=forms.Select(), empty_label=_('Select'), label=_('Releasing Body/Institution')) member_state = forms.ModelChoiceField(queryset=MemberState.objects.filter(active=True).order_by('name'), required=False, widget=forms.Select(), empty_label=_('Select'), label=_('Member state')) ... I would like to select a releasing_body in my form and prefill the member_state field associated. Each time I change the realeasing_body it loads the associated member_state. I tried some things in Django but … -
How can I sort a list of objects in Python so that, an object with particular status stays on top [duplicate]
This question already has an answer here: Sort a list by multiple attributes? 4 answers Sorting a Python list by two fields 5 answers I have a list of objects in Python. Each object has an attribute named status, I want that the objects having status as "confirmed" should always be at top of list. Currently the list is sorted on the basis of creation date like : obj_list.sort(key=lambda x:x.obj_created_at,reverse=True) I want to sort it one more time with status. How can I do that? -
Getting a FATAL Exited too quickly error. Supervisor configuration
I am getting this error when trying to configure Supervisor for a Django application on a VPS. So when I look at the error log it seems like it can't find the directory but I don't know what I am doing wrong here. The path is: /home/webconexus/portfolio (portfolio) webconexus@wagtail-portfolio:~/portfolio$ sudo supervisorctl status portfolio FATAL Exited too quickly (process log may have details This is my gunicorn_start file: #!/bin/bash NAME="portfolio" DIR=/home/webconexus/portfolio USER=webconexus GROUP=webconexus WORKERS=3 BIND=unix:/home/webconexus/portfolio/run/gunicorn.sock DJANGO_SETTINGS_MODULE=portfolio.settings DJANGO_WSGI_MODULE=portfolio.wsgi LOG_LEVEL=error cd $DIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- This is my conf file: [program:portfolio] command=/home/webconexus/portfolio/bin/gunicorn_start directory=/home/webconexus/portfolio user=webconexus autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/webconexus/portfolio/logs/gunicorn-error.log My error log: /home/webconexus/portfolio/bin/gunicorn_start: line 14: ../bin/activate: No such file or directory /home/webconexus/portfolio/bin/gunicorn_start: line 19: /home/webconexus/portfolio/src/portfolio/../bin/gunicorn: No such file or directory /home/webconexus/portfolio/bin/gunicorn_start: line 14: ../bin/activate: No such file or directory /home/webconexus/portfolio/bin/gunicorn_start: line 19: /home/webconexus/portfolio/src/portfolio/../bin/gunicorn: No such file or directory /home/webconexus/portfolio/bin/gunicorn_start: line 14: ../bin/activate: No such file or directory /home/webconexus/portfolio/bin/gunicorn_start: line 19: /home/webconexus/portfolio/src/portfolio/../bin/gunicorn: No such file or directory /home/webconexus/portfolio/bin/gunicorn_start: line 14: ../bin/activate: No such file or directory /home/webconexus/portfolio/bin/gunicorn_start: line 19: /home/webconexus/portfolio/src/portfolio/../bin/gunicorn: No such file or directory /home/webconexus/portfolio/bin/gunicorn_start: line 14: ../bin/activate: No such file or … -
How to pass additional data to the post_ajax method?
I have the models: class MyModelOne(models.Model): title = models.CharField(verbose_name=_('Title'), max_length=255) body = models.TextField(verbose_name=_('Body')) # some other fields class MyModelTwo(models.Model) title = models.CharField(verbose_name=_('Title'), max_length=255) # some other fields class Photo(models.Model): title = models.CharField(verbose_name=_('Title'), max_length=255) image = StdImageField(verbose_name=_('Image'),upload_to='photos') content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') I want to include a dropzone (DropzoneJS) field for creating Photos objects inside the admin change views of some other models while updating their objects. I am using the ajax view to handle it independently to the admin change view form. To create the Photo object I need to pass the other model currently updated object's data to the post_ajax method. I don't know how to recognize the current object model and its id in the post_ajax method, where I want to handle the Photos creating. from braces.views import AjaxResponseMixin, JSONResponseMixin, LoginRequiredMixin, SuperuserRequiredMixin class AjaxPhotoUploadView( LoginRequiredMixin, SuperuserRequiredMixin, JSONResponseMixin, AjaxResponseMixin, View, ): def post_ajax(self, request, *args, **kwargs): file = request.FILES['file'] Photo.objects.create( title=file.name, image=file, content_object=obj, ) response_dict = { 'message': 'File uploaded successfully!', } return self.render_json_response(response_dict, status=200) -
How to get the AWS credentials in a certain moment of a django error
I have a Django project deployed on AWS Lambda and I am trying to debug a certain S3 upload problem, but I want to know how to get the certain credentials during the error because it happens at random. I want to get credentials for a past time, For the next time the error appears I have the logging done in the code. So how to get those credentials from the AWS console for a past period of time. I see that my lambda-related-role has a 1hour update of credentials. and It changes in time. Let me know if the question is offtopic. -
Delete records from a collection of a specified DB
I am using mongoDB as my database, i am working on django projects and using mongoengine to connect with database. My question is if my default database in settings.py is DB1 and i want to delete all records of a collection which exists inside DB2 then how can i do this. settings.py import mongoengine mongoengine.connect( db= "DB1", host='localhost', ) models.py class Resources(Document): field1= fields.StringField(max_length=20) field2 = fields.StringField(max_length=70) field3 = fields.StringField(max_length=70) field4 = fields.DictField() meta = {'collection': 'resources', 'allow_inheritance': False, '_target_db': 'DB2'} python shell from .models import Resources import mongoengine mongoengine.connect('DB2', alias='ces') ob = Resources() ob.switch_db('ces') ob.field1 = value ob.field2 = value ob.field3 = value ob.save() Now i have collection resources in DB2 and it has some records, i have tried Resources.objects.all().delete() but it is not deleting records form DB2 instead it deletes records from DB1 which is default database. -
Dango annotation and GROUP BY
I am having trouble with making a query in django. Following is my model class: class Registration(models.Model): event_type = models.CharField(max_length=80) date_time = models.DateField() total_assessment = models.IntegerField() I want to: SELECT event_type, SUM(total_assessment) as count from Registration WHERE event_type in ('value1', 'value2', 'value3') GROUP BY event_type How can I translate this query to Django ORM. -
How to serialize a list of dictionaries into json and return the response?
I have a list of dictionaries as: response_list = [{...}, {...}, {...}] I tried these(with their respective imports) but none is working: return JsonResponse(response_list, safe=False) json.dumps(response_list, safe = False) serializers.serialize('json', response_list) Can anyone tell what`s the fix? I need to return the json response but it gives error as: "TypeError: Object of type TypeError is not JSON serializable" -
Is there any way to upload image in ckeditor, with out log in as admin.?
I'm using a custom dashboard for my admin, i used ckeditor as richtext editor. Whenever i tried to upload a image it shows default django admin. So i cant upload image. I have given my user super user role. I tried commenting the admin user, but shows error. Below is the url for ckeditor. url(r'^ckeditor/', include('ckeditor_uploader.urls')) it redirect to another page and shows 'No reverse math' I already have dashboard with superuser capability and logging into that add account and doing this. So is there any way to avoid login as default admin in django. -
Django - Reducing the boilerplate for to filter the queryset and possibly improve performance
I am using Model Manager to return a filtered search queryset but currently the boilerplate for that is quite long, I'd be glad if I could find a way to reduce the boilerplate as well as gain some performance. Currently I'm doing it this way: class ImageTagManager(models.Manager): def ordered_images(self): queryset = self.model.objects.order_by('id').all() return queryset def search(self, query_dict): if isinstance(query_dict, list): queryset = ImageTag.objects.filter(id__in=query_dict) if queryset is not None: return queryset else: return False # Initially getting all objects queryset_initial = ImageTag.objects.all() # copying queryset_initial to filter queryset = queryset_initial queryset = queryset.filter(company__iexact=query_dict['company']) if query_dict.get('company') not in ( None, '') else queryset queryset = queryset.filter(accoff__iexact=query_dict['accoff']) if query_dict.get('accoff') not in ( None, '') else queryset queryset = queryset.filter(section__iexact=query_dict['section']) if query_dict.get('section') not in ( None, '') else queryset queryset = queryset.filter(docref__iexact=query_dict['docref']) if query_dict.get('docref') not in ( None, '') else queryset start_date = query_dict.get('start_date') end_date = query_dict.get('end_date') if start_date not in (None, '') and end_date not in (None, '') and start_date < end_date: queryset = queryset.filter(start_date__range=(start_date, end_date)) elif start_date not in (None, ''): queryset = queryset.filter(start_date__exact=start_date) if query_dict.get('docref') not in ( None, '') else queryset queryset = queryset.filter(pagenum__iexact=query_dict['pagenum']) if query_dict.get('pagenum') not in ( None, '') else queryset queryset = queryset.filter(refnum__iexact=query_dict['refnum']) if query_dict.get('refnum') not in … -
Paper element import not working in python
Paper elements are not able to import in python-django environment An import error arises Uncaught TypeError: Failed to resolve module specifier "@polymer/polymer/polymer-legacy.js". Relative references must start with either "/", "./", or "../". Tried to build the same project using polymer build still no improvement i placed the polymer components inside a static folder in an app My project -> App-> static -> polymer files Environment details OS: ubuntu 18.04 Lang: python 3.6- django 1.11 polymer version: 3 -
In django, admin.py loses it's CSS
I'm building a django polls application and when I try to initialise the admin.py and then run the server it works fine including the CSS and everything. But when I open it again later, it seems to have lost all the styling and shows me the basic HTML version. -
" How to get same I'd data from many foreignkey field in same table "
" I'm new in Django and i'm Build a coaching website,i want to store student ID and multipal Course Id through Foreignkey in Student Course table and Catching data according to student Id and display student data and all course which selected by student on 'Table HTML' page in single row " Model.py class course_content(models.Model): course = models.CharField(max_length= 100) Code = models.CharField(max_length=50) class student_admission(models.Model): Student = models.CharField(max_length= 50) Father = models.CharField(max_length= 50) Date = models.CharField(max_length= 50) Gender = models.CharField(max_length= 50) class student_course(models.Model): Student_id= models.ForeignKey(student_admission,on_delete=None) Course_id = models.ForeignKey(course_content,on_delete=None) Views.py def savedata(request): student = request.POST.get("student") father = request.POST.get("father") date = request.POST.get("date") gender = request.POST.get("gender") c_id = request.POST.getlist("cid") obj = student_admission(Student=student,Father=father,Date=date,Gender=gender) obj.save() for id in c_id: obj2 = student_course(Student_id_id=obj.id,Course_id_id=id) obj2.save() return HttpResponseRedirect(settings.BASEURL +'/home') def table(request): data = student_course.objects.all().prefetch_related('Student_id','Course_id') unique_list = [] for x in data: if x not in unique_list: unique_list.append(x) d = {'data1' : unique_list} return render(request,"html/tables.html",d) Table.html {% for c in data1 %} <tr> <td>{{c.Student_id.id}}</td> <td>{{c.Student_id.Student}}</td> <td>{{c.Student_id.Father}}</td> <td>{{c.Student_id.Date}}</td> <td>{{c.Course_id.course }}</td> <td>{{c.Student_id.Gender}}</td> <td><a type="button" class="btn btn-success" href="../editid/{{item.id}}">Edit</a>&nbsp;<a type="button" class="btn btn-success" href="../deleteid/{{item.id}}">Delete</a></td> </tr> {% endfor %} -
How To Properly Display SVG image when converting HTML to PDF Using Reportlab
I have been playing with Reportlab and Django all day today, and I finally have it working with the help of this SO issue earlier today...https://stackoverflow.com/questions/54565679/how-to-incorporate-reportlab-with-django-class-based-view/54566002#= The output is now being produced as a PDF as expected. However, I can't get an image to display when the output is produced as a PDF. Nothing renders. I have tried investigating my URLS, my absolute URLs in my settings.py file and nothing. I've noticed I can't get my template to pick up any of my static settings, yet the rest of my project is working fine with the same references. I also found this very similar SO issue, but can't seem to determine the actual fix....html template to pdf with images My utils.py file... from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None My HTML template file... <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Title</title> <style type="text/css"> body { font-weight: 200; font-size: 14px; } .header { font-size: 20px; font-weight: 100; text-align: center; color: #007cae; } .title { font-size: … -
Setting up pagination for list method in Django Rest framework viewset
I have a Viewset which has the following list method: class PolicyViewSet(viewsets.ViewSet): def list(self, request): queryset = Policy.objects.all() serializer = PolicySerializer(queryset, many=True) return Response(serializer.data) This works as intended and I get my desired Response.However, now I am trying to limit the objects returned per GET request and for that I am using pagination.I have defined the following in the settings.py: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 20 } The docs say: Pagination is only performed automatically if you're using the generic views or viewsets. However, my result is still not paginated.What else do I need to do to enable pagination ? -
missing 1 required positional argument: 'on_delete' django-audit-log
I'm trying to have logs on one of my models by using the django-audit-log package. I've installed the package using pip and added 'audit_log.middleware.UserLoggingMiddleware', to my middleware classes in my settings.py In my models.py file, I have imported the necessary... from audit_log.models.fields import LastUserField, LastSessionKeyField class Transaction(models.Model): title = models.CharField(max_length=100) updated_by = LastUserField() update_session = LastSessionKeyField() This is exactly how they have implemented those fields in the documentation at https://django-audit-log.readthedocs.io/en/0.7.0/change_tracking.html#tracking-who-made-the-last-changes-to-a-model Hence I can't see what I'm doing wrong. Even when I update the update_by field to include the on_delete argument, I get the same error when I try and make migrations. What am I missing?