Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Direct mail django
I am looking for the code to make personnalized letters with text editor from IHM, with insert elements from the database. It will be usefull for editing worker's contract. I think about an application like direct mailing from MS WORD. -
Integration of Front End and Backend
I am planning on creating a React/Django web application. I plan on creating an API on the backend to communicate with my React app. I understand you can integrate React with django by including your react app in the django project directory and pointing to the index.html in react. I'm still not sure what the benefits of this are. Would it be better just to separate the django and react application. Whenever I would need to store or retrieve data I could just make requests the django API? -
TypeError at /login Strings must be encoded before hashing
i am facing an error from this django project .... i have tried all the advices i can come across still its not working properly...... below is the error from the web Environment: Request Method: POST Request URL: http://127.0.0.1:8000/login Django Version: 2.2 Python Version: 3.9.7 Installed Applications: ['main', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_filters'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\venv1\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\venv1\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\venv1\lib\site-packages\django\core\handlers\base.py" in _get_response 113.response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\FacialRecognitionForPolice-master\main\views.py" in login 171.hashed = bcrypt.hashpw(request.POST['login_password'], bcrypt.gensalt()) File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\venv1\lib\site-packages\bcrypt_init_.py" in hashpw 79.raise TypeError("Strings must be encoded before hashing") Exception Type: TypeError at /login Exception Value: Strings must be encoded before hashing -
Como construir um sistema de repositório semelhante ao Github ou ao Google Drive para um projeto Web (Django)?
Estou construindo um site para portfólio e queria deixá-lo profissional. Quero construir um sistema de portfólio semelhante ao Github, mas sei que a implementação é complexa. Para exemplificar minha ideia, segue a imagem abaixo: enter image description here Outra dúvida seria como modelar o Banco de Dados e, por fim, como incorporar ao Django esta solução? -
Django not detecting language variations i.e. pt-br
I am trying to add Spanish and English variations to my site. Specifically: es-cl, es-pe, es-ar, pt-br. However, once I generate the translations and compile them, it only loads the es and pt values, not the country-specific ones. This is my config file GLOBAL_LANGUAGES = [ ('es', _('Español')), ('en', _('Inglés')), ('pt', _('Portugués')) ] COUNTRY_LANGUAGES = [ ('pt-br', _('Portugués (Brasil)')), ('es-cl', _('Español (Chile)')), ('es-ar', _('Español (Argentina)')), ('es-pe', _('Español (Perú)')), ] LANGUAGES = GLOBAL_LANGUAGES + COUNTRY_LANGUAGES # https://docs.djangoproject.com/en/3.1/ref/settings/#use-i18n USE_I18N = True # https://docs.djangoproject.com/en/3.1/ref/settings/#use-l10n USE_L10N = True This is the data when I access these values from my templates, where I can see that the code is repeated for English languages. {'BIDI': FALSE, 'CODE': 'ES', 'NAME': 'SPANISH', 'NAME_LOCAL': 'ESPAÑOL', 'NAME_TRANSLATED': 'ESPAÑOL'} {'BIDI': FALSE, 'CODE': 'EN', 'NAME': 'ENGLISH', 'NAME_LOCAL': 'ENGLISH', 'NAME_TRANSLATED': 'ENGLISH'} {'BIDI': FALSE, 'CODE': 'PT', 'NAME': 'PORTUGUESE', 'NAME_LOCAL': 'PORTUGUÊS', 'NAME_TRANSLATED': 'PORTUGUÊS'} {'BIDI': FALSE, 'CODE': 'PT-BR', 'NAME': 'BRAZILIAN PORTUGUESE', 'NAME_LOCAL': 'PORTUGUÊS BRASILEIRO', 'NAME_TRANSLATED': 'PORTUGUÊS BRASILEIRO'} {'BIDI': FALSE, 'CODE': 'ES', 'NAME': 'SPANISH', 'NAME_LOCAL': 'ESPAÑOL', 'NAME_TRANSLATED': 'ESPAÑOL'} {'BIDI': FALSE, 'CODE': 'ES-AR', 'NAME': 'ARGENTINIAN SPANISH', 'NAME_LOCAL': 'ESPAÑOL DE ARGENTINA', 'NAME_TRANSLATED': 'ESPAÑOL (ARGENTINA)'} {'BIDI': FALSE, 'CODE': 'ES', 'NAME': 'SPANISH', 'NAME_LOCAL': 'ESPAÑOL', 'NAME_TRANSLATED': 'ESPAÑOL'} In the views, I'm checking that the language is activating successfully, but even if I … -
Django Vue.js Axios PUT Not allowed 405
I am developing a small inventory management project. I am trying to update the stock amount when some kind of a product is being withdrawn. I am using Axios and .put() function, and when I send the request it says 405 not allowed. I can't seem to understand what the problem is. I am sending the product id to the backend and using it to identify the product which stock amount I want to upgrade. Hope you will be able to point my errors and teach me how to make it work. Here is the Views from Django: class materialWithdraw(APIView): authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.BasePermission] def update(self, request, *args, **kwargs): serializer = WithdrawFormSerializer(data=request.data) if serializer.is_valid(): material_id = serializer.validated_data['id'] quantity_to_withdraw = serializer.validated_data['quantity'] withdrawn_material = Listing.objects.get(id=material_id) withdrawn_material.quantity = withdrawn_material.quantity - quantity_to_withdraw serializer.save(quantity=withdrawn_material.quantity) return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is the urls.py: urlpatterns = [ path('all-materials/', views.allMarketingMaterials.as_view()), path('all-medical-lines/', views.allMedicalLines.as_view()), path('gastroenterologia/', views.gastroenterologiaMaterials.as_view()), path('withdraw/', views.materialWithdraw.as_view()), ] and this is my script from Vue.js: export default { name: "Gastroenterologia", components: {}, data() { return { gastroenterologiaMaterials: [], quantity: 0, id:'', } }, mounted() { document.title = "Gastroenterologia"; this.getGastroenterologiaMaterials() }, methods: { getGastroenterologiaMaterials() { axios .get('/api/v1/gastroenterologia/') .then(response => { this.gastroenterologiaMaterials = response.data console.log(this.gastroenterologiaMaterials) }) .catch(error => … -
How to fix error with related models serialization, that have HyperlinkedIdentityField?
I'm getting this error when I try to get /api/dishes-types/ page in my site: ImproperlyConfigured at /api/dishes-types/ Could not resolve URL for hyperlinked relationship using view name "category-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. I've tried to apply to my code all the solutions from this page, but nothing worked for me. How to solve this error ? I'm really got stuck... And here is my code. models.py: *I've replaced metaclasses and magic __str__ methods that are intended to admin panel from django.db import models class Category(models.Model): name = models.CharField(max_length=30, unique=True) class DishesType(models.Model): name = models.CharField(max_length=30, unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) class Dish(models.Model): name = models.CharField(max_length=64, unique=True) type_of_food = models.ForeignKey(DishesType, on_delete=models.CASCADE) description = models.CharField(max_length=1000) prices = models.JSONField() serializers.py: from rest_framework.exceptions import ValidationError from rest_framework.fields import SerializerMethodField from rest_framework.relations import HyperlinkedIdentityField from rest_framework.serializers import HyperlinkedModelSerializer from Pub.models import Category, DishesType, Dish class BaseSerializerMixin(HyperlinkedModelSerializer): @staticmethod def validate_name(name): if not name.replace(" ", "").isalnum(): raise ValidationError( "'name' field may contain only letters, numbers and spaces. Change it, please !" ) return name # # DISH SERIALIZERS # class DishSerializerMixin(BaseSerializerMixin): dish_url = HyperlinkedIdentityField(view_name="dish-detail", lookup_field="name") class DishesSerializer(DishSerializerMixin): class Meta: model = … -
Best Way To Store User Info separate from User model in django
Say I have a bunch of flags/options related to using my app. Stuff like firstSetupCompleted, tutorialCompleted, userExperienceLevel. What would be the best way to store these on a per-user basis? The options I've considered so far are django-constance package A profile model that's 1-1 with a User model a JSON field on the user model What would the best approach be to storing flags/info related to using the site, but not necessarily directly related to the user themselves (thus do not want to store in the User model) -
How can i use firebase cloud storage to handle static files
I am building a a Practice blog with django, after hosting it on heroku, i discovered that any images i upload using image field or fetch disappear after a while. Now i started using firebase cloud storage via django-storage gloud backend and it is working fine since then , but when i tried hosting my staticfiles storage from there is get this error cross origin request blocked the same-origin policy disallows reading the remote resource at? how do i fix this? -
Dynamic 'Order' column based on 'Datetime_submitted' is not updating when 'Datetime_submitted' is updated
I am creating a queue management system where patrons can sign-up in person for passport applications and the staff are able to see a queue of people based off of their form submission time. The code in my model.py is working for every scenario I have tried (New submissions, no-shows, cancelled, etc) except for if a staff were to change the form submission time to alter the order. When this occurs, the order number changes for the row modified but not any other rows. However, all I need to do to update the order on the rest of the rows is open up a row and click 'save' then all of the rows update. This is a very minor issue and I could simply disallow the modification of the 'datetime_submitted' feild. However, this is my first Django project so I would love to know why the 'order' column doesn't update when the 'datetime_submitted' is modified. Apologies in advance as this is also my first time asking a question as well. I am just including my model.py file because the forms and stuff do not matter and all editing and testing is currently being done through the Django admin login. model.py … -
DRF Error: 'str' object has no attribute 'decode'
Hi Everyone I am creating a login api using Jwt in django but i am getting error -'str' object has no attribute 'decode', if i remove decode('utf-8') then i am getting token in response but this token when i use other api then getting Error:-Given token not valid for any token views.py class LoginApiview(APIView): def post(self,request): user_name=request.data['user_name'] password=request.data['password'] user=EmpUser.objects.filter(user_name=user_name).first() if user is None: raise AuthenticationFailed('User not found') payload ={ "id":user.id, "exp":datetime.datetime.utcnow() + datetime.timedelta(days=1), "iat":datetime.datetime.utcnow(), "user_name":user.user_name } token=jwt.encode(payload,'secret',algorithm='HS256').decode('utf-8') return Response({"message": "login sucessfully","error":False,"code":200,"results":{"token":token}},status=HTTP_200_OK) -
How to display django data in multiple rows
So I am making a website using Django, HTML/CSS, and Bootstrap 5 to display books a user has. Currently, all the books are displayed in one row but I would like them to be split up into multiple rows with three on each row. How should I go about doing this? This is the model I'm using for the book: lass Book(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) isbn = models.CharField('ISBN', max_length=16, unique=True, help_text='10 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>') title = models.CharField(max_length=10, null=True, blank=True) image_src = models.CharField(max_length=400, null=True, blank=True) author = models.CharField(max_length=50, null=True, blank=True) desc = models.CharField(max_length=1000, null=True, blank=True) LOAN_STATUS = ( ('AVAILABLE', 'Available'), ('ON LOAN', 'On Loan'), ('ON HOLD', 'On Hold'), ) GENRES = { ('REALISTIC FICTION', 'Realistic Fiction'), ('HISTORICAL FICTION', 'Historical Fiction'), ('SCIENCE FICTION', 'Science Fiction'), ('ADVENTURE', 'Adventure'), ('FANTASY', 'Fantasy'), ('HORROR', 'Horror'), ('MYSTERY', 'Mystery'), ('NON-FICTION', 'Nonfiction'), } genre = models.CharField( max_length=30, choices=GENRES, blank=True, help_text='Book Genre', ) status = models.CharField( max_length=30, choices=LOAN_STATUS, blank=True, default='Available', help_text='Book Availabiliy', ) def __str__(self): #String representing model object return self.title And this is the HTML for the book list page: {% extends "base_generic.html" %} {% block content %} <div class="d-flex justify-content-around pt-4"> {% for book in object_list %} <div><a href="{% url 'book_detail' book.pk %}"> <img … -
How to set a timer in the backend for 10 minutes?
I have a ticket booking system for events. When someone wants to book a ticket, it should "reserve" it for n minutes for the person to purchase it. If he does not purchase it, then the ticket should be released after n minutes. How should I go about doing this sort of system? I am thinking of storing the timestamp of each entry on redis or something, then checking every 10 seconds and if it has been n minutes without a confirmed booking, then I release the ticket? I'm not sure if this approach will work and I don't know what to search on google on how to do this. Any help would be appreciated. My backend is django if that is useful. -
Error when assigning HyperlinkedIdentityField to a field with names other than "url"
I'm trying to apply HATEOAS to my Django REST framework API. I have a model called Coupon: class Coupon(models.Model): code = models.CharField( max_length=10, help_text='Promotion code to get free access to any product or service.' ) description = models.CharField(max_length=200, blank=True) expires = models.DateField() Then a HyperlinkedModelSerializer: class CouponModelSerializer(serializers.HyperlinkedModelSerializer): # the problem url = serializers.HyperlinkedIdentityField(view_name='market-api:coupons-detail') created_by = serializers.SlugRelatedField( read_only=True, slug_field='username' ) class Meta: model = Coupon exclude = ['modified', 'active'] read_only_fields = ['id', 'created_by', 'created'] Finally CouponsViewset: class CouponsViewSet(DestroyIotaModelMixin, viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = Coupon.objects.filter(active=True) serializer_class = CouponModelSerializer The viewset is register with a DefaultRouter router = DefaultRouter() router.register(r'coupons', CouponsViewSet, basename='coupons') And in the project urls: path('market-api/', include(('iota.market.urls', 'market'), namespace='market-api')) The problem goes when I change the attribute name of the HyperlinkedIdentityField in the serializer. Whatever I set trows an error Evidence: I have tried debugging but have not found the cause. -
How to count views of blog in django
i am trying to count and show all views in every blog in my django project. What is the best way to do that?(pardon mistakes? -
How to implement CRUD operation with Django Rest mixins
I'm trying to implement CRUD operation with nested serializer with multiple data models so that I can write all field at once when I call the API endpoint. I use mixins from REST framework https://www.django-rest-framework.org/api-guide/generic-views/#mixins I have found some relevant examples but still, my serializer is only returning the fields from the Student model for CRUDoperation. I'm not able to see the Course models field in REst api ui. How can I do CRUD operation with using mixins ? How to display Data from two model without creating new model in Django? use of mixins class defined in Django rest framework models.py class Student(models.Model): student_id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) firstName = models.CharField(max_length=20) age = models.IntegerField(default=18) class Course(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) courseName = models.CharField(max_length=20) courseYear = models.IntegerField(default=2021) student = models.ManyToManyField(Student, related_name='courses') class Homework(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) hwName = models.CharField(max_length=20) hwPossScore = models.IntegerField(default=100) course = models.ForeignKey(Course, related_name='homeworks', on_delete=models.CASCADE, null=True, blank=True) students = models.ManyToManyField(Student) Serializers.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = "__all__" class HomeworkSerializer(serializers.ModelSerializer): class Meta: model = Homework fields = __all__ class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = "__all__" ###I combine both Student and Course into one class All_Serializer(serializers.ModelSerializer): students = serializers.SerializerMethodField() homeworks = … -
How to add comments without authentification required
i just done comments on my website,and i want to do non-authorized comments,and dont know how to.My models looks like this class Comment(models.Model): article = models.ForeignKey(Product, on_delete = models.CASCADE, verbose_name='Page', blank = True, null = True,related_name='comments' ) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, verbose_name='Comment author', blank = True, null = True ) create_date = models.DateTimeField(auto_now=True) text = models.TextField(verbose_name='Comment text', max_length=500) status = models.BooleanField(verbose_name='Visible', default=False) and views.py like this def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): self.object = form.save(commit=False) self.object.article = self.get_object() self.object.author = self.request.user self.object.save() return super().form_valid(form) -
Django ORM: How to GROUP BY a field that "lives" in the bottom of a recursive model?
Let's say I have the following models: class Unit(models.Model): name = models.CharField(...) class PackageDescription(models.Model): lower_level = models.ForeignKey("self", null=True, ...) unit = models.OneToOneField(Unit, null=True, ...) class StockItem(models.Model): package_description = models.OneToOneField(PackageDescription, ...) I want to know the amount of unit names in a given StockItem queryset (qs). If we don't had this recursive nature, we could simply do something like: qs.values("package_description__unit__name").annotate(count=Count("package_description__unit__name")) However, a PackageDescription can have several levels, and the Unit "lives" in the bottom of the structure. How would I know, within DB level, the lowest level? And more than that: how can I GROUP BY such field? NOTE: I'm using PostgreSQL. -
django createView return UNIQUE constraint failed: answer_profile.user_id when i submited the form
I'm trying to add User profile for user's in my website when they finished creating a user registration form it will redirected the user to the Profile model where they will create a Profile for their account. I successfully created a user registration form and it works fine but when the form is submitted and redirected a new user to the Profile model where i use CreateView the form throws an error when i submitted the form. the error: IntegrityError at /CreateProfile/ UNIQUE constraint failed: answer_profile.user_id Or is there anyway i can create a custom User profile for all new user when they create an account in my app. Like Stack Overflow. When a user created an account using Github, Facebook or Gmail the Stack Overflow will create a custom User profile where you can edit it. I have successfully created an edit profile. my views: class CreateProfile(CreateView): model = Profile fields = ['profile_image', 'stories', 'website', 'twitter', 'location'] template_name = 'create.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.user = self.request.user return super (CreateProfile, self).form_valid(form) def register(request): if request.method == 'POST': username = request.POST['username'] first_name = request.POST['first_name'] last_name = request.POST['last_name'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] if password … -
How to create absolute url inside serializer
Freshly created image field has only relative url - ImageFieldFile My serializer image field - ImageField How can I get the full url to this file? Should i just iterate over serializer data and append my domain before path? - example -
Is s3direct still supported?
I am using Django on heroku. I use Amazon s3 for my file storage. I am trying to use https://github.com/bradleyg/django-s3direct solution for large file uploads. I did everything I the tutorial but the file widget doesn’t appear in my admin. Is this solution still supported? -
Why django create empty field?
Hello I have simple model: class Company(models.Model): name = models.CharField(max_length=150, unique=True, blank=False) fullname = models.CharField(max_length=250, blank=True, null=True) description = models.TextField(blank=True, null=False) ... And I created simple test: ... def test_create_company_fail_name(self): """ Why create empty name Models!""" payload = { 'fullname': 'Test2Django', 'description': 'Simple test', 'country': 'Poland', 'city': 'Gdynia' } company = Company.objects.create(**payload) self.assertEqual(Company.objects.count(), 1) Why django create model if it didn't get field 'name'? But when I create model in admin section then I get error 'Field is require'. -
How to assign ForeignKey MySQL item in views.py?
When I save my NoteForm, I want to save my form and the "note" field, then I want to create a "tag" for the Note in the NoteTagModel. At the moment, I create a new tag but it is not assigned to the note. I know that the following code must be wrong: notetag.id = new_note_parse.id If I change to: notetag.note = new_note_parse.id I receive the following error: "NoteTagModel.note" must be a "NoteModel" instance. The below is my views.py: def notes(request): note_form = NoteForm notetag = NoteTagModel() note_form=NoteForm(request.POST) if note_form.is_valid(): new_note = note_form.save(commit=False) new_note_parse = new_note new_note.save() notetag.id = new_note_parse.id notetag.tag = "Test" notetag.save() return HttpResponseRedirect(reverse('notes:notes')) context = { 'note_form' : note_form, 'notes' : NoteModel.objects.all(), 'notes_tag' : NoteTagModel.objects.all(), } return render(request, "notes/notes.html", context) My models.py is: class NoteModel(models.Model): note = models.CharField( max_length = 5000 ) def __str__(self): return f"{self.note}" class NoteTagModel(models.Model): note = models.ForeignKey( NoteModel, on_delete=models.CASCADE, related_name="notes", blank= False, null = True, ) tag = models.CharField( max_length = 5000 ) def __str__(self): return f"Note: {self.note} | Tag: {self.tag}" I have the following as my forms.py: class NoteForm(ModelForm): class Meta: model = NoteModel fields = [ 'note', ] Any help would be greatly appreciated -
Django | Get count of articles per month
I got two models Article and Author implemented like this: class Author(models.Model): name = models.CharField(max_length=50) class Article(models.Model): name = models.CharField(max_length=50) author = models.ForeignKey(Author, on_delete=models.CASCADE) pub_date = models.DateField() On my template I want to plot a graph (using chart.js on the frontend side) showing the authors publications per month, for the last 12 months. For that I need the count of articles published each month. This is the query to get the authors articles: articles = Article.objects.filter(author=author) What would be best practice to get the count per month? I've thought about annotating each of the twelve month separately to the QuerySet, but haven't found a way that works for me. Alternatively, I thought about dealing with this on the JS site in the users browser. Any suggestions/recommendations? -
How to Replace All __prefix__ Placeholder Strings within Django Formsets empty_form Elements Using Only Javascript?
Django formsets have an empty_form attribute. empty_form BaseFormSet provides an additional attribute empty_form which returns a form instance with a prefix of __prefix__ for easier use in dynamic forms with JavaScript. The Django documentation doesn't actually say how to replace the __prefix__ with Javascript. Several online examples show how to do it with jQuery, but I specifically want to do it with Javascript - no jQuery. Here is the resulting HTML from my {{ formset.empty_form }}: <div id="prerequisiteEmptyForm"> <input type="text" name="prerequisites-__prefix__-text" maxlength="100" id="id-prerequisites-__prefix__-text"> <label for="id-prerequisites-__prefix__-DELETE">Delete:</label> <input type="checkbox" name="prerequisites-__prefix__-DELETE" id="id-prerequisites-__prefix__-DELETE"> <input type="hidden" name="prerequisites-__prefix__-id" id="id-prerequisites-__prefix__-id"> <input type="hidden" name="prerequisites-__prefix__-content" value="21" id="id-prerequisites-__prefix__-content"> </div> Everywhere it shows __prefix__, I want to replace it with a number... let's say 321. Correct solution: <div id="prerequisiteEmptyForm"> <input type="text" name="prerequisites-321-text" maxlength="100" id="id-prerequisites-321-text"> <label for="id-prerequisites-321-DELETE">Delete:</label> <input type="checkbox" name="prerequisites-321-DELETE" id="id-prerequisites-321-DELETE"> <input type="hidden" name="prerequisites-321-id" id="id-prerequisites-321-id"> <input type="hidden" name="prerequisites-321-content" value="21" id="id-prerequisites-321-content"> </div> So my question becomes Using Javascript only, how do I replace a constant value ("__prefix__") with something else ("321") across several elements (inputs and labels) within multiple attributes (name, id)? Specifically, I want to do it cleanly for repeatability. I don't want a highly custom solution to this specific problem. It needs to be a general approach... since this is replacing …