Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
manage.py migrate on Amazon Linux 2023
I am trying to deploy my django environment on aws linux 2023 and I have a file with command for migration: container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate" leader_only: true Then I get an error in cfn-init.log 2023-11-06 19:01:44,570 [ERROR] Command 01_migrate (source /var/app/venv/*/bin/activate && python3 manage.py migrate) failed 2023-11-06 19:01:44,570 [ERROR] Error encountered during build of postbuild_0_hq_app: Command 01_migrate failed Traceback (most recent call last): File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 579, in run_config CloudFormationCarpenter(config, self._auth_config, self.strict_mode).build(worklog) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 277, in build changes['commands'] = CommandTool().apply( File "/usr/lib/python3.9/site-packages/cfnbootstrap/command_tool.py", line 127, in apply raise ToolError(u"Command %s failed" % name) cfnbootstrap.construction_errors.ToolError: Command 01_migrate failed 2023-11-06 19:01:44,571 [ERROR] -----------------------BUILD FAILED!------------------------ 2023-11-06 19:01:44,571 [ERROR] Unhandled exception during build: Command 01_migrate failed Traceback (most recent call last): File "/opt/aws/bin/cfn-init", line 181, in <module> worklog.build(metadata, configSets, strict_mode) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 137, in build Contractor(metadata, strict_mode).build(configSets, self) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 567, in build self.run_config(config, worklog) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 579, in run_config CloudFormationCarpenter(config, self._auth_config, self.strict_mode).build(worklog) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 277, in build changes['commands'] = CommandTool().apply( File "/usr/lib/python3.9/site-packages/cfnbootstrap/command_tool.py", line 127, in apply raise ToolError(u"Command %s failed" % name) cfnbootstrap.construction_errors.ToolError: Command 01_migrate failed Is command changed from linux2 to linux 2023? Thank you for your help -
getting error while trying to open websocket connection
This is the error I am getting while trying to start the websocket. I am not able Traceback (most recent call last): File "/usr/local/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) File "/usr/local/lib/python3.10/dist-packages/daphne/cli.py", line 171, in entrypoint cls().run(sys.argv[1:]) File "/usr/local/lib/python3.10/dist-packages/daphne/cli.py", line 233, in run application = import_by_path(args.application) File "/usr/local/lib/python3.10/dist-packages/daphne/utils.py", line 12, in import_by_path target = importlib.import_module(module_path) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/yana/Desktop/learn/code-executor/server/./codeexec/asgi.py", line 7, in <module> from collaborate.routing import websocket_urlpatterns File "/home/yana/Desktop/learn/code-executor/server/./collaborate/routing.py", line 2, in <module> from collaborate import consumers File "/home/yana/Desktop/learn/code-executor/server/./collaborate/consumers.py", line 2, in <module> from collaborate.models import CollaborateRoom File "/home/yana/Desktop/learn/code-executor/server/./collaborate/models.py", line 2, in <module> from authentication.models import CustomUser File "/home/yana/Desktop/learn/code-executor/server/./authentication/models.py", line 2, in <module> from .manager import UserManager File "/home/yana/Desktop/learn/code-executor/server/./authentication/manager.py", line 1, in <module> from django.contrib.auth.base_user import BaseUserManager File "/usr/local/lib/python3.10/dist-packages/django/contrib/auth/base_user.py", line 57, in <module> class AbstractBaseUser(models.Model): File "/usr/local/lib/python3.10/dist-packages/django/db/models/base.py", line 129, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python3.10/dist-packages/django/apps/registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python3.10/dist-packages/django/apps/registry.py", line 138, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded … -
Please am trying to pip install mysqlclient in windows and am always getting this error even in cmd
enter image description here This is the error that always pops up Actually am trying to configure mysql database with django on Windows and this step is required but anytime i try to pip install the mysqlclient this error keeps on showing up,please can somone show me how to solve this issue -
Error Assigning Foreign Key in Django CreateView, can't get an instance
Issue: Cannot Assign "38" to "Pusinex2.seccion" - Must Be a "Seccion" Instance Models: The models Seccion and Pusinex2 are related in a ForeignKey manner. Seccion holds the primary key field and other details related to a section. Pusinex2 has a foreign key relationship with Seccion along with fields for date, file, and user traceability. Views: A PUSINEXForm is defined in the forms.py, linking various form fields to the respective model fields. The CreatePUSINEX view handles the form submission, using PUSINEXForm and Pusinex2. Error: The error is encountered during form submission: ValueError at /creation/. Specifically: "Cannot assign '38' to 'Pusinex2.seccion' - Must Be a 'Seccion' instance." The issue arises in the CreatePUSINEX view's form_valid method. Here's my models: class Seccion(models.Model): distrito = models.ForeignKey(Distrito, on_delete=models.CASCADE) municipio = models.ForeignKey(Municipio, on_delete=models.CASCADE) seccion = models.PositiveSmallIntegerField(primary_key=True) tipo = models.PositiveSmallIntegerField(choices=CAT_TIPO) activa = models.BooleanField(default=True) class Pusinex2(models.Model): seccion = models.ForeignKey(Seccion, on_delete=models.CASCADE) f_act = models.DateField() hojas = models.PositiveSmallIntegerField() observaciones = models.TextField(blank=True, null=True) archivo = models.FileField(upload_to=pusinex_file, blank=True, null=True) # Trazabilidad user = models.ForeignKey(User, editable=False, on_delete=models.CASCADE) a FormView: class PUSINEXForm(forms.ModelForm): seccion = forms.IntegerField() f_act = forms.DateField() hojas = forms.IntegerField() archivo = forms.FileField() observaciones = forms.CharField(widget=forms.Textarea, required=False) And a related CreateView: class CreatePUSINEX(LoginRequiredMixin, CreateView): template_name = 'control/pusinex_form.html' form_class = PUSINEXForm model = Pusinex2 … -
Swagger not working correctly through Nginx
We are developing web application in our class, and one of the tasks is to configure swagger for documentation. I did it, and it works perfectly. However, next we had to configure nginx and now when sending request with swagger through nginx it isn't requesting correct url (it requests http://127.0.0.1/api/v1/albums/ instead of http://127.0.0.1:82/api/v1/albums/) This is my config for swagger location /api/v1/swagger/ { proxy_pass http://127.0.0.1:8000/swagger/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } (I am developing web app with django, for swagger i'm using drf_yasg) I tried adding 'API_URL': 'http://127.0.0.1:82/api/v1/', in my SWAGGER SETTINGS in Django but it didn't fix anything -
How do I copy the values of a HTML table column to the clipboard using a Django template and JavaScript?
I need to copy the values of a HTML table column to the clipboard. I'm using Django templates. Here is my HTML table: <table> <tr> <th>Name</th> <th>DOB</th> <th>ID</th> <th>Guardian</th> <th>Email</th> <th>Telephone</th> <th>NIF</th> <th>Notes</th> </tr> {% for a in sessao.first %} <tr> <td>{{ a.nome }}</td> <td>{{ a.dtnasc }}</td> <td>{{ a.alunoid }}</td> <td>{{ a.educaid }}</td> <td id="a.id">{{ a.educaid.email }}</td> <td>{{ a.educaid.telefonea }}</td> <td>{{ a.nif }}</td> <td>{{ a.notas }}</td> <td><button class="btn btn-outline-success btn-sm" onclick="CopyText({{ a.id }})" data-toggle="tooltip" data-placement="top" title="Copy"> copy </button> </td> </tr> {% endfor %} </table> I'm trying this script but I get an error message: // Copy to ClipBoard function CopyText(el) { // Get the Selected Data By ID var copyText = document.getElementById(`${el}`) var str = copyText.innerHTML // Get All HTML Data and Copy to Clipboard function listener(e) { e.clipboardData.setData("text/plain", str); e.preventDefault(); } document.addEventListener("copy", listener); document.execCommand("copy"); document.removeEventListener("copy", listener); }; The error message is: Uncaught TypeError: Cannot read properties of null (reading 'innerHTML') at CopyText (lu.js:11:22) at HTMLButtonElement.onclick (2/:80:159) Any help would be much appreciated. Thanks in advance. -
My form in django is not saving data to db model
The data of form is not being saved to the db checkout table. In this code I want to give to field cart_information the value from another model that is related to user with session. The post request: [06/Nov/2023 18:44:49] "POST /order/checkout-info/ HTTP/1.1" 302 0 This is code: models.py: class Checkout(models.Model): cart_information = models.OneToOneField(Cart, on_delete=models.PROTECT) first_name = models.CharField(max_length=155) last_name = models.CharField(max_length=255) company_name = models.CharField(max_length=255, null=True) country = models.CharField(max_length=255) street_address_1 = models.TextField() street_address_2 = models.TextField(null=True) city = models.CharField(max_length=155) state = models.CharField(max_length=155) zip_code = models.CharField(max_length=155) phone = models.CharField(max_length=255) email = models.EmailField() order_notes = models.TextField(null=True, blank=True) STATUS_LIST = ( ('pending', 'Pending'), ('processing', 'Processing'), ('cancel', 'Cancel'), ('delivered', 'Delivered') ) status = models.CharField(max_length=255, choices=STATUS_LIST, default=STATUS_LIST[0][0]) html: <form method="post"> {% csrf_token %} <div class="client-info"> <div class="part1-of"> <label for="first_name">First Name:</label> <input type="text" id="first_name" name="first_name" required /> <label for="last_name">Last Name:</label> <input type="text" id="last_name" name="last_name" required /> <label for="company_name">Company Name:</label> <input type="text" id="company_name" name="company_name" /> <label for="country">Country:</label> <input type="text" id="country" name="country" required /> <label for="street_address_1">Street Address 1:</label> <textarea id="street_address_1" name="street_address_1" required></textarea> <label for="street_address_2">Street Address 2:</label> <textarea id="street_address_2" name="street_address_2"></textarea> </div> <div class="part2-of"> <label for="city">City:</label> <input type="text" id="city" name="city" required /> <label for="state">State:</label> <input type="text" id="state" name="state" required /> <label for="zip_code">Zip Code:</label> <input type="text" id="zip_code" name="zip_code" required /> <label for="phone">Phone:</label> <input … -
Cannot write to sqlite3 in docker container
I am starting to get my feet wet attempting to deploy a django/react app up on an EC2 instance. Everything is running fine on my personal Windows computer but when I pulled the code into the Ubuntu 22.04.3 container I got the following error: django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (attempt to write a readonly database) As I said this worked fine on my Windows laptop but is not working in Linux. Is this an issue with Linux or my Dockerfile? I plan to eventually use a postgres instance once I am feeling confident, but maybe I should just do it? Dockerfile: ARG PYTHON_VERSION=3.9-slim-bullseye FROM python:${PYTHON_VERSION} as python # Stage1: Create Wheels FROM python as python-build-stage ARG BUILD_ENVIRONMENT=local # required for make and setup for postgres (not used yet) RUN apt-get update && apt-get install --no-install-recommends -y \ build-essential \ libpq-dev COPY Backend/requirements . RUN pip wheel --wheel-dir /usr/src/app/wheels \ -r ${BUILD_ENVIRONMENT}.txt # Stage 2: Setup Django FROM python as python-run-stage ARG BUILD_ENVIRONMENT=local ARG APP_HOME=/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV BUILD_ENV ${BUILD_ENVIRONMENT} WORKDIR ${APP_HOME} RUN addgroup --system django \ && adduser --system --ingroup django django RUN apt-get update && apt-get install --no-install-recommends -y \ libpq-dev \ netcat … -
When i open my admin panel in django they show me the error
Please anyone tell me what I can do. whenever I save my project and open the admin-panel they show the error " raceback (most recent call last): File "C:\Program Files\Python311\Lib\site-packages\django\db\models\fields_init_.py", line 2053, in get_prep_value return int(value=0) ^^^^^^^^^^^^ TypeError: 'value' is an invalid keyword argument for int() The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Program Files\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\utils\decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\views\decorators\cache.py", line 62, in _wrapper_view_func response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\contrib\admin\sites.py", line 441, in login return LoginView.as_view(**defaults)(request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\utils\decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\views\decorators\debug.py", line 92, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\utils\decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\utils\decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\utils\decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\views\decorators\cache.py", line 62, in wrapper_view_func response = view_func(request, … -
Django Admin Panel Customization, Custom method for generating student fee vocuher in School Management System Admin panel
@admin.register(Student) class StudentAdmin(admin.ModelAdmin): actions = ['generate_fee_vouchers',] def generate_fee_vouchers(self, request, queryset): rule = VoucherGenerationRule.objects.latest('created') try: with transaction.atomic(): for student in queryset: if student.student_status not in ["LEFT", "FREEZE"]: if student.student_fee_structure: fee_structure = student.student_fee_structure # Generate the voucher number based on your logic voucher_no = student.roll_no + str(rule.issue_date.year)[-2:] + str( rule.issue_date.month).zfill(2) total_fee = ( fee_structure.total + student.arrears + rule.extra_charges + fee_structure.fine) - student.advance # Try to get an existing voucher for the student with the same voucher number total_fee_after_due_date = total_fee + rule.late_payment_fine student_fee_voucher = StudentFeeVoucher.objects.filter( voucher_number=voucher_no, student=student, fee_structure=fee_structure ).first() if student_fee_voucher: # # If the voucher already exists, update its attributes voucher_url = reverse('admin:student_management_studentfeevoucher_change', args=[student_fee_voucher.id]) student_fee_voucher.due_date = rule.due_date student_fee_voucher.issue_date = rule.issue_date student_fee_voucher.arrears = student.arrears student_fee_voucher.advance = student.advance student_fee_voucher.tuition_fee = fee_structure.tuition_fee student_fee_voucher.dev_fund = fee_structure.development_fund student_fee_voucher.misc_fee = fee_structure.misc student_fee_voucher.late_payment_fine = rule.late_payment_fine student_fee_voucher.extra_charges = rule.extra_charges student_fee_voucher.extra_charges_note = rule.extra_charges_note # Set the calculated total_fee student_fee_voucher.total_fee = int(total_fee) student_fee_voucher.total_fee_after_due_date = int(total_fee_after_due_date) student_fee_voucher.save() message = mark_safe( f"Updated fee voucher to <strong>Rs.{student_fee_voucher.total_fee:,}/-</strong> for <strong>{student.student_name}</strong> ({student.roll_no}, {student.student_section}) already exists <a href='{voucher_url}' target='_blank'>View Voucher</a> .") messages.warning(request, message) else: # If no voucher was found, create a new one student_fee_voucher = StudentFeeVoucher.objects.create( voucher_number=voucher_no, student=student, fee_structure=fee_structure, due_date=rule.due_date, issue_date=rule.issue_date, arrears=student.arrears, advance=student.advance, tuition_fee=fee_structure.tuition_fee, dev_fund=fee_structure.development_fund, misc_fee=fee_structure.misc, late_payment_fine=rule.late_payment_fine, extra_charges=rule.extra_charges, extra_charges_note=rule.extra_charges_note, total_fee=int(total_fee), total_fee_after_due_date=int(total_fee_after_due_date) ) student_fee_voucher.save() voucher_url = reverse('admin:student_management_studentfeevoucher_change', … -
Customizing Django Form based on model from 2 different models
I have the following 3 models in django. models.py ============= class Customer(models.Model): name = models.CharField(max_length=255, null=False, unique=True) class Service(models.Model): name = models.CharField(max_length=255, null=False) architecture = models.NameField() class customer_services(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, related_name='customer_service_entries') service = models.ForeignKey(Service, on_delete=models.SET_NULL, null=True, related_name='customer_service_entries') start = models.DateField() end = models.DateField() I have the following forms forms.py ============== class CustomerForm(ModelForm): class Meta: model = Customer fields = ["name"] class CustomerServiceForm(ModelForm): class Meta: model = customer_services fields = ["service", "start", "end"] class ServiceForm(ModelForm): class Meta: model = Service fields = ["name", "architecture"] I am trying to have a form that i can add services to customers, and the issue i am running into is that the form will display only the fields from the CustomerServiceForm. The problem i am running into is that in the services table, i can have multiple services with the same name, but different architectures, but i don't have a way of displaying that in the form. So lets say i have the following values in the Service table. services table ============== id || name || architecture 1 || Test || 32Bit 2 || Test || 64Bit 3 || AnotherTest || 32Bit 4 || AnotherTest || 64bit 5 || TestTwo || 32Bit … -
Javascript Function Not Working in Django
I have A Javascript Function in js file and called it in html file rendered by django. But that javascript function is not working. Javascript:- function delete_edit(){ div = document.getElementById('delete_confirm') div.showModal(); document.getElementById('"cancel_delete').addEventListener("click" , () => { div.close(); })}; Html Template:- <td><button id="delete-btn" onclick="delete_edit()"><strong>Delete</strong></button></td> <dialog id="delete_confirm"> <h1>Confirm to Delete</h1> <button id="cancel_delete">Cancel</button> <button id="confirm_delete"><a href="{% url 'delete_form' form_id=form.saral_id %}">Delete</a></button> </dialog> Js file is perfectly Linked to html template. I have also placed dailog outside of table but also not worked. -
Reassign all Guardian User Object Permissions from one Django User to another Django User
I have a Django system that users Guardian's User Object Permissions. I want to write a function that finds all permissions across all content types associated with an "old" user and assign them to a "new" user. I cannot query UserObjectPermission directly because our system uses direct foreign key tables for performance reasons. Here is an example of what I want from django.contrib.auth.models import User from guardian.shortcuts import get_objects_for_user, assign_perm def update_permissions_for_user(old_user, new_user): # Retrieve all USER permission objects for the old user # this throws exception because it requires a perms param that I do not want to provide. I want all objects across all models old_user_permissions = get_objects_for_user(old_user, use_groups=False, any_perm=False, with_superuser=False, accept_global_perms=False) # Iterate through each permission object and update it to point to the new user for permission in old_user_permissions: assign_perm(permission.codename, new_user, permission) remove_perm(permission.codename, old_user, permission) # Example usage: old_user = User.objects.get(username='old_username') # Replace 'old_username' with the actual username new_user = User.objects.get(username='new_username') # Replace 'new_username' with the actual username update_permissions_for_user(old_user, new_user) However, the problem with this is that get_objects_for_user requires a perms parameter which would require me to hardcode all the perms we wish to copy. Any time I introduce a new model we'd need to modify … -
How to Render HTML Templates in Django?
I have been trying to display html templates of Login and Register for an ecommerce website, using Django Framework and Python as server side scripting language. I want to make sure that If Users logs in using its email address and password then It should be redirected to its dashboard. New User has to first register then that user is allowed to login. I'm done with the backend coding of the templates, but now able to display UI first so that I can try to login from html template and the desired result should be display in default database of the Django. How I can do this? -
Error: must include rest_framework.authtoken in INSTALLED_APPS or set TOKEN_MODEL to None
I have a problem with the rest_framework_simplejwt package. I installed it and configured everything. and I am encountering an error. django.core.exceptions. ImproperlyConfigured: You must include rest_framework.authtoken in INSTALLED_APPS or set TOKEN_MODEL to None. this is my settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'dj_rest_auth.jwt_auth.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } REST_AUTH_TOKEN_MODEL = None REST_USE_JWT = True SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(hours=1), 'REFRESH_TOKEN_LIFETIME': timedelta(days=5), } -
How to Display the Size of a file in Django
I have a pdf file in my media directory that i want users to download, the issue is that, how can i make the users see the size of the file so they are aware of the size of what they want to download. Also, is it better to create a model for the pdf file as shown below in models.py? What is the best approach to handle this. I need help. models.py (this is not part of my code for now) class PersonalStatement(models.Model): personal_statement = models.FileField(upload_to='personal_statement/') title = models.CharField(max_length=50) views.py def personal_statement_download(request): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = 'Writing-a-Personal-Statement.pdf' filepath = BASE_DIR + '/media/personal_statement/' + filename path = open(filepath, 'rb') mime_type, _ = mimetypes.guess_type(filepath) response = HttpResponse(path, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response urls.py path('personal_statement/download/', views.personal_statement_download,name='personal_statement_download'), templates/index.html <a href="{% url 'personal_statement_download'%}" class="applyRightContentContainerSubDownloadLink"> Download File &#8681;</a> -
Run management commands on Django server in a Linux hosted App Service in Azure. Anything other than cronjobs?
Please Excuse me if this question has been posted before.I have a linux hosted App Service in Azure running a Django server. I want to run a management command periodically on the server. I am somewhat of an inexperienced person as far as cloud and architechure goes. So please be as elaborate as possible, mentioning the reasoning behind your recomendations, so that I can learn more. Tried using Cronjobs but it was not consistent and I did not have access to logs. Can't use Webjobs since the app service is on a linux machine and webjobs aren't supported on linux machines. Have read that funtions can be used. If so please point me in the right direction on how to setup and connect function to the App service and run command. -
ajax comment in django
I am trying to create a comment on a post in my Django application. I have a working form for the comment, but when I submit the form, I get an error message. The error message is: {"response": "forbidden"} I have checked my code and I am sure that the form is valid and that the request is being sent to the correct URL. I have also checked the permissions for the user who is trying to create the comment, and they are logged in and have the appropriate permissions. I am not sure what is causing the error. Can anyone help me? Code: class CommentForm(forms.ModelForm): author = forms.CharField(required=True, error_messages={'required': 'لطفاً نام خود را وارد کنید.'}) body = forms.CharField(required=True, error_messages={'required': 'لطفاً نظر خود را وارد کنید.'}) class Meta: model = Comment fields = ('author', 'body', 'post') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.cleaned_data = {} def clean_author(self): author = self.cleaned_data.get('author', 'نام کاربری ناشناس') return author def clean_body(self): body = self.cleaned_data.get('body') return body function comment(slug, id) { var comment = document.getElementById("comment").value; $.post(`/posts/post/${slug}/comment/create/${id}`, { comment: comment }).then(response => { if (response['response'] === 'created') { var count = document.getElementById("count"); count.innerText = Number(count.innerText) + 1; document.getElementById("comment").value = ""; } else { var errors = … -
User Profile not updating and no errors is given
I am having an issue while i want to update my user profile in my django project. It is not updating, not saving to the database and not showing any error in the terminal. Here is the form: from django import forms from .models import CustomUser, Profile class UserUpdateViewForm(forms.ModelForm): first_name = forms.CharField(max_length=30, required=False) last_name = forms.CharField(max_length=30, required=False) phone_number = forms.CharField(max_length=20, required=False) address = forms.CharField(max_length=100, required=False) class Meta: model = Profile fields = ['image', 'first_name', 'last_name', 'address', 'phone_number'] Here is the View: from django.forms.models import BaseModelForm from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import TemplateView, UpdateView from .models import CustomUser,Profile from .forms import UserUpdateViewForm class UserProfileView(LoginRequiredMixin, TemplateView): template_name = 'account/account.html' # Change this to the template name you want to use def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['user_profile'] = self.request.user # Assumes a one-to-one relationship between CustomUser and Profile return context class UserProfileUpdateView(LoginRequiredMixin, UpdateView): model = Profile form_class = UserUpdateViewForm template_name = 'account/update_profile.html' def get_object(self, queryset=None): # Get the user's profile to be updated return self.request.user.profile def form_valid(self, form): self.object = form.save() success_url = reverse_lazy('profile_page') return HttpResponseRedirect(success_url) Here is the template too {% extends 'base/base.html' %} {% load static %} … -
Why is my django-channels project not able to connect to Websockets in my Heroku deployed site?
I've been stuck at this for daaaays now and I realise that solution is probably simple but I no matter how much I read here and try I get the same error... When loading the chats part of my site I get this error in the dev tools console: WebSocket connection to 'wss://vareberg-games-a44cb52aa87b.herokuapp.com/wss/chat/' failed: (anonymous) @ chats/:131 and line 131 in the chats.html is inside the script tags and looks like this: const chatSocket = new WebSocket('wss://' + window.location.host + '/wss/chat/'); This is all the files I think are relevant to get help: The projects settings.py file: from pathlib import Path import os import dj_database_url if os.path.isfile('env.py'): import env # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['vareberg-games-a44cb52aa87b.herokuapp.com', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'daphne', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'profiles', 'events', 'channels', 'chats', ] SITE_ID = 1 LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL … -
Payment Intent value is null Stripe Django
I successfully created a checkout session, but when I checked the payment_intent value, it was coming out as null. Here's the code I used: @csrf_exempt def create_checkout_session(request,id): request_data = json.loads(request.body) order = Order.objects.filter(id = id).last() stripe.api_key = PaymentConfig.objects.all().last().stripe_secret_key checkout_session = stripe.checkout.Session.create( # Customer Email is optional, # It is not safe to accept email directly from the client side customer_email=request_data['email'], payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': str(order.amount_type.lower()), 'product_data': { 'name': order.plan.title, }, 'unit_amount': int(order.amount * 100), }, 'quantity': 1, } ], mode='payment', success_url=request.build_absolute_uri( reverse('paymentsuccess') ) + "?session_id={CHECKOUT_SESSION_ID}", cancel_url=request.build_absolute_uri(reverse('paymentfailed')), ) order.stripe_payment_intent = checkout_session['payment_intent'] print(payment_intent) -- **null value** order.save() return JsonResponse({'sessionId':checkout_session.id}) It's essential to get this value and save it in the order object so that I can access the order in the handler view after payment. Here's the handler view's code: class PaymentSuccessView(TemplateView): template_name = "v3/payment-successful.html" def get(self, request, *args, **kwargs): session_id = request.GET.get('session_id') if session_id is None: return HttpResponseNotFound() stripe.api_key = PaymentConfig.objects.all().last().stripe_secret_key session = stripe.checkout.Session.retrieve(session_id) order = get_object_or_404(Order, stripe_payment_intent=session.payment_intent) --**HERE** call=AfterPaymentBackend(request, order.id) ctx = { 'order':order, 'siteInfo':Company.objects.all().last() } return render(request, self.template_name, ctx) Is there something I'm overlooking? Thanks. I tried asking chat GPT for the help but AI isn't that much powerful. I tried searching on google but couldn't find … -
user need to submit the feedback and in my models I'm having user field which is associated with User instance, now don't want to expose my user filed
Users need to submit feedback, and in my models, there's a "user" field associated with a User instance. I want to ensure that this "user" field remains confidential, so it is not identifiable to other individuals when they access the database. Additionally, I need a mechanism to prevent users from submitting feedback more than once. Validation should be in place to ensure that feedback can only be submitted once. Here is what I tried models.py class Trainer_Feedback(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) satisfaction_rate = models.IntegerField() addressed_questions_or_not = models.CharField(max_length=10) were_training_materials_clear_ornot = models.CharField(max_length=10) were_training_engaging_interactive = models.CharField(max_length=10) opportunity_given_to_participate_or_not = models.CharField(max_length=10) training_content_meet_expectation_ornot = models.CharField(max_length=10) complex_concepts_clearly_explained_ornot = models.CharField(max_length=10) which_activity_method_you_found_beneficial = models.CharField(max_length=10) aspects_of_training_which_could_improved = models.TextField() Suggestions= models.TextField() views.py @csrf_exempt def trainer_feedback(request): try: if request.method == 'POST': data = json.loads(request.body) session_id = data.get('session_id') try: user = validate_session(session_id) except ObjectDoesNotExist: return JsonResponse({'message': 'Invalid session ID'}, status=401) existing_feedback = Trainer_Feedback.objects.filter(user=user).first() if existing_feedback: return JsonResponse({'message': 'Feedback already submitted by this user'}, status=400) feedback = data.get('feedback') satisfaction_rate = feedback.get('1') addressed_questions_or_not = feedback.get('2') were_training_materials_clear_ornot = feedback.get('3') were_training_engaging_interactive = feedback.get('4') opportunity_given_to_participate_or_not = feedback.get('5') training_content_meet_expectation_ornot = feedback.get('6') complex_concepts_clearly_explained_ornot = feedback.get('7') which_activity_method_you_found_beneficial = feedback.get('8') aspects_of_training_which_could_improved = feedback.get('9') Suggestions = feedback.get('10') feedback_data = Trainer_Feedback( user=user, satisfaction_rate=satisfaction_rate, addressed_questions_or_not=addressed_questions_or_not, were_training_materials_clear_ornot=were_training_materials_clear_ornot, were_training_engaging_interactive=were_training_engaging_interactive, opportunity_given_to_participate_or_not=opportunity_given_to_participate_or_not, training_content_meet_expectation_ornot=training_content_meet_expectation_ornot, complex_concepts_clearly_explained_ornot=complex_concepts_clearly_explained_ornot, which_activity_method_you_found_beneficial=which_activity_method_you_found_beneficial, aspects_of_training_which_could_improved=aspects_of_training_which_could_improved, Suggestions=Suggestions ) feedback_data.save() … -
Page not found in database
Page inside the database is not being accessed by the server using Django framework. Why am I getting this error? Tried all methods and error checks to find a solution to the problem, but I couldn’t find any solution to the problem. -
DRF generateschema - change example domain and customise
When I run generateschema command in DRF, it produces YAML file with example containing example.com responses: '200': content: application/json: schema: type: object properties: count: type: integer example: 123 next: type: string nullable: true format: uri example: http://api.example.org/accounts/?page=4 previous: type: string nullable: true format: uri example: http://api.example.org/accounts/?page=2 results: type: array items: $ref: '#/components/schemas/Book' description: '' How can I make it to mydomain.com ? How can I customise the schema in general? Ideally without introducing another library? Thanks -
I implemented auto save function in my Django 4 web app using js and django view function but it keep saving new model instances at every interval
I have implemented auto save feature in my Django 4 web app using javascript and Django views.py function as the end point.I got it to save the form / model instances to database, bypassing the django forms validation. The problem now is that it keep saving new instances at every interval. The correct behavior is to create the first instance and at subsequent interval only update the database with new data if there has been changes since the last auto save. The problem is i don't know how to store the id of the model instance that was just created so that at every call of the auto save javascript i can check if this auto save request a new request or existing request. I have not tried anything yet at this point. Getting it to this point where I can save the unchecked form/model instance already took a lot of time for me.