Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery can't send tasks to queue when running in docker
I tested it on windows and it worked, but now I want to do it using docker. The problem is when I try to execute task to send email to user I get error: [Errno 111] Connection refused, but celery starts successfully and connects to rabbitmq. Why can't celery send tasks to rabbitmq? Traceback (most recent call last): File "/usr/local/lib/python3.11/dist-packages/kombu/utils/functional.py", line 32, in __call__ return self.__value__ ^^^^^^^^^^^^^^ During handling of the above exception ('ChannelPromise' object has no attribute '__value__'), another exception occurred: File "/usr/local/lib/python3.11/dist-packages/kombu/connection.py", line 472, in _reraise_as_library_errors yield ^^^^^ File "/usr/local/lib/python3.11/dist-packages/kombu/connection.py", line 459, in _ensure_connection return retry_over_time( File "/usr/local/lib/python3.11/dist-packages/kombu/utils/functional.py", line 318, in retry_over_time return fun(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/kombu/connection.py", line 941, in _connection_factory self._connection = self._establish_connection() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/kombu/connection.py", line 867, in _establish_connection conn = self.transport.establish_connection() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/kombu/transport/pyamqp.py", line 203, in establish_connection conn.connect() ^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/amqp/connection.py", line 323, in connect self.transport.connect() ^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/amqp/transport.py", line 129, in connect self._connect(self.host, self.port, self.connect_timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/amqp/transport.py", line 184, in _connect self.sock.connect(sa) ^^^^^^^^^^^^^^^^^^^^^ The above exception ([Errno 111] Connection refused) was the direct cause of the following exception: File "/usr/local/lib/python3.11/dist-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File … -
Printing from Django
I've been doing some googling and I am not turning up the answer I am searching for. Essentially I have a Django web app. One of the models is a Blueprint which contains a link to a PDF stored someplace. I want to be able to write an admin action so that if the user selects one or more of these models I can print the PDFs attached one after another to a physical printer. 90% of the stuff I'm finding is about how to create PDFs. I don't want to create them, they already exist. Essentially all I need to do is allow the user to select a printer to send the pdfs to in a sequential order. I'm a little confused on what needs to be done , but I might just be overthinking it. From inside the admin action I have access to all the selected Objects. But the actual PDF files would be in memory not sitting in disk someplace. They do exist in storage. However, this is running inside a browser so I suppose all I need to do is trigger the browser's inborn print capability and pass it some sort of reference to the … -
Error: Incorrect padding when decoding encrypted payload data in Django registration view function
I want to encode my payload data for a form so that on submission the view function for my registration decodes the data and performs necessary validation on the data and saves it to the database. However, I keep getting the error below. Error at /register/ Incorrect padding Here is the complete Traceback Environment: Request Method: POST Request URL: http://localhost:8003/register/ Django Version: 4.2 Python Version: 3.9.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'authentication', 'rest_framework', 'rest_framework_simplejwt.token_blacklist', 'corsheaders'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/dubsy/virtualenvs/djangoproject/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/dubsy/virtualenvs/djangoproject/digirepo2/authentication/views.py", line 86, in post cipher = AES.new(base64.b64decode(encryption_secret_key), AES.MODE_ECB) File "/home/dubsy/anaconda3/lib/python3.9/base64.py", line 87, in b64decode return binascii.a2b_base64(s) Exception Type: Error at /register/ Exception Value: Incorrect padding Below are the code snippet that … -
How to call python function from javascript in django?
I'm making a Cubing Timer app. I have a django app which loads python function that generates a scramble from file in views.py. I have a JS file that runs timer by clicking Space bar. I want to generate new scramble everytime timer stops. How to do that? Here is my views.py file: from .scramble_generator import * def home(request): s = scramble_replace(scramble_gen()) scramble = sprint(valid(s)) return render(request, 'timer/index.html', {'scramble':scramble}) main.js: let state = 'stopped'; const transitions = { waiting: state => ResetTimer(), started: state => StartTimer(), stopped: state => PauseTimer(), }; document.addEventListener('keydown', changeState); document.addEventListener('keyup', changeState); function changeState({code, repeat, type: action}){ if(code !== 'Space' || repeat){ return; } // this allows to have more event types and states in the future without cluttering const actions = { keydown: () => state === 'stopped' ? 'waiting' : 'stopped', keyup: () => state === 'stopped' ? state : 'started', }; // determine the next state const next = actions[action](); // if the next state is different, commit it to the current and execute transition next === state || transitions[state = next](state); } -
How can I automatically attach a comment to a post?
I have a form for creating comments that already knows how to determine which user the message is from, but it does not know how to join the post to which it is written. Here are models.py: class Post(models.Model): title = models.CharField(max_length=150) text = models.CharField(max_length=8000) data = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='media/', null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) connect_category = models.ManyToManyField('Category') def __str__(self): return self.title def save(self): super().save() if self.image: img = Image.open(self.image.path) if img.height > 300 or img.width > 300: new_img = (500, 600) img.thumbnail(new_img) img.save(self.image.path) def get_absolute_url(self): return reverse('post', args=[str(self.id)]) class Category(models.Model): title = models.CharField(max_length=30) class Comments(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.CharField(max_length=800) approved = 'Approved' refused = 'Refused' choice = ( (approved, 'Одобрено'), (refused, 'Отказано') ) status = models.CharField(max_length=8, choices=choice, default='Ожидание') connect_post = models.ForeignKey('Post', on_delete=models.CASCADE, null=True) def get_absolute_url(self): return reverse('post', args=[str(self.id)]) views.py: class PostDetail(DetailView): model = Post template_name = 'post.html' context_object_name = 'post' form_class = CommentForm success_url = '' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comment_form'] = CommentForm(initial={'connect_post': self.object.id}) return context class CommentCreateView(CreateView): form_class = CommentForm success_url = '/' model = Comments def form_valid(self, form): form.instance.author = self.request.user post_id = form.cleaned_data['connect_post'] form.instance.connect_post = post_id return super().form_valid(form) forms.py: class CommentForm(forms.ModelForm): connect_post = forms.IntegerField(widget=forms.HiddenInput) class Meta: model = Comments … -
Using a database modeler with Django
I am trying to use Navicat as a visual way of designing the database Schema for a Django application. I saw the inspectdb command for Django, but it seems for migrating an old database to a new one, not continuous changes as the application is developed. What would the best way to integrate the both Navicat and Django together? Thanks in advance! -
ModuleNotFoundError when attempting runserver in a new Django project
Description: I'm encountering a ModuleNotFoundError while trying to run a developer server in a new Django project with a fresh virtual environment. The error refers to a project named "Carshering" and boostrap import that has no connection to the current project which is just created empty template. I'd like to understand the reason behind this error and how to resolve it. The error message includes <frozen importlib._bootstrap>, which prompted me to install two Bootstrap-related modules. (venv) C:\Users\karpi\PycharmProjects\WEB_QUIZ>python manage.py runserver Traceback (most recent call last): File "C:\Users\karpi\PycharmProjects\WEB_QUIZ\venv\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) ... ModuleNotFoundError: No module named 'Carshering' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\karpi\PycharmProjects\WEB_QUIZ\manage.py", line 22, in <module> main() ... ModuleNotFoundError: No module named 'Carshering' Expected Outcome: I expect the server to run successfully without any ModuleNotFoundError related to the "Carshering" project. Attempts so far: Created a new Django project in a fresh virtual environment. Installed Bootstrap using pip. Checked the installed packages and verified that the virtual environment is activated. Tried running the migration using the command python manage.py makemigrations, but encountered the ModuleNotFoundError. set PYTHONPATH Additional Information: Django version: 4.2.3 Python version: 3.11 django-bootstrap-form 3.4* crispy-bootstrap5 0.7* *These … -
Poetry can't find dependencies on installation
I'm trying to run a Django project. The project has the files poetry.lock and pyproject.toml and it runs on other computers, but I can't install it on my computer (macOS Monterey). On my computer with the newly created virtual environment (venv), when I run the poetry install command, I receive the message: "No dependencies to install or update." When I run the poetry show command, several libraries are listed. But when I run the project, Python doesn't find any libraries. (I can run older Python projects on my computer) -
Order a Django Queryset by how many times it appears in a Foreign Key
In my Django App i have a model called Room, class Room(models.Model): host = models.ForeignKey(User, on_delete=models.CASCADE, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null = True, blank = True) participants = models.ManyToManyField(User, related_name='participants', blank = True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name In my app, i want to show all the Topics ordered by counting how many rooms have that topic. class Topic(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name How can i order them? In my html file i can get this value by using <span>{{topic.room_set.all.count}}</span> that way i get the number of rooms that have this topic, which is useful, but don't work when using the order_by method. -
Reverse for url with arguments not found in Django
Error: Reverse for 'task_list_by_tag' with arguments '('оаип_1',)' not found. 1 pattern(s) tried: ['tag/(?P<tag_slug>[-a-zA-Z0-9_]+)/\Z'] views.py def index(request, tag_slug=None): task_list = Task.objects.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) task_list = task_list.filter(tags__in=[tag]) paginator = Paginator(task_list, 2) page_number = request.GET.get('page', 1) try: tasks = paginator.page(page_number) context = {"tasks":tasks, 'tag':tag} return render(request, 'main/index.html', context) urls.py app_name = 'main' ... path('tag/<slug:tag_slug>/', views.index, name = "task_list_by_tag"), index.html {% for tag in task.tags.all %} <a href="{% url "main:task_list_by_tag" tag.slug %}"> {{ tag.name }} </a> {% if not forloop.last %}, {% endif %} {% endfor %} I tried to fix that problem: 1) <a href="{% url "main:task_list_by_tag" tag_slug=tag.slug %}"> return the error: Reverse for 'task_list_by_tag' with keyword arguments '{'tag_slug': 'оаип_1'}' not found. 1 pattern(s) tried: ['tag/(?P<tag_slug>[-a-zA-Z0-9_]+)/\Z'] 2) `<a href="{% url "main:task_list_by_tag" slug=tag.slug %}">` Reverse for 'task_list_by_tag' with keyword arguments '{'slug': 'оаип_1'}' not found. 1 pattern(s) tried: ['tag/(?P<tag_slug>[-a-zA-Z0-9_]+)/\Z'] -
Issue With Anchor Tags Not Scrolling Far Enough in Django
I have a Django model called "prompt" that has particular properties, and I have linked these prompts to certain paragraphs (paragraph is another model) in the database depending on whether I want to display that prompt with that paragraph. Before I had starting displaying the prompts on the webpage alongside the paragraphs, my anchor tags inside the "sidebar" area worked properly and scrolled to the correct section of the page, but after I added in the prompts from the Django database, the anchor tag "jumping" functionality stopped working properly. Here is my code: {% extends 'prompt/base.html' %} {%block title%} Guidebook for Prompting {%endblock%} {%block content%} Guidebook on Prompting for Language Learning {%endblock%} {%block sidebar%} <div class="ml-3 mb-16 grid grid-cols-4 gap-4"> <div class="pb-6"> <div class="col-span-1"> <ul> {% for section in sections %} <li id="section{{section.id}}" class="py-2 px-2 rounded-xl"> <a href="{%url 'section:detail' section.id %}" class="section-link">{{section.section_title}}</a> <ul> {% for paragraph in section.paragraph_set.all %} <!-- here is the section where the links are--> <li id="paragraph{{paragraph.id}}" class="ml-3"> <a href="{%url 'section:detail' section.id %}#paragraph{{paragraph.id}}">{{paragraph.paragraph_title}}</a> </li> {%endfor%} </ul> </li> {%endfor%} </ul> </div> </div> <div class="space-y-10 mr-24 text-5xl col-span-3" id="section-text-container"> {{section.section_title}} <div class="mt-10 text-lg"> {{section.section_description}} </div> {%for paragraph in section.paragraph_set.all%} <!-- jump here --> <div id="paragraph{{paragraph.id}}" class="mt-10 text-3xl">{{paragraph.paragraph_title}}</div> <div class="text-lg">{{paragraph.paragraph_text … -
Content security policy blocking CKEditor write function in from bundled script in Django website application
In my Django website application, I am using CKEditor 5.1.1 and a bundled script is being blocked by my script-src directive in my content security policy. The offending file is bundle-5f73f48756.cms.ckeditor.min.js. Specifically, the write(a) function from the block of code below is being flagged in the console: write: function(a) { this.$.open("text/html", "replace"); CKEDITOR.env.ie && (a = a.replace(/(?:^\s*<!DOCTYPE[^>]*?>)|^/i, '$\x26\n\x3cscript data-cke-temp\x3d"1"\x3e(' + CKEDITOR.tools.fixDomain + ")();\x3c/script\x3e")); this.$.write(a); this.$.close() }, I have tried writing middleware (with the help of ChatGPT) to address the issue. I have successfully done this with other popup or inline scripts but in this case, the middleware does not work. The goal there was to inject my nonce into the script tag from the replace() function but nonetheless, the error persists. ChatGPT also suggested editing the configuration for CKEditor. However, since it is a "site-package" I am not sure where in my Django project I can actually update or override the configuration. For context, the path to my base.py (settings) file is marketing/marketing/settings/base.py -
Pycharm debugging does not stop at breakpoints when starting Django server on docker-compose
I have a Django project that I can perfectly debug when ran on my machine through the CLI, however when I moved the logic into Docker & docker-compose, even though it runs without any issu I can no longer debug it, i.e. it does not stop at breakpoints, even though I can see through the debugger console that Pydevd receives commands related to addition / deletion of breakpoints: /usr/local/bin/python3 /opt/.pycharm_helpers/pydev/pydevd.py --multiprocess --client host.docker.internal --port 55583 --file /opt/project/manage.py runserver 0.0.0.0:8000 Container project-api-db-1 Running Container project-api-project-api-1 Recreate Container project-api-project-api-1 Recreated Attaching to project-api-project-api-1 project-api-project-api-1 | Executing PyCharm's `sitecustomize` project-api-project-api-1 | User doesn't have a custom `sitecustomize` project-api-project-api-1 | Custom matplotlib backend was set for SciView project-api-project-api-1 | Debugger warning: It seems that frozen modules are being used, which may project-api-project-api-1 | make the debugger miss breakpoints. Please pass -Xfrozen_modules=off project-api-project-api-1 | to python to disable frozen modules. project-api-project-api-1 | Note: Debugging will proceed. project-api-project-api-1 | Unable to load jupyter_debug plugin project-api-project-api-1 | Executing file /opt/project/manage.py project-api-project-api-1 | arguments: ['/opt/project/manage.py', 'runserver', '0.0.0.0:8000'] project-api-project-api-1 | PYDEVD_FILTER_LIBRARIES False project-api-project-api-1 | project-api-project-api-1 | ('Connecting to ', 'host.docker.internal', ':', '55583') project-api-project-api-1 | ('Connected.',) project-api-project-api-1 | debugger: received >>501 1 0.1 UNIX project-api-project-api-1 | << project-api-project-api-1 | Received … -
I could create the root index.html page but could not create another page in Django
I have made a simple Django design in which I displayed a database for Medical blood test items. I successfully made the typical three files (views, the app URLS, and the basic URLS) as follows: Views.py from .models import Test from django.shortcuts import render def index(request): tests = Test.objects.all() return render(request, 'btestinfo/index.html', {'tests': tests}) def contact(request): return render(request, 'btestinfo/contact.html') App URLS from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), # path('<int:test_id>', views.detail, name='tests_detail'), path('contact/', views.contact, name='contact') ] Basic URLS from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("btestinfo/", include("btestinfo.urls")), path("contact/", include("contact.urls")) ] I exhausted all my tricks to create a link like http://127.0.0.1:8000/contact in order to display the contact.html page, am always ending up with the error: ModuleNotFoundError: No module named 'contact' I was only able to display the the db items from the link http://127.0.0.1:8000/btestinfo. I will be so grateful if you get to my rescue -
How to set cachecontrol for different types of image differently without overriding get_object_parameters using django-storages
I have multiple apps and each app has different cachecontrol requirement. get_object_parameters provides us. But it will be big change for codebase. Instead is it possible to pass cachecontrol to constructor e.g S3Boto3Storage(**options = { 'bucket_name': 'abc', 'querystring_expire': 172800, 'cachecontro': 'max-age=12000', 'location': 'LINTING', }) Right now its not working need to add this functionality in package. -
Value error at /register/ Fernet key must be 32 url-safe base64-encoded bytes
I am trying to encode the payload data of a form I created using react from frontend using the code below const handleSubmit = (e) => { e.preventDefault(); const encryptedPassword = CryptoJS.AES.encrypt( formData.password, "b'VFRkU0hHSEZORFN2dWx1b3VNT213SVE4OTJkLWFiYU1CQU5TdjVGWjhiST0'" ).toString(); const encryptedPassword2 = CryptoJS.AES.encrypt( formData.password2, "b'VFRkU0hHSEZORFN2dWx1b3VNT213SVE4OTJkLWFiYU1CQU5TdjVGWjhiST0'" ).toString(); const encryptedEmail = CryptoJS.AES.encrypt( formData.email, "b'VFRkU0hHSEZORFN2dWx1b3VNT213SVE4OTJkLWFiYU1CQU5TdjVGWjhiST0'" ).toString(); const encryptedPayload = { ...formData, password: encryptedPassword, password2: encryptedPassword2, email: encryptedEmail, }; // Send the encrypted payload to the backend axios .post("http://127.0.0.1:8003/register/", encryptedPayload) .then((response) => { // Handle successful response console.log(response.data); }) .catch((error) => { // Handle error console.error(error); }); }; So whenever I submit the form, the view function below is what I used to decrypt the payload and save it to the database. class CreateUser(APIView): permission_classes = [AllowAny] def post(self, request): encrypted_password = request.data.get("password") encrypted_password2 = request.data.get("password2") encrypted_email = request.data.get("email") encryption_secret_key = "b'VFRkU0hHSEZORFN2dWx1b3VNT213SVE4OTJkLWFiYU1CQU5TdjVGWjhiST0'" cipher_suite = Fernet(encryption_secret_key) decrypted_password = cipher_suite.decrypt( encrypted_password.encode()).decode() decrypted_password2 = cipher_suite.decrypt( encrypted_password2.encode()).decode() decrypted_email = cipher_suite.decrypt( encrypted_email.encode()).decode() # Update the request data with the decrypted password request.data["password"] = decrypted_password request.data["pasword2"] = decrypted_password2 request.data["email"] = decrypted_email serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() user.email = user.email.lower() user.username = user.email.lower() if user.email else None user.first_name = user.first_name.lower() if user.first_name else None user.last_name = user.last_name.lower() if user.last_name else None user.avatar … -
Images fetched with axios not found in react/django
Am having problems using axios to fetch data containing images and strings from django backend. It just shows this error in my browser console: gig2_sWgfG4m.png:1 GET http://localhost:5173/media/gig2_sWgfG4m.png 404 (Not Found) I have tried different configurations but still didn't get a positive response. Here is my code: CARD.JSX import axios from "axios" import { useEffect, useState } from "react" const baseURL = 'http://127.0.0.1:8000/BlogHost' export const Card = () => { const [posts, setPosts] = useState([]) useEffect(() => { axios.get(baseURL) .then((response) => { setPosts(response.data); }) .catch(error => { console.error('An error occured while fetching data from backend', error) }) }, []) if (!posts) return null; return ( <div className="bg-gray-400"> <div className="mx-auto min-w-fit px-4 sm:px-6 lg:px-8"> <div className="mx-auto max-w-2xl py-16 sm:py-24 lg:max-w-none lg:py-32"> <div className="mt-6 space-y-12 gap-y-6 gap-x-3 grid grid-cols-1 md:grid md:grid-cols-2 md:space-y-0 lg:grid lg:grid-cols-4 lg:space-y-0"> {posts.map((post) => ( <div key={post.title} className="group relative"> <div className="relative h-80 w-full overflow-hidden rounded-lg bg-white sm:aspect-h-1 sm:aspect-w-2 lg:aspect-h-1 lg:aspect-w-1 group-hover:opacity-75 sm:h-64"> <img src={post.image} alt={post.title} className="h-full w-full object-cover object-center" /> </div> <h3 className="mt-6 text-sm md:text-base lg:text-lg text-gray-800"> <a href='{post.href}'> <span className="absolute inset-0" /> {post.category} </a> </h3> <p className="text-base md:text-xl lg:text-2xl font-semibold text-gray-900">{post.body}</p> </div> ))} </div> </div> </div> </div> ) } BACKEND VIEWS.PY from .models import Blog from .serializer import BlogSerializer … -
How do I integrate xAPI or cmi5 in my Django application?
I have all the user's activity data like course completion data, course topic completion data, time spent on each topic and course, assessment data in MySQL database. But, I couldn't find the documentation/tutorial on integrating cmi5 (with/without xAPI) into Learning Management System platform built using Django web-framework. So, far I have learned a little about the cmi5 from the below links, https://risc-inc.com/cmi5-overview-process-flow/ https://xapi.com/cmi5/cmi5-technical-101/ -
Download CSV using AJAX in Django - saved file contains the view content instead of the csv content
I'm dynamically generating a CSV from some content, and want to provide a message to the user and then download the file. When using Javascript, the file that's downloaded is the HTML of the view, and not the CSV. If I remove the javascript, the CSV is downloaded, but then there is no indication of this to the user. How can I get the CSV when using javascript? One thing I note is that I see a GET after the POST in my Django application log when using the javascript script. I am following https://docs.djangoproject.com/en/4.2/howto/outputting-csv/ to generate the csv content, and got the javascript from the answer in Django cannot download docx file in ajax This view content works when used without the javascript components - a csv file is downloaded. def csv_report(request): if request.method == "POST": report_dates_form = AllMemberseventForm(request.POST) if report_dates_form.is_valid(): start_date = report_dates_form.cleaned_data.get("start_date") end_date = report_dates_form.cleaned_data.get("end_date") events = Events.objects.filter(event_date__range=[start_date, end_date]).order_by("event_date") if events and len(events) > 0: response = HttpResponse( content_type="text/csv", headers={ "Content-Disposition": 'attachment; filename="%s"' % filename, "filename": filename, "event_count": len(events), }, ) writer = csv.writer(response) for event in events: writer.writerow( [event.thing, event.otherthing, event.event_date] ) return response My javascript in the template that the view uses is as follows. … -
Django + Mongo + djongo. Trouble with adding new models with ForeignKey
i use django + mongo with djongo. I have 2 models: Deck and Card; class Deck(models.Model): deckName = models.TextField(max_length=100) deckDetail = models.TextField(max_length=1400) class Card(models.Model): cardName = models.TextField(max_length=100) cardDetail = models.TextField(max_length=1400) deckCard = models.ForeignKey(Deck, on_delete=models.CASCADE) dailyCard = models.BooleanField(default=False, unique=True) when i add new Deck model with http://127.0.0.1:8000/admin/app/deck/add/ (django admin standart) it's ok. But when i add new Card model i have "Exception Type: DatabaseError at /admin/app/card/add/ Exception Value: " ; in py manage.py shell i create 2 new models (card, deck) and it's ok! I think the point is that when saving the Card, the string (id) is passed to the deck field, but do you need int? Or something like that? Do I really have to make my own admin page and override the methods for saving models there? -
Django Model Queryset Calculation
For example class Rice(models.Model): quantity = models.DecimalField(...) Lets say: rices = Rice.objects.all() for i in rices: i.quantity This gives output as : 5 7 9 10 Now what i want to achieve is a total_quantity till that object is reached what my desired output should be : 5 12 21 31 Logic: First object total_quantity till that object is calculated is 0+5 then, next object total_quantity is 0+5+7 then 0+5+7+9 and so on. And this should be done using (queryset) annotate/aggregate or any other db models functions. (If not possible then any other way) If the order changes the the output should also change. -
How does has_module_permission work with inline models in django admin
While there are other ModelAdmin methods that can be used to hide inlines, it's noted here that the InlineModelAdmin also shares the has_module_permission feature with ModelAdmin. It works perfectly on ModelAdmin objects as described in the docs but I don't seem to understand how it works or is supposed to work for InlineModelAdmin objects. class HideModuleAdmin(admin.ModelAdmin): def has_module_permission(self, request): if condition: # This works as expected. Hides it from the menu items return False return super().has_module_permission(request class HideTabularInlineModelAdmin(admin.TabularInline): def has_module_permission(self, request): if condition: # This does not work as expected. The inline is visible places I don't expect to see it return False return super().has_module_permission(request I am simply inheriting the above where I need them e.g class SomeModelAdmin(HideModuleAdmin): pass class SomeTabularInline(HideTabularInlineModelAdmin): pass -
Using Cookiecutter Django Docker backup functions on a Windows machine
I have used Cookiecutter Django to create a dockerized project, which I have deployed to production. I can use the commands for backing up, checking backups, and restoring all fine on my production server, which is a linux machine. I was hoping to move the backup from my production environment to my development environment, which is a windows machine, however using the commands throws an issue "/usr/bin/env: ‘bash\r’: No such file or directory". I've searched around and seen this is a windows files encoding issue but can't find an answer which works for me for resolving that issue. Has anyone faced this issue before and found a workaround? Thanks for any help anyone can offer! -
Multiple Group by boolean fields with date interval
I have a table like this: User Record Date Online Alice 2023/05/01 Online Alice 2023/05/03 Online Alice 2023/05/15 Online Alice 2023/05/31 Offline Alice 2023/06/01 Offline Alice 2023/06/04 Offline Alice 2023/06/20 Online Alice 2023/06/21 Online And I would like to have a result like this: Alice was online from 2023/05/01 to 2023/05/15 Alice was offline from 2023/05/31 to 2023/06/04 Alice was online 2023/06/20 to 2023/06/21 I tried to use this query: _users = (MyUserModel.objects.filter(record_date__year=2023) .values('online', 'record_date') .annotate(min_date=Min('record_date'), max_date=Max('record_date')) .order_by() ) but it doesn't return a correct result -
How to solucionate the error to Upgrade project to Django 4.2.3
I have a Django project in the 3.1.2 version. However, I need upgrade it to a new version, to 4.2.3. I´m having the following message when I upgrade the project. How to solucionate this? "django.core.exceptions.ImproperlyConfigured: Cannot import 'core'. Check that 'apps.core.apps.CoreConfig.name' is correct. " In the 3.1.2 version, this works well. Follow the structure of the folders of the project: |.quality |.. apps |... core |... changelog |.. quality |... init.py |... asgi.py |... settings.py |... urls.py |... wsgi.py |.. static |.. templates |.. venv Follow the Installed_apps in the settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrapform', 'apps.core', 'apps.changelog', ] Thank you very much!