Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding a scheduled task (cron) on the save action of model object
I have a model object which has day of month and time of that day stored in it. On the save action I want to create a cron job to execute on that day and time. I am using apscheduler (https://github.com/agronholm/apscheduler) and django-apscheduler (https://github.com/jarekwg/django-apscheduler) libraries. Unfortunately, when I save the object, I get following lines in debug: DEBUG:apscheduler.scheduler:No jobs; waiting until a job is added If I save the same object once again then the scheduler picks it up. The reason I deduced is that my code exits before the job is added to the scheduler. I tried may ways but now I am clueless how to implement is. scheduler.py import logging from apscheduler.schedulers.background import BackgroundScheduler from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job from django.conf import settings # Create scheduler to run in a thread inside the application process scheduler = BackgroundScheduler() scheduler.add_jobstore(DjangoJobStore(), 'djangojobstore') def start(): if settings.DEBUG: # Hook into the apscheduler logger logging.basicConfig() logging.getLogger('apscheduler').setLevel(logging.DEBUG) register_events(scheduler) scheduler.start() models.py def save(self, *args, **kwargs): # ToDo: check and update the scheduler for JMR from portal.scheduler import scheduler from django_apscheduler.jobstores import register_events from portal.functions import generate_jmr job_id= f'c_{self.company.id}_generate_jmr' job = scheduler.get_job(job_id=job_id) if job is not None: scheduler.remove_job(job_id=job_id) jmr_day = self.jmr_generation_date jmr_time: datetime.time = … -
How can I use a fieldset with a custom form?
I am trying to make a collapsible fieldset in a model. When I apply the fieldset it create a problem with some of the fields above. The problem is because I have some fields that are foriegn keys with a custom autocomplete form. And when I add these feilds to the fieldset they do not have the form which is needed. I have tried: fieldsets = ( (None, { 'fields': ('autocomplete_field_1', 'autocomplete_field_2', 'field_3'), }), ('advanced', { 'classes': ('collapse',), 'fields': ('field_4', 'field_5'), }), ) And I have tried only having the advanced fieldset, but that will not display autocomplete_field_1, autocomplete_field_2 or field 3. -
How to display details from database to html template in Django?
I am making a registration form with the help of medium.com. Admin display some information from database to html template using some syntax. But how to display email, portfolio site ? -
Advice on how to parse large and dynamic json results
I am looking for some advice on how to best automatically parse and display a large, dynamic json result to my Django app. The data comes from a variety of server hosts and it has a similar but content each time. The user would simply like to see the entire file in a nice, readable format. I am thinking tables. I don't want to create and manage template tags for each item in the file, but rather have them auto-created based on the contents. Note: I do have the data available as a {{ context }} tag in Django template, and the view, template parts are all working fine. For example, the following is just a snippet of the output coming from the json output, and I would like to create tables from this data auto-magically. "processes": [ { "id": "daq-emd", "status": "EXEC", "process_id": 6828, "started": "2019-08-20T05:20:26", "last_updated": "2019-09-09T16:53:09", "parameters": { "isExecuting": "1", "isRunning": "1", "physicalMemoryUsageMb": "162.48", "virtualMemoryUsageMb": "152.14" } }, { "id": "daq-extipxml", "status": "EXEC", "process_id": 7124, "started": "2019-08-20T05:20:24", "last_updated": "2019-09-09T16:53:09", "parameters": { "clientConnected": "1", "clientDisconnectedEvent": "1", "clientDisonnectedEvent": "0", "dataOutageEvent": "0", "incorrectMessages": "34876", "isExecuting": "1", "isRunning": "1", "lastAcknowledgedMessage": "30256", "lastAcknowledgedMessageSent": "4709086", "lastKeepAlive": "2019-09-09T16:52:36Z", "lastReceivedData": "2019-09-09T16:53:01Z", "last_Flightplan": "2019-09-09T16:53:00Z", "last_FlightplanUpdate": "2019-09-09T16:53:01Z", … -
How to solve horizontal scroll on Django admin pages
The problem is that on pages with long text in some fields list table becomes too wide and there is only one way to scroll it - you have to scroll to the bottom where you will find horizontal scroller. So if you need to see something on the right of the first row you will scroll down, right and back to top. This is very annoying. Is there a way to avoid scrolling without truncating data? Is there a way to add horizontal another scroller on top of the table? -
How can I insert data into the database using django form?
I am trying to use django form to insert some information into the database, but the insert is now working properly. This is for form page with some inputs that I am using. > <!DOCTYPE html> <html lang="en"> > <head> <!-- /Css --> <link rel = "stylesheet" type = "text/css" href = "../static/survey.css" /> <!-- /Css --> > <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>Preencha a pesquisa de satisfação</title> > > <style> > * { > box-sizing: border-box; > } > > input[type=submit] { > background-color: #4CAF50; > color: white; > padding: 10px 10px; > border: none; > border-radius: 4px; > cursor: pointer; > float: right; > } > > input[type=submit]:hover { > background-color: #45a049; > } > > .col-25 { > float: left; > width: 50%; > margin-top: 6px; > } > > .col-75 { > float: left; > width: 100%; > margin-top: 5px; > } > > /* Clear floats after the columns */ > .row:after { > content: ""; > display: table; > clear: both; > } > </style> <!-- /Fonts --> <link href='https://fonts.googleapis.com/css?family=Comfortaa' > rel='stylesheet'> <link > href="https://fonts.googleapis.com/css?family=Poppins:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900" > rel="stylesheet"> <!-- /Fonts --> </head> <body> > > <h2>Pesquisa de satisfação</h2> … -
How to filter posts by a specific user in Django?
I want to set up a newsfeed website for my college. There must be tabs in the navbar like, Current News, Literary Society, Clubs, Placement News etc. How do I go about making those tabs functional? For e.g., Current News will be the homepage, Literary Society will show the posts by a user named 'Literary Society' and so on.I'm a beginner and all this is just overwhelming me. Please help me out. -
Make a Django post request to ManyToManyField
This is my List in the HTML document I have a Django post view, when I hit send I want the selected users to be posted to the students field. As you can see I have tried to do the instance and user thing from this url but I can't figure it out! HTML: {% for elev in elever %} <div class="custom-control custom-checkbox"> <span class="d-flex align-items-center"> <div style="margin-right: 10px"> <div class="circle" style="background-color: {{ elev.color }}"> <span class="initials" , style="color: #ffffff"> {{ elev.user|capfirst|first }} </span> </div> </div> <div style="width: 300px"> <span class="h6 mb-0" data-filter-by="text">{{elev.user|capfirst}}</span> </div> <div class="checkboxx"> <input type="checkbox" name="Studyplan-Canview" value= "{{ student.name }}"> <style> .checkerName { margin-left: 10px } .checkboxx { align-content: flex-end; margin-left: 300px } </style> </div> </span> </label> </div> {% endfor %} The View: #post request checker @login_required def skapa_studieplan(request): if request.method == 'POST': name = request.POST.get('Studyplan-Name') description = request.POST.get('Studyplan-Description') parent_assignment = Assignment.objects.get(pk=request.POST.get('Studyplan-PAID')) users = UserProfile.objects.all() instance = Studyplan.objects.create(request.POST.get('Studyplan-Canview')) for user in users: instance.canview.add(user) studyplan = Studyplan(name=name, description=description, parent_assignment=parent_assignment, canview=instance) studyplan.save() return redirect('allaStudieplaner') -
How to prepopulate an each formset line from select option?
I am using Django for an project. The target is to implement an invoice table using Django formset. I want now when i will select an option, the other fields of a formset line will be prepopulated. For dynamic adding and deleting formset row, i use jquery.formset.js found on github. It is difficult to realize it simply for me because formset structure is not so clear for me and i have not the level in javascript. I would want help about how to prepopulate other fields from selecting option. Reminding that for table, i use django formset employing jquery.formset.js script. -
Django constraints: if foreignkey is empty, then field must be true
I'm reading Django's documentation on CheckConstraint to avoid overriding the .save() method to achieve this behavior: MyModel(models.Model): user = models.ForeignKey(User, null=True) is_default = models.BooleanField() if m.user is None and m.is_default -> valid if m.user is None and not m.is_default -> invalid if m.user is not None and m.is_default -> invalid if m.user is not None and not m.is_default -> valid Basically, I want is_default to be true only if user is assigned. Can I do this with CheckConstraint or am I forced to override the .save() method? -
Django ImportError: cannot import name 'designs' view in Users URLs
I'm using the Cookiecutter-django boilerplate for a project. I'm able to successfully create migrations and migrate but getting an import error that appears when I run server. Here's the traceback: File "/Users/username/Desktop/workspace/project/config/urls.py", line 16, in <module> path("users/", include("project.users.urls", namespace="users")), File "/Users/username/miniconda3/envs/cl/lib/python3.6/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/Users/username/miniconda3/envs/cl/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/username/Desktop/workspace/project/project/users/urls.py", line 3, in <module> from project.designs.views import designs, popular ImportError: cannot import name 'designs' Here is the urls.py file referenced above: from django.urls import path from project.designs.views import designs, popular from project.users.views import (user_detail_view, user_redirect_view, user_update_view) app_name = "users" urlpatterns = [ path("~redirect/", view=user_redirect_view, name="redirect"), path("~update/", view=user_update_view, name="update"), path("<str:username>/", view=user_detail_view, name="detail"), path('', popular.top_designers, name='designs_top_designers'), path('<username>/', designs.designer_designs, name='designs_designer_designs'), ] And here's the designs.py file called on line 3 of the urls.py file above: ... from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.mail import mail_admins ... ... from ..forms import DesignFlagForm, DesignForm from ..models import Design, DesignFlag, Images … -
How to copy and change a property of many models from a queryset, in batch?
I'm aware that you can force copying an instance of a model by settings its pk to None and saving myModel = MyModel.objects.get(..) myModel.pk = None myModel.save() # -> Creates a new copy What if I want to do this on an entire queryset? MyModel.objects.filter(...) Should I iterate over this and do it one-by-one? Or can this be made more efficiently? Use case: Every time a new user is created, I need to copy a bunch of models and related models that I assign to him by default: def save(self, **kwargs): super(User, self).save(**kwargs) for c in MyModelCategory.objects.filter(mymodel__is_default=True): c.pk = None c.user = self.user c.save() for s in MyModel.objects.filter(category=c): s.pk = None s.user = self.user s.save() -
transfer to heroku impossible
hello the setting in production is impossible explanation I have a problem with heroku when I try to put in production it tells me that the static files does not work that's what i tried since the problem always appear because there is some backage that does not work together i create a venv and i install that library necessary` code requirement.txt(certifi == 2019.6.16, chardet == 3.0 .4, dj-database-url == 0.5.0, Django == 2.2.5 django-heroku == 0.3.1 django-tinymce4-lite == 1.7.5, 19.9.0 gunicorn ==, IDNA = = 2.8, JSMin == 2.2.2, 6.1.0 == Pillow, pipenv == 2018.11.26, psycopg2 == 2.8.3, pytz == 2019.2, requests == 2.22.0, sqlparse == 0.3.0, urllib3 == 1.25.3, virtualenv == 16.7.5, virtualenv-clone == 0.5.3, 4.1.3 == whitenoise) view that she works properly locally I hope she walks in heroku -
Create M2M Relationship in post_save Signal
What is the proper way to create M2M relationships during a post-save signal? I have the below code. It successfully creates two Articles and a Blog but does not save the relationship between the two. from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class Article(models.Model): title = models.CharField(max_length=250) class Blog(models.Model): title = models.CharField(max_length=250) articles = models.ManyToManyField(Article, blank=True) def set_related_articles(self): article_titles = ['a', 'b'] for title in article_titles: _blog = Article(title=title) _blog.save() self.articles.add(_blog) @receiver(post_save, sender=Blog) def blog_post_save(sender, instance, **kwargs): instance.set_related_articles() -
django-rest-framework, adding 'includes' to list response, with pagination
With an API I am currently working on in django-rest-framework, I am attempting to implement something similar to a feature in the json-api standard. Given a book model: class Book(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(Author, on_delete=models.CASCADE) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) I want to include a parameter in the url, include, which lets the user define if they want to include author and publisher models in the response. The additional gotcha, is I am using limit/offset pagination. Thus, the following url: https://my-api-domain/api/books?limit=5&offset=0&include=authors should return something that looks like: { "count": 152, "next": "https://my-api-domain/api/books/limit=5&offset=5&include=authors" "previous": null, "results": [ {"id": 1, "title": "Book 1", "author": 1, "publisher": 18}, {"id": 2, "title": "Book 2", "author": 2, "publisher": 26}, ... ], "include": { "authors": [ {"id": 1, "first_name": "Author", "last_name": "One"}, {"id": 2, "first_name": "Author", "last_name": "Two"}, ... for all author ids in paged `results` field above ] } } So far, my view looks like: class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer permission_classes = (IsAuthenticated,) pagination_class = LimitOffsetPagination filter_class = BookFilterSet filter_backends = [DjangoFilterBackend] def list(self, request, *args, **kwargs): # Grab include from url parameters include = request.query_params.get('include', None) # Apply incoming filters to books queryset = self.filter_queryset(self.get_queryset()) # Apply pagination to … -
How do I refrain from showing repeat datetime data in a django template forloop?
In a django template, I'm accessing objects in a list filtered by the objects' datetime. Here's a current image of the object_list onto an HTML table: The time part of the datetime ("11:50a.m") must remain regardless of duplicates. However, the date part of the datetime ("September 9"), must appear only once for each unique date. Essentially, what I'm looking for would look something like: How would I go about achieving this effect? I've tried using {% if forloop.first %}, but I'm unable to find a way to target all "firsts" of unique dates. This is the current code which corresponds to the first image: {% for event in object_list %} <tr> <td>{{ event.datetime|date:"F j g:ia e" }}: </td> <td><a href="{% url 'detail' event.id %}">{{ event.venue }}</a></td> </tr> {% endfor %} I've also considered not using the date of the datetime object and manually coding the dates in the HTML, but wouldn't know how to eventually tie the DOM date to the object_list according to date. -
Trying to get rid of help text in Django results into error: a list indices must be integers or slices, not str
I am trying to get rid via backend (not with CSS) of help text underneath the user field in a custom User UpdateView. This is my code: class UpdateCustomUser(UpdateView): model = User fields = ['username', 'first_name', 'last_name', 'email'] template_name = 'auth/user_update_form.html' context_object_name = 'current_user' def __init__(self, *args, **kwargs): super(UpdateCustomUser, self).__init__(*args, **kwargs) for fieldname in ['username', 'first_name', 'last_name', 'email']: self.fields[fieldname].help_text = None def get_object(self, queryset=None): return self.request.user Unfortunately, this is the error I get: list indices must be integers or slices, not str I do not understand why this is happening, considering the code I use to get rid of the help text in the user creation form works perfectly and does not throw any error: class CustomUserForm(UserCreationForm): email = models.EmailField(max_length=200, help_text='Required') first_name = models.CharField(max_length=200) def save(self, commit=True): user = super(CustomUserForm, self).save(commit=False) # user.email = self.cleaned_data['email'] if commit: user.save() return user def __init__(self, *args, **kwargs): super(CustomUserForm, self).__init__(*args, **kwargs) for fieldname in ['username', 'password1', 'password2']: self.fields[fieldname].help_text = None class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') -
Django office365
How can we add office365 login to our django application login? So I need to add some authentication to my user in django. And similarly how would I be able to use this user in the request parameter. -
How can I add headers to compress statics on a django server in response headers?
Now I am working on site optimization. I use the pagespeed service. Writes that need to compress static files. In the documentation of Django, I found the middleware who is responsible for this, added it. Added file compression headers to request headers. Response headers HTTP/1.1 200 OK Content-Length: 23183 Content-Type: application/javascript Date: Mon, 09 Sep 2019 14:18:34 GMT Last-Modified: Fri, 06 Sep 2019 09:09:22 GMT Server: WSGIServer/0.2 CPython/3.6.8 Request headers Accept: */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9,ru;q=0.8 Cache-Control: no-cache Connection: keep-alive Cookie: csrftoken=Lp7qIg3c8hrfWa1GhP2V104Zfem6hz5z63jbLDQHAxxUARRsEgCGZ9pApd4auNfV Host: 22186d6d.ngrok.io Pragma: no-cache Referer: https://22186d6d.ngrok.io/ Sec-Fetch-Mode: no-cors Sec-Fetch-Site: same-origin User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 But they need to be added to the response headers, so that pagespeed protects this item. How can I do that? The Django's server is used. Link for check page from pagespeed - https://developers.google.com/speed/pagespeed/insights/?url=https%3A%2F%2F22186d6d.ngrok.io -
Relationship between the client and the company
I have a problem with the relationship between the client and the company. The requirement is this: 1) A client can be a client from many companies. 2) A company can have many clients. class Company(models.Model): name = models.CharField(max_length=30) users = models.ManyToManyField('User') def __str__(self): return self.name class User(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name I read that this should be a ManyToManyField relationship. But where should it be in the Company model or in the Client model? -
How can I filter manytomany models?
I would like to filter my plots objects on the fruit ex.pear. The Inputs are linked via a manytomany to the plots. This is the structure: This is the data I get out of it: What i would like to have: result: I tried the following: plots = Plot.objects.filter(fruittype__fruit="Pear") inputs = Input.objects.filter(plot__in=plots).distinct() This gives me already a close solution for my problem but not what I want. Now I only would like to filter out the other plots that still show up with apple. -
How to configure a Django application served by uswgi and started by a systemd service?
I'm trying to configure a basic a Django application served by uwsgi so that it can be started from systemd on a CentoS 7.X server. So far my SystemD service is started (active and in running state) but application is not reachable on the configured port. Note that application is running inside a Python virtual environment. Systemd service is active and running uwsgi worker processes are active socket bind to TCP 8003 is in LISTEN state SystemD unit file # /etc/systemd/system/django_03.service [Unit] Description=My Django app Requires=network.target After=network.target After=syslog.target [Service] TimeoutStartSec=0 RestartSec=10 Restart=always User=myuser KillSignal=SIGQUIT Type=notify NotifyAccess=all StandardError=syslog RuntimeDirectory=uwsgi ExecStart=/bin/bash -c 'cd /opt/scripts/django/django_03; source django_03_env/bin/activate; uwsgi --ini /opt/scripts/django/django_03/django_03.ini' [Install] WantedBy=multi-user.target uwsgi configuration file # /opt/scripts/django/django_03/django_03.ini [uwsgi] module = wsgi:application master = true processes = 5 socket = 127.0.0.1:8003 chmod-socket = 664 vacuum = true die-on-term = true Django application # wsgi.py def application(environ, response): response('200 OK', [('Content-Type', 'text/html')]) return [b"Test OK (Django 03) !!"] Thanks for your help -
How do I set up html redirection in google docs?
I am looking for a way to open a file generated by the Django function in Google Documents. For this I use the pydrive library. Now I have a function that forms an html instanse class CvView(AuthorizedMixin, View): """Employee CV view.""" def get(self, request, employee_id, format_): """Returns employee's CV in format which is equal to `format_` parameter.""" employee = get_object_or_404(Employee, pk=employee_id) user = request.user content_type, data = Cv(employee, format_, user).get() if isinstance(data, BytesIO): return FileResponse( data, as_attachment=True, filename=f'cv.{format_}', content_type=content_type) return HttpResponse(data, content_type=content_type) It generates a new html template and opens in a new page of my site. But I need to make sure that the html context (data variable in my function) opens in the user's google docs. To check, I created a new file with the code from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() gauth.LocalWebserverAuth() gauth.LoadCredentialsFile(gauth) drive = GoogleDrive(gauth) textfile = drive.CreateFile() textfile.SetContentFile('test.txt') textfile.Upload() and created the client_secrets.json file with Google account access in the same folder. After the direct start of the file I got Authentication successful message. Then I wrapped the code with a function def file_to_gd(file): from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() gauth.LocalWebserverAuth() gauth.LoadCredentialsFile(gauth) drive = GoogleDrive(gauth) … -
how to use a column value as a key in json field with django orm and postgres?
I need to find how build a query with django orm I need to find how build a query with django orm I have two tables with a relation one to many. table A id = integer autonumeric data = postgres json ... table B id = integer autonumeric id_A = table A id name = string t_name = string like slug the A.data have a json with the structure {key (t_name of table B): value (is a string value)} so that the definition of entities (name and t_name) are in the table B and the values of that entities ere in the json structure in the table A. eje: Table A id | data 1 |{"a_01":"value a","a_02":"value a","b_01":"value b"} 2 |{"a_01":"value a","b_01":"value b"} Table B id | id_A | name | t_name 1 | 1 | A | a_01 2 | 1 | AA | a_02 3 | 1 | B | b_01 4 | 2 | A | a_01 5 | 2 | B | b_01 the id_A and t_name are uniques together I need to get the items from table A with name (B.name) and value (A.data."t_name") from django orm this query solve my problem but I … -
Advanced queryset sort ordering - won't order as I would like
I'm trying to get a queryset to order in a specific way and can't figure out how to do it. First I'd like it to order by descending end_date - with any empty end_date records grouped first. Then the list should be ordered by the primary field, followed by descending amount. queryset = MyModel.exclude_denied.filter(user=user).order_by( "end_date", "primary", "-amount" ) This is what I currently have but it doesn't quite return it as I'd like it. I want the groups to appear something like this: Items without end_date primary items listed first, then ordered by desc amount Items with end_date primary items listed first, then ordered by desc amount Is trying to create this order just using order_by the appropriate approach? I feel like it's close - but not quite there. I am thinking a better approach would be to create 2 Querysets, then merge them together keeping their order in place. Something like this: Queryset1 = items without end_date, descending primary, then descending amount Queryset2 = items with end_date (desc), descending primary, then descending amount Combine the two Querysets but keeping Queryset1 items listed in order first, then Queryset2 items listed. I'm not sure the best way to accomplish that though, …