Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uploading Cyrillic files in Django
Good afternoon. I am writing share for a corporate portal. I ran into such a problem that after downloading files with Cyrillic, I try to download them, and Django gives a path error urls 404 the path to the file was not found. Tell me where I'm wrong. My models.py: from django.db import models from datetime import datetime from django.contrib.auth.models import User def user_directory_path(instance, filename): return 'user_{0}/{1}'.format(instance.owner.id, instance.name) class DirectoryItem(models.Model): name = models.CharField(max_length=200, default="New Folder", blank=False) owner = models.ForeignKey(User, on_delete=models.CASCADE) # a parent folder of null/blank would indicate a root folder. # A users root folder is created upon registration date_created = models.DateTimeField(default=datetime.now) is_recycled = models.BooleanField(default=False) # auto_now: updates on changes. date_recycled will be last change # (Improve - create custom save function) date_recycled = models.DateTimeField(auto_now=True) is_public = models.BooleanField(default=False) is_shared = models.BooleanField(default=False) class Meta: abstract = True class Folder(DirectoryItem): parent_folder = models.ForeignKey( "self", on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name class File(DirectoryItem): parent_folder = models.ForeignKey(Folder, on_delete=models.CASCADE) file_source = models.FileField(upload_to=user_directory_path) file_type = models.CharField(max_length=20) def __str__(self): return self.name My views.py , the function responsible for downloading the file: def folders(request, folder_id): requested_folder_id = folder_id cur_user_id = request.user.id requested_folder = Folder.objects.get(id=requested_folder_id) # Is it the users folder? if (requested_folder.owner.id != cur_user_id): # Does … -
Python Django always passes id 1 on ForeignKey with to_field
I'm new to Django and trying to create a small application that shows scanned data from virtual machines that are inserted in a table named HostsFixDataScans. To access the scanned data in HostsFixDataScans via the Hosts model, I defined a ForeignKey with to_field. But unfortunately, the data returned by the linked HostsFixDataScans are wrong. I checked the SQL statements and when requesting the HostsFixDataScans table, not the id of the Host is used, but always 1. My domain = models.ForeignKey(Domains, on_delete=models.CASCADE) definition which does not use to_field works correctly. I'm pretty sure, I have a misunderstanding of the definition of this relationship. Maybe you could give me some hints how to solve the problem? Many thanks in advance! Here are the shortened definitions of the models: class Os(models.Model): operatingsystem = models.CharField(max_length=32) lsbdistcodename = models.CharField(max_length=32) lsbdistrelease = models.CharField(max_length=32, db_collation='ascii_bin') lsbmajdistrelease = models.IntegerField() remarks = models.CharField(max_length=256, blank=True, null=True) class HostsFixDataScans(models.Model): host_id = models.PositiveIntegerField(primary_key=True, unique=True) scan_id = models.PositiveIntegerField() os = models.ForeignKey(Os, on_delete=models.CASCADE) class Hosts(models.Model): hostname = models.CharField(max_length=256) domain = models.ForeignKey(Domains, on_delete=models.CASCADE) is_virtual = models.PositiveIntegerField(blank=True, null=True) os = models.ForeignKey(HostsFixDataScans, to_field='host_id', on_delete=models.CASCADE) -
How do I port Django's ModelMultipleChoiceField widget to reactjs?
This is the widget I'm talking about: https://docs.djangoproject.com/en/4.0/ref/forms/fields/#modelmultiplechoicefield Here's a picture of it: https://i.stack.imgur.com/2tZhv.png Rendering it statically and preserving the style was easy, but I'm not sure how to do that dynamically, so that I'm able to dynamically feed it a list of input and be able to submit or change it or use the provided search bar. -
protect SQL injection on django Rest API
For penetration testing purpose, I am tring sql-injection to my Django Rest API,And I can successfully take schema , table and rows information by SQLmap. I was try several times,It was just simple API. I was create function based view, also a class base view, I was try with cursor and also try ORM.raw query try with parameterize. but every time I can injected sql by SQLMAP. I can't believe, how it happens, but I see result in my implementation. I am sure that I follow proper way. Please suggest my , how can I protect all type of API, which url have params. -
Django Rest Framework Viewset Filter By Value
Let's say I have a DRF viewset like so class SecretViewset( viewsets.ModelViewSet, ): queryset = Secret.objects.all() serializer_class = SecretSerializer @action(methods=['GET'], detail=True) def name(self, request, pk=None): secrets = Secret.objects.filter(name__contains=pk) return Response(self.get_serializer(secrets, many=True).data) I want to be able to search via a name in the URL. So /api/secrets/name/NAMEHERE/ However, because ModelViewset implements mixins.Retrieve, it returns a 404 because it searches /api/secrets/ID/ first and doesn't find it, therefore throws a 404. What would the proper way be to go about adding the ability to search by name as described above? Edit Adding my urls conf from .Secret.viewsets import SecretViewset router = routers.SimpleRouter() router.register(r'^api/secrets', SecretViewset, 'secrets') # Later on, router gets imported and added on via `urlpatterns += router.urls` -
Django celery with redis is executing same task multiple times
I'm trying to creating a background task with Django celery and Redis as broker. this task is being sent from models when model post save. But the problem is that, the same task is getting executed 1000 of times (other debug or add task are working fine). i have already tried this method but this didn't resolve the issue. Please find the below codes for your reference and help to resolve. Thanks in advance. models.py from django.db.models.signals import post_save from django.dispatch import receiver from student.tasks import create_student_subject_tryout_result, add @receiver(post_save, sender=TryoutSubmission, dispatch_uid='create_student_subject_tryout_result') def result_calculation(sender, instance, **kwargs): if instance.status == 'C': print('Calculating result') create_student_subject_tryout_result.delay(instance.student.id, instance.tryout.id) celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'eec.settings') app = Celery('eec') app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.broker_transport_options = {'visibility_timeout': 3600} . app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') tasks.py from celery import shared_task import tryout.models @shared_task(bind=True) def create_student_subject_tryout_result(self, student_id, tryout_id): tryout_submission=tryout.models.TryoutSubmission.objects.get( student_id=student_id, tryout_id=tryout_id ) tryout_questions = tryout_submission.tryout.tryoutquestion_set.all().count() answered_qs = tryout_submission.tryout.tryoutanswersubmission_set.filter( is_answered=True).count() correct_ans = tryout_submission.tryout.tryoutanswersubmission_set.filter( is_correct=True).count() tryout_submission.total_questions = tryout_questions tryout_submission.answered_questions = answered_qs tryout_submission.correct_answers = correct_ans tryout_submission.total_time = tryout_submission.end_time - tryout_submission.start_time tryout_submission.save() return "Result created" settings.py CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'django-cache' CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' -
Why am I getting a IntegrityError at, null value in a column that doesn't exists... Django
I am trying to hit an external api, when a user submits a form. I am using Django and Postgresql My Model class League_Mod(models.Model): host = models.CharField(max_length=50) Espn_League_Id = models.IntegerField(unique = True) Espn_S2 = models.CharField(max_length=3000) Espn_Swid = models.CharField(max_length=300) bigdata = models.JSONField(default=dict,null=True) My Serializer class Meta: model = League_Mod fields = ['host', 'Espn_League_Id','Espn_S2','Espn_Swid','bigdata'] Views where Owners is a large dictionary. league_data = { 'host' : request.data['host'], 'Espn_League_Id' :request.data['Espn_League_Id'], 'Espn_S2' : request.data['Espn_S2'], 'Espn_Swid' : request.data['Espn_Swid'], 'bigdata' : Owners } serializer = LeagueSerializer(data=league_data) print(serializer) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) my print serializer runs, and prints the data correctly. But I get an error: integrityError at /wel/ null value in column "hello" of relation "api_league_mod" violates not-null constraint DETAIL: Failing row contains (11, JPFL, 216415, AEAylLD7uSQQ7%2BenPr6av1H%2Fx0Hqbbpn8Jvr91ngxM1ll5ynO685mhN%2BSu..., {D19D67CA-C981-4CA2-8463-AF4111D2E8E2}, {"Person1": {"2010": [0, 1, 2, 2, 2, 3, 3, 3, 3, 4, 5, 5, 6,..., null). I am very unclear where the column hello is... and there is no relation to api_league_mod Model, so don't quite understand why my serializer is returning unvalid Any insight would be appreciated. Thanks! -
showing a field of multiplke choises in django admin
In my django admin I'm trying to show a field of my model which may has multiple values (like a list). Here's my definition of the field in models.py related_countries = CountryField( multiple=True, blank=True ) So when I create a model in the database, what I got as the value of the field is something like AL,AS Then for my admin page, I didn't put it in the list_display because I don't want it to be shown at the page where all the records of this models is printed. I want it to be shown only when I click one of the record and check the detail of this record. So when I'm at the page that shows everythhing, it works well. Also, the record cannont be modified on the admin page so I have this function on my admin code: def has_change_permission(self, request: HttpRequest, obj=None) -> bool: return False And there comes the issue: When I enter the page for the detail of the record, I got a TypeError at XXX unhashable type: 'list' and I'm pretty sure it comes from the field related_countries. Cause when I removed the function to make it possible to modify the record, anything … -
Render Excel templates
I'd like to have the ability to render Excel template files: and not create Excel files programmatically. There is a lib Templated-docs. But the templates themselves must be in on of the OpenDocument formats: .odt, .ods, .odp or .odg. Those templates are rendered to excel futher. This fact affects on formatting features when rendering to Excel. Is there any possibility to render directly to Excel file template? -
how to set a default for multiselect field in django
I have an Account model that extends django's custom User model: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) joined_groups = models.ManyToManyField(Group, related_name='joined_group', blank=True) created_groups = models.ManyToManyField(Group, blank=True) EMAIL_PREFERENCES = [ ('user_emails', 'User Emails'), ('group_emails', 'Group Emails'), ('leader_emails', 'Leader Emails'), ] email_preferences = MultiSelectField( verbose_name = 'Email Preferences', choices=EMAIL_PREFERENCES, blank=True, max_choices=3, max_length=255, ) When a User registers or signs up, as of now, they create a connected Account with the same id and pk with the fields of joined_groups and created_groups empty. However, they also have none of the email_preferences selected either. Here in lies my issue. I want a User who signs up to have the default for email_preferences true for all of them. Then, if they prefer to not receive any emails, they can edit their email_preferences on their Account page. Lastly, once the email_preferences have been selected, I need to add the conditional into the view to see whether or not this User should receive email notifications: For when a User creates a Group: class CreateGroup(CreateView): model = Group form_class = GroupForm template_name = 'create_group.html' def form_valid(self, form): group = form.save() group.joined.add(self.request.user) account = self.request.user.account account.created_chaburahs.add(group) account.joined_chaburahs.add(group) email = account.user.email # celery task to send email create_group_notification_task.delay(email) return HttpResponseRedirect(reverse('group_detail', … -
Adding condition to DeleteView in Django
I am learning basics of Django and trying to add a condition before deletion of Ingredient instance in a generic DeleteView. But it looks like DeleteView is just ignoring my condition. What am I doing wrong? Thank you in advance for looking at my question! class IngredientDelete(LoginRequiredMixin, DeleteView): model = Ingredient template_name = "inventory/ingredient_delete_form.html" success_url = "/ingredient/list" def delete(self, request, *args, **kwargs): object = self.get_object() if len(object.reciperequirement_set.all()) > 0: object.delete(save=False) messages.error("You can't delete an ingredient if it is used in Menu Items. Please update Menu items first. You can check related Menu items list on the Ingredient Details page") return render(request, "ingredient/<pk>", messages) else: return super().delete(request, *args, **kwargs) in python shell, for the instance object I try len(object.reciperequirement_set.all()) and get 1, so I suppose the query in my condition is set correctly. At local host page for the same Ingredient instance I get the error page: ProtectedError at /ingredient/23/delete ("Cannot delete some instances of model 'Ingredient' because they are referenced through protected foreign keys: 'RecipeRequirement.ingredient'.", {<RecipeRequirement: menu item: testdel, price: 34.00, ingredient: testingr: 22.00 tsp>}) Request Method: POST Request URL: http://127.0.0.1:8000/ingredient/23/delete Django Version: 4.0.4 Exception Type: ProtectedError -
implementing multi user types for hospital management system
so I am building a hospital management system as my pet project in Django, and one thing that I realized is that you need implement a 3 user multi system which includes the HR, staff(doctor) and patient. Been surfing through the internet for the best implementation and came up short. The best I saw was this tutorial blog on How to implement multi user system, but it doesn't cover on using more than 3 user like I want to. This is my current user/models.py from django.db import models from django.contrib.auth.models import AbstractUser USER_CHOICE = [ ('D', 'Doctor'), ('P', 'Patient'), ('R', 'Receptionist'), ('HR', 'HR') ] # Create your models here. class User(AbstractUser): """ user class for different users in the database """ user_type = models.CharField(choices=USER_CHOICE, max_length=3, default=None) def is_doctor(self): """ return True if the user is a doctor and False if not """ if self.user_type == 'D': return True return False def is_patient(self): """ return True if the user is a patient and False if not """ if self.user_type == 'P': return True return False def is_receptionist(self): """ return True if the user is a receptionist and False if not """ if self.user_type == 'R': return True return False def is_hr(self): … -
Make Django form choices depend on values submitted in a previous form
I'm using django-formtools to create a multi-step form wizard. I want to use data entered in the first step to call an API, then use the response data in the next step as a ChoiceField. This is what my code currently looks like: views.py from server.companies.models import Company from server.data_sources.models import DataDictionary, DataSource from django.shortcuts import render from formtools.wizard.views import SessionWizardView import json import logging from server.data_sources import ds from server.data_sources.models import SOURCE logger = logging.getLogger("server." + __name__) def create_records(data): if not data or data == {}: return name = data.get("company_name") is_sandbox = data.get("is_sandbox") city = data.get("city") state = data.get("state") username = data.get("username") password = data.get("password") data_source = DataSource.objects.create( name=name, source_type=SOURCE, ) ds.login(data_source, username, password) company = Company.objects.create( name=name, data_source=data_source, ) return company class Wizard(SessionWizardView): template_name = "wizard.html" def done(self, form_list, **kwargs): return render( self.request, "done.html", {"form_data": [form.cleaned_data for form in form_list]}, ) def get_form_step_data(self, form): return form.data def get_form(self, step=None, data=None, files=None): form = super().get_form(step, data, files) company = None # determine the step if not given if step is None: step = self.steps.current if step == "0": if form.is_valid(): step_zero_data = form.cleaned_data company = create_records(step_zero_data) source = company.data_source data_dict = {} for field in ds.select( company, "DATADICT", ["dd_dbf", … -
Heroku Django post-gis extension: Error "no attribute 'geo_db_type'" problem when migrating a new model that contains geo elements
I'm running into this issue when deploying my django app on heroku. It had be building and deploying fine before I edited my django model to include a geometry field: geom = models.PointField(verbose_name='geo',srid = 4326) Now it builds successfully, but then fails at this migration code in the Procfile `release: python manage.py migrate` The migration file is successfully in my git repo. And locally I was able to run python manage.py migrate successfully. When I go to migrate on heroku I get the below error. AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type' It seems to indicate that there is something "geo-related" missing, but I can't figure out what since I have created a postgis extension on the postgres db in heroku and I have the heroku-geo-buildpack along with the heroku/python buildpack. On heroku I have python 3.10 and locally it's Python 3.9.13. In my settings.py file I have: 'ENGINE':'django.contrib.gis.db.backends.postgis', in the DATABASES and 'django.contrib.gis', in INSTALLED_APPS Here's the post-gis extension on the heroku postgres database: And the two buildpacks set in heroku: Thank you for any help or guidance! -
"Invalid value." error while using django rest framework Serializer
I am trying save some information from a csv file into the DB using django rest framework, currently I am not sure where is the issue if it is in the view or something in the model, to test it out I am sending the data as it is arriving to the serializer Here there is my view.py import re import csv import codecs import pandas as pd from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.shortcuts import render from rest_framework.decorators import api_view # Create your views here. from rest_framework import viewsets,status from .serializer import tripSerializer #,DataSourceSerializer from .models import Trips from rest_framework.response import Response class TripViewSet(viewsets.ViewSet): def list(self, request): queryset = Trips.objects.all() serializer = tripSerializer(queryset, many=True) return Response(serializer.data) def insert(self, request): file=codecs.EncodedFile(request.FILES.get("file").open(),"utf-8") print(type(file)) reader = pd.read_csv(file, delimiter=";") reader.columns = ['region','origin_coord','destination_coord','datetime','datasource']; reader=reader.to_dict(orient = 'records')[0] print("--------------------------------------------------------") print("DATA inicial",reader) print("--------------------------------------------------------") data={'region': 'Prague', 'origin_coord': 'POINT (14.4973794438195 50.00136875782316)', 'destination_coord': 'POINT (14.43109483523328 50.04052930943246)', 'datetime': '28/05/2018 9:03', 'datasource': 'funny_car'} serializer = tripSerializer(data=reader) print("trying to validate") if serializer.is_valid(): serializer.save() return Response({"status":"success"}, status=status.HTTP_200_OK) else: return Response({"status":"Error!!","data":serializer.data,"Error:":serializer.errors,"message_error":serializer.error_messages}, status=status.HTTP_400_BAD_REQUEST) Serializer.py from django.shortcuts import render # Create your views here. from dataclasses import field, fields from rest_framework import serializers from .models import Datasources, Regions, Trips … -
how to serialize two classes have one to many relation in django
this is my models class Users(models.Model) : name = models.CharField(max_length=20 , blank=False , null=False) email = models.EmailField(max_length=50 , blank=True , null=True) password = models.CharField(max_length=30 , blank=False , null=False) birthday = models.DateField(null=False) photo = models.ImageField(upload_to = 'user_photos/%y/%m/%d') #friend = models.ManyToManyField('self',through='Notif',null=True,related_name='friend') class Product(models.Model): pub_date = models.DateTimeField(default=datetime.now) price = models.DecimalField(max_digits=100000,decimal_places=5,null=False,blank=False) size = models.IntegerField(null=True,blank=True,default='undefined') photo = models.ImageField(upload_to = 'product_photos/%y/%m/%d',null=True) #for 1--n relation with users user_id = models.ForeignKey(Users,on_delete=models.CASCADE,null=True,related_name='user') this is my serializers.py class ProductSerializer (serializers.ModelSerializer): class Meta : model = Product fields = '__all__' class UsersSerializer(serializers.ModelSerializer): class Meta: model = Users fields = '__all__' i want to send product object with the email of his user what i have to do in serializers and views to make it note i use function based views in my views -
How can I store images on server and serve them with nginx and django?
I've created a Django app and I'm using Gunicorn and Nginx with it on an Ubuntu server. Nginx serve my static files and it work great for css files and javascript, but I have problem with images. App is my personal blog site and I'm using Django ckeditor for uploading images and writing some text.Everything worked as it should while I was using local server, but when i deploy it on cloud server images are not displayed. here's my project/app/models.py from django.db import models import uuid from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class Category(models.Model): title = models.CharField(max_length=150) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.title class Article(models.Model): title = models.CharField(max_length=150) description = models.CharField(max_length=150, blank=True, null=True) body = RichTextUploadingField(blank=True, null=True) profile_image = models.ImageField(null=True, blank=True, default='default.png') category = models.ForeignKey(Category, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.title class Meta: ordering = ['-created'] The code below is in settings.py: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] MEDIA_ROOT = '/var/www/my-website.com/media' STATIC_ROOT = '/var/www/my-website.com/static' CKEDITOR_UPLOAD_PATH = 'uploads/' In project urls.py I add: urlpatterns = [ . . . path('ckeditor', include('ckeditor_uploader.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) … -
How to configure data migration from one model to another . Django?
There is model Leads with fields : name, phone, email, address and I create model Contacts with the same fields but with processed data from Leads for example, combine all leads with the same names and phone numbers into one contact, etc. how to implement it? whether to create a migration or a . how it is better to implement it? -
accordion with for loop to only open one item at a time
I am trying to add an interactive id to my accordion, but something is off in my code and the accordion opens every accordion item, all I want is to be able to open one accordion item at a time when clicking on it. {% for study in studies %} <div class="accordion" id="accordionExample"> <div class="accordion-item"> <h2 class="accordion-header" id="heading{study.uid}"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs- target="#collapse{study.uid}" aria-expanded="true" aria- controls="collapse{study.uid}"> {{ study.uid }} </button> </h2> <div id="collapse{study.uid}" class="accordion-collapse collapse" aria- labelledby="heading{study.uid}" data-bs-parent="#accordionExample"> <div class="accordion-body"> text </div> </div> </div> {% endfor %} -
Python/Django - Best way to avoid UnboundLocalError when a list is empty
I'm using a list to get data from an API. This list is created with a code like this: mylist = [] for batch in stream: for row in batch.results: data = {} data["color"] = row.color data["count"] = row.count mylist.append(data) And the list end up being something like: mylist = [{'color':'red','count':5}, {'color':'blue','count':7}] And then I send it to the Django template using something like this: context = { 'mylist' : mylist, 'data' : data, } return render(request, 'page.html', context) This works OK most of the time. But sometimes there is no data to send, so the API doesn't send anything and mylist is empty. When that happens, I get an error: UnboundLocalError at /page local variable 'data' referenced before assignment I've "solved" it with the following code: if not mylist: data = {"error": "no data"} That removes the error, but seems very "hacky". I don't need that info in my list. If there is no data, I would probably prefer to have the list empty (so I can do an "if" to check if it's empty or not and stuff like that). Is there a better solution? Thanks! (I'm learning Python and Django, so maybe most of my code can … -
GCBV Generic Class Based View, Django Classes Issue
$ Hello, I was trying to use "GCBV Generic Class Based View" for edit a post, but it seems not working and event it django can't find my HTML and I don't know why , Hope I get some support …. $ edit button link {% if post.created_by == user %} <div class="mt-3"> <a class="btn btn-success float-end" href="{% url 'edit_post' post.topic.board.pk post.topic.pk post.pk %}">Edit</a> </div> {% endif %} $ edit HTML Page {% extends 'base.html' %} {% load static %} {% block title %}Edit Post{% endblock %}<!-- | Page-title--> {% block content %} <link rel="stylesheet" href="{% static 'css/boards.css' %}"> <div class="newtopic"> <div class="container container-newtopic w-50"> <h1>Edit Post</h1> <br> {% include 'parts/alerts.html' %} <div aria-label="breadcrumb"> <ol class="breadcrumb n1-head"> <li class="breadcrumb-item"><a href="{% url 'boards' %}">Boards</a></li> <li class="breadcrumb-item"><a href="{% url 'topics' post.topic.board.pk %}"> {{post.topic.board.name}}</a></li> <li class="breadcrumb-item active" aria-current="page"><a href="">Edit Post</a></li> </ol> </div> <form method="POST" action="" novalidate class="mb-4"> {% csrf_token %} {% include 'includes/form.html' %} <button type="submit" class="btn main-btn w-100 rounded-pill mt-5"> Save Changes </button> </form> </div> </div> {% endblock %} $ Views.py @method_decorator(login_required, name='dispatch') class PostUpdateView(UpdateView): model = Post fields = ('message',) template_name = 'edit_post.html' pk_url_kwarg = 'post_id' context_object_name = 'post' def form_valid(self, form): post = form.save(commit=False) post.updated_by = self.request.user post.updated_date = timezone.now() … -
Django Rest API Unit Testing returning 401 Unauthorized for endpoint tests
I created some unit tests with basic asserts checking for status codes to get a few tests done and working. The endpoints themselves work flawlessly when I test them individually outside of the Django unit tests using manage.py test test_file However, I am getting a 401 Unauthorized on all endpoints when I run the tests. I have tried writing in several auth methods to correct the issue but no matter what I try, a 401 is returned. I have tried adding a force auth function, changing TestCase to APITestCase, and creating a superuser manually in the setUp() for each of my test cases. All of the solutions I have found online for similar problems still yield the 401, unauthorized error. Using: Django 3.2.14 Python 3.10.4 I have also followed the Django Rest API documentation for test cases to the letter. I get 401 errors all the way through. -
how to implement depended dropdown lists in Django formset
The code below represents the scripts that are working well in the Django formset but only in the first formset. When I add another one it is showing me the list of components only from the first product. How can I make my dropdown list feature more dynamic so it changes for example form-0 into form-1 if it the second formset is created? I'd appreciate any help. my html file <body> <form id="form-container" method="POST" data-components-url="{% url 'ajax_load_components' %}"> {% csrf_token %} {{ce_request_formset.management_form}} {% for form in ce_request_formset %} <div class="ce-request-form"> {{ form|crispy }} </div> {% endfor %} <button id="add-form" type="button">Add component</button> <button type="submit">Send CE</button> </form> </body> <script> // Script to handle adding new forms in html file let CERequestForm = document.querySelectorAll(".ce-request-form") let container = document.querySelector("#form-container") let addButton = document.querySelector("#add-form") let totalForms = document.querySelector("#id_form-TOTAL_FORMS") let formNum = CERequestForm.length-1 addButton.addEventListener('click', addForm) function addForm(e){ e.preventDefault() let newForm = CERequestForm[0].cloneNode(true) let formRegex = RegExp(`form-(\\d){1}-`,'g') formNum++ newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`) container.insertBefore(newForm, addButton) totalForms.setAttribute('value', `${formNum+1}`) } // Script to handle dependent dropdown lists $("#id_form-0-related_product").change(function () { var url = $("#form-container").attr("data-components-url"); var related_product_id = $(this).val(); $.ajax({ url: url, data: { 'related_product': related_product_id }, success: function (data) { $("#id_form-0-related_component").html(data); } }); }); </script> -
Django-tables2 pagination
While using django-tables2 I couldn't find how I paginate the table. On the documentation It says enough to set the table for view but doesn't work. class TableView(SingleTableView): model = TableModel table_class = MyTable template_name = "table.html" -
Django Recursive Foreign Key for Serializer Getting not iterable errors
I followed a lot of answers regarding my questions, I tried all solutions given here Basically scenario is almost same I wanted recursive query in my serializer. Firstly I want to show my models class Policy(TimeStampedModel): product = models.ForeignKey(Product, related_name='policies', on_delete=models.PROTECT, null=True) name = models.CharField(max_length=32) slug = AutoSlugField(populate_from='name', editable=True, slugify_function=slugify) and I have Foreign Key from Policy to PolicyCondition here is policy condition model. class PolicyCondition(TimeStampedModel): policy = models.ForeignKey(Policy, on_delete=models.CASCADE) name = models.CharField(max_length=200) slug = AutoSlugField(populate_from='name', editable=True, slugify_function=slugify,null=True) text = models.TextField() parent = models.ForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True, related_name='children' ) On serializer I am fetching all my data from policy model. Here is my serializer. class PolicyListSerializer(serializers.ModelSerializer): conditions = PolicyConditionSerializer(source='policycondition_set', many=True) class Meta: model = Policy fields = ['conditions'] Here is my policy condition serializer class PolicyConditionSerializer(serializers.ModelSerializer): class Meta: model = PolicyCondition fields = [ 'id', 'policy', 'name', 'text', 'slug', 'parent' ] def to_representation(self, instance): self.fields['parent'] = PolicyConditionSerializer(read_only=True) return super(PolicyConditionSerializer, self).to_representation(instance) I am getting error as PolicyCondition' object is not iterable any soluton what I am missing here.