Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Convert Django DateField to usable value for React Calendar
I have read the documentation for the react-calendar: https://www.npmjs.com/package/react-calendar, I have read the documentation for django DateField, and I have read similar questions on stack overflow. My problem is trying to get the format YYYY MM dd that is saved in Django DateField to a usable value for the React calendar. I am currently trying to change the format using const value = (locale, date) => formatDate(date, 'YYYY MMM dd') and then calling the variable value when rendering the calendar component <Calendar value = {value}/> but I don't know where to put the date variable that I've saved. I currently have the date stored as a variable {club.next} which is dynamic for each page. -
Mailchimp integration with Django Tutorial not Working
I am trying to connect Mailchimp with my HTML form. I tried following this tutorial, but after writing everything up nothing is working. I don't receive any errors, but it won't add new emails to my list after submitting. here is the html: <section class="cta2"> <form action="{% url 'subscription' %}" method="POST"> {% csrf_token %} <div class="form-group"> <h2>Stay Up-to-Date</h2> <p>Join our newsletter to receive updates and first access to new features!</p> <input type="email" required id="email" placeholder="enter your email to subscribe"><input type="submit" id="submit" value="Join!"> </div> </form> <!-- message if email is sent --> {% if messages %} {% for message in messages %} <div class="my-5 alert alert-success"> <h5 class="m-0"> {{ message}} </h5> </div> {% endfor %} {% endif %} </section> here is my views.py: from django.shortcuts import render from django.http import HttpResponse from django.contrib import messages from django.conf import settings from mailchimp_marketing import Client from mailchimp_marketing.api_client import ApiClientError # Mailchimp Settings api_key = settings.MAILCHIMP_API_KEY server = settings.MAILCHIMP_DATA_CENTER list_id = settings.MAILCHIMP_EMAIL_LIST_ID # Subscription Logic def subscribe(email): """ Contains code handling the communication to the mailchimp api to create a contact/member in an audience/list. """ mailchimp = Client() mailchimp.set_config({ "api_key": api_key, "server": server, }) member_info = { "email_address": email, "status": "subscribed", } try: response … -
How to filter datetime from an interval of two dates in Django ORM
I'd like to filter an interval of two dates in one datetime on django ORM date_start = 2021-05-17 date_end = 2021-05-18 inspect_dt in database is datetime type, sample: 2021-05-17 06:56:59 2021-05-17 06:58:32 2021-05-18 06:58:37 2021-05-18 06:59:53 2021-05-18 07:00:25 I want to pass date_start and date_end, then filter it on inspect_dt What i tried: filteredDate= inspectionDate.objects.all().filter( inspect_dt__gt = date_start, inspect_dt__lt = date_end) filteredDate= inspectionDate.objects.all().filter( inspect_dt__contains = (date_start, date_end)) filteredDate= inspectionDate.objects.all().filter( inspect_dt__range = (date_start, date_end)) both returns were empty: [] -
Django-autocomplete-light not showing in bootstrap modal form
I am setting up a homepage which should include bootstrap modal forms. This part works fine. But as soon as I try to implement a Django-autocomplet-light (DAL) widget, things start to get complicated. I have this autocomplete view class TagAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Tag.objects.all() if self.q: qs = qs.filter(name_de__icontains=self.q) return qs which has the following url configuration urlpatterns = [ path('tag-autocomplete', views.TagAutocomplete.as_view(create_field='name_de'), name='tag-autocomplete'), path('sound-create/<int:category_id>', views.SoundCreateView.as_view(), name='sound-create'), path('image-create/<int:category_id>', views.ImageCreateView.as_view(), name='image-create'), ] I have two similar ModelForms: class ImageForm(forms.ModelForm): class Meta: model = Image form_tag = False fields = ('solution', 'image_file', 'difficulty', 'explicit', 'tags', 'category') widgets = {'tags': autocomplete.ModelSelect2Multiple(url='gamefiles:tag-autocomplete'),} class SoundForm(forms.ModelForm): class Meta: model = Sound form_tag = False fields = ('solution', 'sound_file', 'difficulty', 'explicit', 'tags', 'category') widgets = {'tags': autocomplete.ModelSelect2Multiple(url='gamefiles:tag-autocomplete'), } with the according views: class ParentCreateView(CreateView): def get_initial(self): return { 'category': self.kwargs['category_id'], } def form_valid(self, form): tags = form.cleaned_data["tags"] self.object = form.save() self.object.tags.add(*tags) return render(self.request, 'success.html', {'element': self.object}) class ImageCreateView(ParentCreateView): model = Image form_class = ImageForm template_name = 'image_create_form.html' def get_context_data(self, **kwargs): ctx = super(ImageCreateView, self).get_context_data(**kwargs) ctx['category_id'] = self.kwargs['category_id'] return ctx class SoundCreateView(ParentCreateView): model = Sound form_class = SoundForm template_name = 'sound_create_form.html' def get_context_data(self, **kwargs): ctx = super(SoundCreateView, self).get_context_data(**kwargs) ctx['category_id'] = self.kwargs['category_id'] return ctx My index.html loads some static … -
Indexing models and model fields in Django with managed=False
I have a simple question. Is there a way to create indexes for models and/or their fields if the models themselves are being imported from somewhere else, i.e., managed=False? I don't think Django will do it without migrating and I can't do that as the db is littered with tables that are not needed so I haven't created models for them. By the way, I'm using Postgresql. -
Does psycopg2.connect inherit the proxy set in this context manager?
I have a Django app below that uses a proxy to connect to an external Postgres database. I had to replace another package with psycopg2 and it works fine locally, but doesn't work when I move onto our production server which is a Heroku app using QuotaguardStatic for proxy purposes. I'm not sure what's wrong here For some reason, the psycopg2.connect part returns an error with a different IP address. Is it not inheriting the proxy set in the context manager? What would be from apps.proxy.socks import Socks5Proxy import requests PROXY_URL = os.environ['QUOTAGUARDSTATIC_URL'] with Socks5Proxy(url=PROXY_URL) as p: public_ip = requests.get("http://wtfismyip.com/text").text print(public_ip) # prints the expected IP address print('end') try: connection = psycopg2.connect(user=EXTERNAL_DB_USERNAME, password=EXTERNAL_DB_PASSWORD, host=EXTERNAL_DB_HOSTNAME, port=EXTERNAL_DB_PORT, database=EXTERNAL_DB_DATABASE, cursor_factory=RealDictCursor # To access query results like a dictionary ) # , ssl_context=True except psycopg2.DatabaseError as e: logger.error('Unable to connect to Illuminate database') raise e finally: logger.info('Successfully connected to Illuminate database') Error is: psycopg2.OperationalError: FATAL: no pg_hba.conf entry for host "12.345.678.910", user "username", database "databasename", SSL on Basically, the IP address 12.345.678.910 does not match what was printed at the beginning of the context manager where the proxy is set. Do I need to set a proxy another method so that the psycopg2 connection … -
Django CMS problemas url multilenguaje
Tengo un problema en una web multilengua con las urls al cambiar el idioma de la web. La web está montada con Django CMS 3.8 Únicamente me pasa con un las rutas de proyectos, al acceder en un determinado idioma, por ejemplo español y selecciono inglés, no me traduce el título del proyecto de la url y me aparece el siguiente error: Not Found The requested resource was not found on this server. Gracias -
Conditional column display, django-tables2
I have developed a table, using django-tables2 which shows records of a model. The last column of this table, is an "edit button" which leads user to the "edit page" of its row record. What I want is that the user can see the edit column only if she has permission to edit the model! Also I need to mention that currently I'm using SingleTableView to develop table view. -
Entries deleted from Django admin uploaded to Heroku reappears after a while
I created a project whose backend is handled by Django. While I was creating the project, I made few entries in the database for testing purposes. I uploaded the Django app to Heroku. Then I went to the admin page on my Heroku website to delete those test entries. The entries get deleted without any error but after few minutes all of the entries reappear and my new entries get deleted. I am using the SqlLite3 database. -
Creating and displaying pyvis graph from django app running sql backend
This is moreso a question about pyvis graphs, but also involves a django server running with a sqlite3 backend. One of my views needs to produce an interactive pyvis graph and display it in the clients browser. I can do this without the django app with the following code: import networkx from pyvis.network import Network nx_graph = networkx.Graph() network.from_nx(nx_graph) network.show('nx.html') As you can see with this method, pyvis creates an html file and save it to disk first. nework.show() simply opens the file in the browser. Because I will be running this on a django webapp, I would rather create the graph's html without saving it to disk, then just return it as a string in the HttpResponse for the view. -
Django how to update model field from QueryDict
I am a newbie in Django, maybe this will be a very simple question that I am not get the answer up until today. Straight to my problems. I have a submitted form and generated this: <QueryDict: {'csrfmiddlewaretoken': ['bla bla bla'], 'id_number': ['1', '5', '17'], 'Status': ['Registered', 'Pending', 'Confirmed']}> I want to update my model field after the admin click on Update button something like this: id# 1 --> Status change to Registered id# 5 --> Status change to Pending id# 17 --> Status change to Confirmed Very appreciate for the help... -
django.db.utils.OperationalError: no such table: theblog_category
I wanted to add tags to my blog in the same way as a category, unfortunately during "makemigrations" I got an error: "django.db.utils.OperationalError: no such table: theblog_tag" Then I tried every way I found, removed the migrations (except init.py) and db.sqlite3 and tried to do the migrations again. Unfortunately for now, the bug also affects the categories. Here is traceback: Traceback (most recent call last): File "C:\plantblog\virt\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\plantblog\virt\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: theblog_category The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\plantblog\blogplant\manage.py", line 22, in <module> main() File "C:\plantblog\blogplant\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\plantblog\virt\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\plantblog\virt\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\plantblog\virt\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\plantblog\virt\lib\site-packages\django\core\management\base.py", line 393, in execute self.check() File "C:\plantblog\virt\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\plantblog\virt\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\plantblog\virt\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\plantblog\virt\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\plantblog\virt\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\plantblog\virt\lib\site-packages\django\utils\functional.py", line 48, in __get__ res … -
want help on writing .circleci/config.yml file
I am going through a tutorial. In that tutorial I learn how to CI in Travis-CI. But as I am learner I am not able to find a way to write the same configure file in circleci. please help. .travis.yml to .circleci/config.yml Dockerfile FROM python:3.8-alpine ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D user USER user docker-compose.yml version: "3.9" services: app: build: context: . ports: - "8000-8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" .travis.yml language: python python: "3.8" services: docker before_script: pip install docker-compose script: docker-compose run app sh -c "python manage.py test && flake8" -
How to pip install django-auth-ldap on a Mac
I want to implement ldap for active directory auth in my Django app. The development is taken place on a Mac. After I ran pip install django-auth-ldap I got a bunch of errors. The reason might be, because I have no OpenLDAP libraries and headers installed. But how do I do it on a Mac? Appreciate any help. -
Django poor request response performance when using threads
I'm trying to optimize the response time on a specific endpoint so I try using vanilla threads to make things on parallel. The problem is that the performance does not seems to improve and actually removing the threads from the view is giving me half of the time, when it should be running in parallel. Here is some example: def myView(): do_a() return Response("ok") def myView(): do_a() thread = Thread(target=do_b) thread.start() return Response("ok") myView without the thread is taking 30ms when the view with the thread that should be running do_b in paralle is actually taking 60ms. I'm using django, django-restframework and mongodb when using the do_b thread (with djongo interface) What's my problem here? -
Javascript url refresh page not found in Django
I am getting page not found error when refresh the page. Page url is set through javascript and render through Django. Please help what's the issue? and how to solve this? urls.py urlpatterns = [ path('',views.index,name='index'), path('section/<int:num>',views.section,name='section') ] Javascript code function ShowSection(section){ fetch(`/section/${section}`) .then(response => response.text()) .then(text => { console.log(text); document.querySelector('#content').innerHTML = text; }); } document.addEventListener('DOMContentLoaded', function () { document.querySelectorAll('button').forEach(button => { button.onclick = function () { const section = this.dataset.section; history.pushState({section: section},'',`section${section}`); ShowSection(section); }; }); }); -
Central align field using FormHelper
I try put form field in central with some size of this field, but I have problem. It's look like on the screen. https://pastebin.com/fa8DLq1y class Test(forms.ModelForm): pole1 = forms.CharField() class Meta: model = User fields = ('pole1',) # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) helper = FormHelper() helper.form_class = 'form-horizontal col-md-6 m-auto' helper.field_class = '' helper.label_class = '' helper.layout = Layout( Row( Column( # Field('pole1', style='margin-left:200px'), Field('pole1', css_class='form-group m-auto'), ) ) ) -
Javascript in Django child HTML template not working
I am tried incorporating this onload Javascript effect but the effect is not happening. Here is my example.html: {% extends 'base.html' %} {% block content %} <div class="container"> <div class="row"> <div class="col-md-8 card mb-4 mt-2 left top"> <div class="card-body"> <div id="div1" style="margin:0px;width:100px;background:#666;border:1px solid black;position:relative;" >Waka Waka</div> {% block extra_js %} <script> $(document).ready(function() { $("#div1").effect("highlight", {}, 3000); //this will highlight on load $("#div1").click(function () { $(this).effect("highlight", {}, 3000); }); }); </script> {% endblock extra_js %} <!-- div { margin: 0px; width: 100px; background: #666; border: 1px solid black; position: relative; }--> <!-- <p class=" text-muted">{{ object.author }} | {{ object.created_on }}</p>--> <!-- <p class="card-text ">{{ object.content | safe }}</p>--> </div> </div> {% block sidebar %} {% include 'sidebar.html' %} {% endblock sidebar %} </div> </div> {% endblock content %} And here is my base.html: {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %} {% endblock %}</title> <link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet"> <meta name="google" content="notranslate" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> <!-- For accordions --> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <link rel="stylesheet" href="{% static 'css/highlight.min.css' %}"> <link ref="stylesheet" href="{% static 'ajax-live-search/css/ajaxlivesearch.min.css' %}"> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.3/highlight.min.js"></script> <script>hljs.initHighlightingOnLoad();</script> <script src="{% static 'ajax-live-search/js/ajaxlivesearch.js'%}"></script> <script src="{% static … -
Python WebAuthn: Unable to verify attestation statement format
I have implemented some sort of password-less authentication using DUO lab's webauthn using Django. However, I keep getting this error: Unable to verify attestation statement format.. when authenticating on my Android phone (at least for now). How can I include more attestation formats to incorporate Android, Windows hello and any other device in this library's attestation formats? -
How would I convert this datetime format into a DateTimeField using datetime.strptime()?
I have a list of strings formatted as follows: 10:00am - Tuesday, March 16, 2021' I have been messing around with datetime.strptime() and am not sure how to convert this correctly since it includes the name of the day of the week as well as the actual date. -
Based on user input generate a formset in django
Let's say, I have a dropdown as an input with the following options. Video games Food Sports By default, I display the Sports formset table which is a DB table that displays Sports info. When I select Video Games and submit a post request it should display the Video Games formset table. I initialize the formset if there's a post request: if request.method == 'POST': formset = display_formset(request.POST, form_kwargs=create_forms, initial=initial_values) if formset.is_valid(): for form in formset: print(form.cleaned_data) return HttpResponseRedirect("/home/") else: print('not valid') else: formset = display_formset(form_kwargs=create_forms, initial=initial_values) The issue I am facing: When I submit 'Video Games' the formset table displays the correct columns for the 'Video Games' formset table, but no data is being populated. It looks like the previous submitted 'Sports' data is getting passed into the request.POST argument in the formset That is why all the forms are empty and no data is being populated What I tried: I removed the request.POST argument from the formset and on user input the tables were getting displayed and were populated with the correct data. However, the formset was returning invalid because no data was being sent to the formset on a post request. Although everything was working on the … -
Different results when accessing Django polymorphic model via query or ORM
I've been using Django's model polymorphism for a while now without a problem, but I've suddenly run into something that's making me question my basic understanding of how this works. Here's basically how I've got things set up. from django.db import models from polymorphic.models import PolymorphicModel class Data(PolymorphicModel): parent = models.ForeignKey('Data', null=True, blank=True, on_delete=models.CASCADE) class Listing(Data): name = models.CharField(max_length=128) def __str__(self): return '%s (%d)' % (self.name, self.id) class Qualification(Data): target_listing = models.ForeignKey(Listing, on_delete=models.SET_NULL, blank=True, null=True) class Job(models.Model): data = models.ForeignKey(Data, on_delete=models.CASCADE, related_name="job_data") Long story short, Jobs can carry Data with them, which for now are of two types: Qualification and Listing. Qualifications themselves can point to a Listing. I suddenly noticed that in the admin site, a particular Qualification instance didn't have its target listing set, so I put in some print statements and discovered this. q = job.data print("job.data.id", job.data.id) // Yields 'job.data.id 20' print("q.id", q.id) // Yields 'q.id 20' print("job.data.target_listing", job.data.target_listing) // Yields 'job.data.target_listing myListing (12)' print("q.target_listing", q.target_listing) // Yields 'q.target_listing myListing (12)' qq = Qualification.objects.get(id=q.id) print("qq.target_listing", qq.target_listing) // Yields 'qq.target_listing None' !!!!! How can it be that I get different results when I access the apparently same data in different ways? Is my database corrupt or am … -
What things one should not store in cache? [closed]
Consider an Application like facebook, there is user data, timeline data, friends data etc. In such a backend application what things one should keep in mind while moving some data to cache. What principles you should know and follow while caching things. What things you should not cache. -
I Have created Custom User Model but i have "NO MODULE FOR managers.py"
I'm register my app in INSTALLED_APP but it showing no module that is "ModuleNotFoundError: No module named 'myapp.mangers' " help me!!!! 1.myapp/managers.py from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as lagy class UserManager(BaseUserManager): def create_user(self,email,password,**extra_fields): if not email: raise ValueError(lagy("Email Must ")) email =self.normalize_email(email) user=self.model(email=email,**extra_fields) user.set_password(password) user.save() return user def create_superuser(self,email,password,**extra_fields): extra_fields=setdefault('is_staff',True) extra_fields=setdefault('is_active',True) extra_fields=setdefault('is_superuser',True) if extra_fields.get('is_superuser') is not True: raise ValueError(lagy("must be is superuser")) if extra_fields.get('is_staff') is not True: raise ValueError(lagy('Must is_staff category')) return create_user(email,password,**extra_fields) 2.myapp/models.py from django.db import models from django.contrib.auth.models import AbstractUser, PermissionsMixin from django.utils.translation import ugettext_lazy as lagy from django.utils import timezone from .mangers import UserManager class UserModel(AbstractUser): username = None email = models.EmailField(lagy('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email Then Error is like: ModuleNotFoundError: No module named 'myapp.mangers' -
keyerror while migrating in python
i am trying to run but it is not working python manage.py migrate its showing error Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, signup Running migrations: Applying signup.0002_auto_20210511_2201...Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\migration.py", line 116, in apply operation.state_forwards(self.app_label, project_state) File "C:\Users\VAISHNAVI SHUKLA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\operations\fields.py", line 92, in state_forwards state.models[app_label, self.model_name_lower].fields[self.name] = field KeyError: ('signup', 'students') what does keyerror mean. I have been trying to solve it. I tried deleting migrated files but after running makemigrations again it made no difference and said No changes detected