Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
chrome makes null endpoint request in django service
My env is django backend , vuejs from vite frontned. also using django-vite package in backend and nginx for proxy server. But when I depolyed all code to server, now I am getting null endpoint request. I can only see it in chrome browser. It doesn't appear in IE edge. Why does it happend? Do you guys have any idea? I left screenshot and service url http://3.35.61.148/ Can it be related to not using SSL(https) ? -
django allauth multiple custom forms for social sign up
I want to build 2 different custom forms, one for google sign up accounts, and one for facebook sign up accounts. Yet allauth only allow one custom form for all social sign up via the settings.py: SOCIALACCOUNT_FORMS = {'signup': 'accounts.forms.SignupFormSocial'} Is there a way to this ? Like pass in two different form to the overriden forms so I can choose which one to show based on the current provider. -
How to add extra per-Feed fields to a Django Feed (Specifically, a Django-iCal feed)
I am generating a per-user calendar feed. As part of the URL, I'm allowing event filters. I am struggling to figure out how to save that filter (or any arbitrary variable) to the specific Feed I am generating from the specific call. The method I thought would work is (coming from a C++ world) making a static variable that is shared amongst all Feed callers, which would lead to inconsistency when Feeds are being generated simultaneously. What is the proper way to do this? Reading through the Feed libraries, I see methods like feed_extra_kwargs() and item_extra_kwargs(), but I can't find examples or documentation on them that show how to use them. My URL: re_path(r'^ics/(?P<user_id>\d+)/(?P<params>[\w=;]+)/ical.ics$', EventFeed(), name='ics'), My Feed attempt: class EventFeed(ICalFeed): """ A simple event calender """ product_id = '-//icevite.com//Schedule//EN' timezone = 'UTC' file_name = "icevite.ics" filter = [] alarms = [] def get_object(self, request, user_id, params, *args, **kwargs): self.filter = [] try: split = params.split(";") for s in split: item = s.split("=") match item[0]: case "f": self.filter = list(item[1]) case "n": mins = int(item[1]) if mins: self.alarms.append(mins) return Player.objects.get(id=user_id) except: return None def items(self, player): responses = Response.objects.filter(mate__player=player) if self.filter: filtered = responses.exclude(response__in=self.filter) else: filtered = responses return filtered.select_related('game', … -
having trouble with saving the value of "gender" in update page
and I amd making a CRUD project,I have used radio button's for genders:male /female. I am able to successfully add the genders while adding new employee, however while updating the details, the gender which I selected isnt saved in the 'update' page. below is the code for gender in the 'Insert' page <tr> <td>gender</td> <td> <input type="radio" value="male" name="gender">male | <input type="radio" value="female" name="gender">female </td> </tr> below is the code for my 'Edit' page Male:<input type="radio" value="{{EmpModel.gender}}"> Female: <input type="radio" value="{{EmpModel.gender}}"> Since I am not sure what value I am supposed to put here, I added EmpModel.gender for both please help -
Pagination for Django search results (python)
I want to add pagination to my search results in django. This is my search function form views.py for the relevant (Jobs) module: def search(request): queryset_list = Job.objects.order_by('-publishing_date') if 'keywords'in request.GET: keywords = request.GET['keywords'] if keywords: queryset_list = queryset_list.filter(description__icontains=keywords) if 'state' in request.GET: state = request.GET['state'] if state: queryset_list = queryset_list.filter(location__iexact=state) if 'job_type' in request.GET: job_type = request.GET['job_type'] if job_type: queryset_list = queryset_list.filter(job_type__iexact=job_type_choices) if 'industry' in request.GET: industry = request.GET['industry'] if industry: queryset_list = queryset_list.filter(industry__icontains=industry_choices) if 'salary' in request.GET: salary = request.GET['salary'] if salary: queryset_list = queryset_list.filter(salary__lte=salary) context = { 'location_choices':location_choices, 'salary_choices':salary_choices, 'job_type_choices':job_type_choices, 'industry_choices':industry_choices, 'jobs':queryset_list, 'values':request.GET, } return render(request, 'jobs/search.html', context) This is pagination function from the same file: def index(request): jobs = Job.objects.order_by('-publishing_date').filter(is_published=True) paginator = Paginator(jobs, 6) page = request.GET.get('page') paged_jobs = paginator.get_page(page) context = { 'jobs': paged_jobs } return render(request, 'jobs/jobs.html', context) Both of them work (search returns results and pagination works on listing page) however I want to have pagination too for my search results. I am very new to python and django, and assume there is more elegant way of writing my search function, so please do not hesitate to let me know your thoughts. -
How to configure my django settings.py for production using postgresql
I'm already deploying my django app. However, I don't know what I should place in my host instead of using localhost. note: this works perfectly if I run it locally. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'trilz', 'USER': 'postgres', 'PASSWORD': 'franz123', 'HOST': 'localhost', 'PORT': '5432', } } -
Unable to run index migration in OpenSearch
I have a docker compose running where a django backend, opensearch & opensearch dashboard are running. I have connected the backend to talk to opensearch and I'm able to query it successfully. I'm trying to create indexes using this command inside the docker container. ./manage.py opensearch --rebuild Reference: https://django-opensearch-dsl.readthedocs.io/en/latest/getting_started/#create-and-populate-opensearchs-indices I get the following error when I run the above command root@ed186e462ca3:/app# ./manage.py opensearch --rebuild /usr/local/lib/python3.6/site-packages/OpenSSL/crypto.py:8: CryptographyDeprecationWarning: Python 3.6 is no longer supported by the Python core team. Therefore, support for it is deprecated in cryptography and will be removed in a future release. from cryptography import utils, x509 Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 224, in fetch_command klass = load_command_class(app_name, subcommand) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 37, in load_command_class return module.Command() File "/usr/local/lib/python3.6/site-packages/django_opensearch_dsl/management/commands/opensearch.py", line 32, in __init__ if settings.TESTING: # pragma: no cover File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 80, in __getattr__ val = getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'TESTING' Sentry is attempting to send 1 pending error messages Waiting up to 2 seconds Press Ctrl-C to quit I'm not sure where I'm going wrong. Any help would be … -
How to display ID for each form in Django Formset
Need to make the UI more ordered, can i have indexing for the forms in formset or access the form ID? <div class="card"> <div class="card-body"> <div id="form-container"> {% csrf_token %} {{ formset1.management_form }} {% for form in formset1 %} <div class="test-form"> {% crispy form %} </div> {% endfor %} <button id="add-form" type="button" class="btn btn-primary">Add Another Request </button> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </div> -
Upload PDF File via Django Admin, Users Download from Link on Template
I'm trying to allow users to download a PDF file that I've previously uploaded to the MEDIA_ROOT folder via the admin console. I've emulated the answer in this post, however it's incomplete and I can't figure out how to fix this. Hoping someone can spot my issue in the code below. settings.py # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = str(BASE_DIR) + "/media/" # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '/media/' # Absolute path to the directory that holds static files. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = str(BASE_DIR) + "/static/" # URL that handles the static files served from STATIC_ROOT. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' models.py from django.db import models # Create your models here. class ResumeModel(models.Model): pdf = models.FileField(upload_to="resume_app/media/resume/") # So this file gets uploaded to root > media > resume_app > media > resume admin.py from django.contrib import admin from .models import ResumeModel # Register your models here. admin.site.register(ResumeModel) views.py from django.shortcuts import render from .models import ResumeModel # Create your views here. … -
Cannot save model inside celery task exception?
I have a chain of celery tasks to manage talking to an older XML polling based API, so I need to be able to make one call to a remote API per task, and pass the results to the next task. Some of these APIs throw weird errors, so I'm trying to come up a general way to catch and make sure all my errors end up in the database so I have an audit trail of what happened. No matter what I've tried, when I try to write to the database from within a caught exception block, it refuses to save it. I assume there's something going on in Django, but I can't find much to suggest why in the docs. I know I'm catching the error, because I do see log entries. I'm trying to do something like the following: import traceback import sys import logging log = logging.getLogger('daniTest') @celery_app.task() def dmtest(d:dict): log.info(f'DM: Test: dict: {d}') try: raise Exception('Just a test.') except Exception as e: exc_info = sys.exc_info() errStr = ''.join(traceback.format_exception(*exc_info)) log.error(errStr) # d has a jobId key I can use to link to DB: dbJob = MyModel.objects.get(job_id=d['jobId']) dbJob.error_messages = errStr dbJob.save() Is there a way to make … -
ValueError: source code string cannot contain null bytes when I install a new requirements.txt file
I did a pip install -r requirements.txt and after that, realized that my development server could nolonger start. I have been unable to tell which of the files installed caused this. I even tried to re-install a previous requirements.txt file I had before this one but the nothing changed. Could anyone be having a clue on what exactly is happening from this traceback message? Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File … -
Django templates using buttons for Boolean fields
I have a preferences page that has many Boolean fields. I created an UpdateView and when I use {{ form.as_p }} in my template it works, but I am trying to create individual buttons for each option instead of checkboxes. I couldn't find a way to make it work in my template. models.py class Preference(models.Model): user = models.OneToOneField("User", on_delete=models.SET_NULL, null=True) option1= models.BooleanField(default=False) option2= models.BooleanField(default=False) option3= models.BooleanField(default=False) option4= models.BooleanField(default=False) views.py class preferencesview(UpdateView): model = Preference form_class = PreferenceForm success_url = reverse_lazy("profiles:preferences") forms.py class PreferenceForm (forms.ModelForm): class Meta: model = Preference exclude = ['user'] I want to have individual buttons for each option and a submit button to save the changes. Please let me know if you have any documentation or tutorials. Thanks! -
Django-Tables2-Column-Shifter <frozen importlib._bootstrap> Error When Getting Table Class
I am using the Django-Tables2-Column-Shifter Django library successfully in my Django application from one of my applications named app1. I am running into a bizarre error when attempting to use the same logic to use Django-Tables2-Column-Shifter from another app app2 which uses a different model. The error that I am receiving is below: File "/home/datavizapp/.virtualenvs/venv/lib/python3.9/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'project_name' The code posted below all works as expected. The error arises in the get_table_class code when I change the following: tabledata_table = get_table_1_class( self.table_class_version )(tabledata_queryset) to tabledata_table = get_table_2_class( self.table_class_version )(tabledata_queryset) Below is "views.py" inside app2 from project_name.app1.models import Table1 from project_name.app2.models import Table2 from project_name.app2.tables import get_table_1_class from project_name.app2.tables import get_table_2_class #from project_name.app1.tables import get_table_1_class # This also works if uncommented (original code is in app1) from django_tables2_column_shifter.tables import ( ColumnShiftTableBootstrap4 ) from … -
Got error when trying to remove auth and user tables in Django migration
I am using Django to create rest apis. But as I notice whenever I migrate tables to databases tables such asauth_ user_ got migrated as well. I want to prevent that so I remove some rows of INSTALLED_APPS in settings.py INSTALLE D_APPS = [ # 'django.contrib.admin', # 'django.contrib.auth', # 'django.contrib.contenttypes', # 'django.contrib.sessions', # 'django.contrib.messages', # 'django.contrib.staticfiles', 'devices', 'django_crontab', 'drf_yasg', ] But I go this error, when trying to run py manage.py makemigrations. Traceback (most recent call last): File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\registry.py", line 156, in get_app_config return self.app_configs[app_label] KeyError: 'admin' ...................... LookupError: No installed app with label 'admin'. -
Django: Is it possible to get field values for a list of objects in bulk?
This is probably a silly question, but for some reason I just cannot find a way to do this: I am working on a recommendation engine in Django, which recommends movies based on the similarities between your taste and other users' tastes. Since every database access takes time, I try to use bulk methods as much as possible. However, at one point I need to get the movie that is associated with a certain vote, and I just cannot figure out how to do this in bulk: The relevant models are: class Movie(models.Model): id = models.AutoField(primary_key=True) ... voters = models.ManyToManyField(Voter) ... and class MovieVote(models.Model): rating = models.FloatField() weight = models.FloatField() voter = models.ForeignKey(Voter, on_delete=models.CASCADE, null=True) movie = models.ForeignKey(Movie, on_delete=models.CASCADE, null=True) ... And the one line that currently takes 80%(!) of the time of the whole recommendation process is: for otherVote in listOfOtherVotes: ... movie = otherVote.movie ... Is there any way to look up the foreign key "movie" for the whole list of votes at once? And ideally return it as a dictionary that maps each vote to the movie? -
Iterate through fields using array Django
I have this model: class Some_model(models.Model): field_1 = models.CharField(max_length=200, blank=True, null=True) field_2 = models.CharField(max_length=200, blank=True, null=True) and this function: # create a function to upload a model object given a json object def upload_object_values(model, json_values, keys=None): if json_values: # assign a value to each key which is a the field in the given model for key, value in json_values.items(): setattr(model, key, value) # if the object has keys to check if keys: # check if exists using the keys when called like this: upload_object_values(Some_model(), {'field_1': 'val', 'field_2': 'val_2'}, ['field_2']) It would do a get or create inside the upload_object_values function using the fields inside the keys parameter (e.g.: field_2 as the parameter). Some_model.objects.get_or_create(field_2='val_2') -
PostgreSQL - compare python list to table rows
tried to look around on the internet for this for a while without success. I have a python list which looks like this: [{'id': 5, 'field1': True}, {'id': 6, 'field1': False}] It's just a list of dictionaries containing key/value pairs. Now, I'm asking myself whether there is any way to look up an SQL Table by every id in the list and only return the row if 'field1' is different. Say my table looks like: id field1 ----------- 5 True 6 True Given that the row with the id of field 6 differs in the value of field1, only that row should be included in the resulting query. Is there any way to achieve this with SQL or would I need to loop through it manually? My use case involves a lot of rows, and this process would be repeated many times, so I'm trying to find the most efficient way to do it. As a sidenote: I am using Postgres. Thank you! -
Making django server tick?
I have a django server setup on Linux/Apache/Mysql with WSGI (WGSIDaemonProcess/WGSIDaemonGroup/WSGIScriptAlias). I'd like to write a python function that has access to all the backend models and stuff that a normal view function has, and to have that function run periodically (perhaps once a second or faster) while the server is up. I guess I could write a new view function and then write a local script to GET that url every second, but is there a way of doing this within the django app itself? -
How to show the number of items from database according to drop down menu number in django?
I am new to django. I have 100 items in database, and i have dropdown menu number [1,5,10,20]. if i select 20 then i would like to show 20 items with 5 different pages. if i select 10, i would like to show 10 items in one page with 10 different pages in django. I would really appreciate it if you could tell me how to do that. I have no idea how to do it. I made HTML drop down menu with number, but how can i connect it to database, and populate and show it? <option value="1">1</option> <option value="5">5</option> <option value="10">10</option> <option value="20">20</option> -
Making button content dynamic
I have a subscribe button on the nav bar of my index.html, which leads a user to subsribe.html, where they get to fill in a form and the data gets stored in the data base. The users are then redirected back to the home page. I want to make it possible so that when a user finishes filling in the form and submits, and he is redirected back to the homepage, then the button changes from subscribe, to subscribed. But only for users who have already submitted the form. Users who have not yet subscribed will still see the button in its original format. Which is the best and easiest way to do this? I have tried doing it through vue, where I can use axios, but I have been unable to integrate the two applications. If there is an easier method like Ajax, or even CSS, then kindly please share the procedure index.html <div id="app"> <a href="subscribe"> <button type="button" class="btn btn-warning mx-5"> Subscribe </button> </a> </div> subscribe.html {% extends 'index.html' %} {% block subscribe %} <div class="card mx-5"> <h1 class="mx-5 mt-3"> Subscribe</h1> <form method="POST" enctype="multipart/form-data" action="subscribe"> {% csrf_token %} <div class="mb-3 mx-5"> <label for="firstname" class="form-label ">First Name</label> <input type="text" … -
Overriding django-allauth views to use with modals
I am trying to handle login/registration functionality in a modal. I got successful login/registration working by importing the LoginForm and RegistrationForm into my modal view and then posting to the appropriate allauth URLs. The desired behavior is to have forms with errors rendered asynchronously in the modal. I have not been able to get forms with errors (email doesn't exist when trying to login, passwords don't match when registering etc.) to render as an html partial in a modal with the errors. I'm not too sure where to start when trying to add this functionality into my own view/how to piggyback on the allauth views and change their functionality. Adding the below to my views.py and url.py I've managed to get the allauth default template to load when the form is invalid (e.g. email field does not contain a valid email) but have not been able to get my template to load. From views.py: class LoginViewSnippet(LoginView): success_url = reverse_lazy('home') template_name = 'user_app/partials/loginmodal.html' def get_context_data(self, **kwargs): print('here1') context = super(LoginView,self).get_context_data(**kwargs) return context def form_invalid(self, form): print('here') error_msg = 'error' return HttpResponse(error_msg, status=400) login = LoginViewSnippet.as_view() From urls.py: path('accounts/login',user_app_views.login, name='account_login'), From user_app/partials/loginmodal.html: ... <div class="modal-body"> <form id="loginform" method="POST" action="{% url 'account_login' %}" … -
How to fix Pinax Django project getting started migration ERROR?
I am following this guide https://pinaxproject.com/pinax/quick_start/ but at the "Modern Local Development Steps" after the follwing command I get an error: ./manage.py migrate ERROR: Traceback (most recent call last): File "/Users/iuser/myproject/myapp/./manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/Users/iuser/myproject/v1/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/iuser/myproject/v1/lib/python3.9/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Users/iuser/myproject/v1/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/iuser/myproject/v1/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/iuser/myproject/v1/lib/python3.9/site-packages/django/apps/config.py", line 126, in create mod = import_module(mod_path) File "/usr/local/Cellar/python@3.9/3.9.7/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/iuser/myproject/v1/lib/python3.9/site-packages/pinax/templates/apps.py", line 2, in <module> from django.utils.translation import ugettext_lazy as _ ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation' (/Users/iuser/myproject/v1/lib/python3.9/site-packages/django/utils/translation/__init__.py) -
Filter Django model with json values
I have this function: # create a function to upload an object one to one given a json def upload_object_values(model, json_values, update_if_exists=True): if json_values: # the json values contain key value that match to the model # use a copy to avoid runtime error dictionary changing size for json_value in json_values.copy(): # remove all ids in model copy if json_value[-3:] == '_id' or json_value == 'id': json_values.pop(json_value) # assign a value to each key which is a the field in the given model for key, value in json_values.items(): setattr(model, key, value) # if the object is get or create, or an update if exists if update_if_exists: # if it exists if model.__class__.objects.seal().exists(): # retrieve the existing object retrieved_object = model.__class__.objects.seal().filter(json_values).first() #TODO: filter the model with the json_values # assign values into it retrieved_object = model # save retrieved_object.save() print(retrieved_object) print('existing, saved successfully') # if it does not exist else: # save model.save() print('does not exist, saved successfully') # else just save else: model.save() print('created successfully') with sample json_values like: {'notes': '', 'name': 'test issuer', 'phone': None} I need to be able to filter using the json_values that I have, as shown in the line: retrieved_object = model.__class__.objects.seal().filter(json_values).first() #TODO: filter the … -
sending calendar in mails using django
I am using mandrill for sending mails after registering the events- mandrill_client = mandrill.Mandrill(MANDRILL_API_KEY) message = { 'html': template_func, 'from_email': 'email@xyz', 'from_name': 'any_name', 'global_merge_vars': [], # need reply mail 'headers': {'Reply-To': 'email@xyz'}, 'merge': True, 'merge_language': 'mailchimp', 'subject': "Event Registered", 'tags': ['password-resets'], 'text': 'Example text content', 'to': [{'email': to_email, 'name': user_name, 'type': 'to'}], } result = mandrill_client.messages.send(message = message) print(result) status = result[0]["status"] This is working fine. but I also want to send calendar. Is there a way to add calendar with mandrill or by any other method. Thank you! -
How to get the User id from the URL search input that contains first name & last name
I created a search bar, where users can search by name and/or the last name of other users. When they submit, it should take them to the profile page of that user based on the search name/last_name provided in the URL. The script from the template, where the search bar is - works ok: <script> new Autocomplete('#autocomplete', { search : input => { const url = `/search/?search_item=${input}` return new Promise(resolve => { fetch(url) .then(response => response.json() .then(data => { resolve(data.data) })) }) }, }) </script> urls.py path('search/', views.search_name, name='search_name'), views.py which generates list of Users in db matching search item: @login_required def search_name(request): search_item = request.GET.get('search_item') payload = [] if search_item: search_item_objects = User.objects.filter( Q(first_name__icontains=search_item) | Q(last_name__icontains=search_item)) for search_item_object in search_item_objects: payload.append(search_item_object.first_name + ' ' + search_item_object.last_name) return JsonResponse({'status':200, 'data': payload}) Now, I added onSubmit to the script - so the updated template is: <script> new Autocomplete('#autocomplete', { search : input => { const url = `/search/?search_item=${input}` return new Promise(resolve => { fetch(url) .then(response => response.json() .then(data => { resolve(data.data) })) }) }, onSubmit : result => { window.open(`/member/?search_item=${result}`) } }) </script> Here is what I'm getting: http://club/member/?search_item=Johny%20Bravo How to obtain the ID of the User having the URL {result} …