Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problems with building an e-commerce platform
i am trying to make a website that allow any one create his own e-commerce website & app without any coding but ... Now almost everything is ready for me, but there are some problems that I want suggestions to solve First problem: Now the platform is creating a website for the client using django This site is made of react js How can I connect my project to sharedhost so that it will automatically send the site files to it and puts it inside a subdomain in another way Allowing the user to deploy to his site without owning hosting and the platform automatically does all this The second problem: There is another feature that I have added, which is that the platform allows the user to build his own application But it only stops when you build apk for this app It works fine localy but I don't know how it will be on the server i build the apk by let python use the command line to build an apk *Note: I am using digitalocean I hope I made it clear -
sorting messages with tag in django template
I'm receiving a list of messages, each message has a tag. It may be "info", "warning", "danger" and "spreadsheet". I need to display the first three first and then spreadsheet's but in collapsible if there are more than 3 of them. So for all messages BUT spreadsheet the template is: <div class="row banner"> <ul class="banner-message"> {% for message in messages %} <li{% if message.tags %} class="banner-message--{{ message.tags }}" {% else %} class="banner-message--info" {% endif %}> <div class="message-content"> <p>{{ message|safe }}</p> <span class="close">&times;</span></div> </li> {% endfor %} </ul> </div> For tags with "spreadsheet" tag the template is: <div class="row banner"> <ul class="banner-message"> {% for message in messages %} <li class="{% if forloop.counter >= 3 %}collapsible_content{% endif %} banner-message--info"> <div class='message-content'> <p>{{ message|safe }}</p> <span class="close">&times;</span> </div> </li> {% endfor %} {% if messages|length > 3 %} <button id="show_more" class="btn btn-secondary collapsible_button">Show all</button> {% endif %} </ul> </div> Where button is shown for spreadsheet messages if there are more then 3 of them and shows all of them on click. Problem is that I receive these messages in one array and I have no guarantee that they won't be all mixed up in different order. I need to sort them somehow with … -
Djangos multiuser table how to log in
I now have two user models, one for background users and one for regular users. Background users are associated with regular users. How do two users log in to Django without affecting each other models.py models.py class BemanUser(AbstractUser): mobile = models.CharField('手机号', max_length=255, unique=True) class consumer(models.Model) account = models.CharField(max_length=255) name = models.CharField(max_length=255) password = models.CharField(max_length=255) mobile = models.CharField(max_length=255) email = models.CharField(max_length=255) How do I get both tables to log in? Thanks -
Django session cookie is changed to "" and expiration date of 1970
I have a problem with the cookies of a session logged into a web with Django. The session is started correctly and when I send request with the session cookie, the server response overwrites the session cookie with "" and sets the expiration date to January 1, 1970. This is something that happens completely randomly. I have checked the database and the session is stored. If I change the cookie that it gives me for the one that the login should have, it is done correctly. Does anyone know what could be happening? Thank you very much in advance. -
Axios to django-backend post image fail
I'm using react frontend to communicate with Django backend through axios. For some reason, I can't post form that include image. I tested my django backend through Postman and it works well. The backend shows code 200 on the terminal as success without saving data and the frontend doesn't through error the form can post successfully if I excluded the image. Please check my code below ; form.js file import React, { useState } from 'react'; import { Helmet } from 'react-helmet'; import axios from 'axios'; import { connect } from 'react-redux'; import { setAlert } from '../actions/alert'; import './ApplicationForm.css'; import { useNavigate } from 'react-router-dom'; import ExpandLessIcon from '@mui/icons-material/ExpandLess'; import ExpandMoreIcon from '@mui/icons-material/ExpandMore'; import { IconButton } from '@mui/material'; function ApplicationForm({ setAlert }) { const [show, setShow] = useState (false); const navigate=useNavigate(); const [formData, setFormData] = useState({ pasport_number: '', first_name: '', last_name: '', passport_photo: '' }); const { pasport_number, first_name, last_name, passport_photo } = formData; const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value }); console.log (formData) const onSubmit = e => { e.preventDefault(); const config = { headers: { 'Content-Type': 'application/json' } }; axios.post(`${process.env.REACT_APP_API_URL}/api/application-form/`, { pasport_number, first_name, last_name, passport_photo }, config) .then(_res => { navigate('/'); setAlert('Application Submitted Successfully', … -
Django can't Login
I can't Login to the system. Please help me. I have default User model in admin panel. Registration works fine but can't login to the homepage. Please debug it Views.py file: def loginpage(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, "Wrong username or password") return render(request,'loginpage.html') else: return render(request,'loginpage.html') Register views here: def register(request): if request.method == "POST": fname = request.POST['fname'] lname = request.POST['lname'] username = request.POST['username'] id = request.POST['id'] email = request.POST['email'] password = request.POST['password'] if User.objects.filter(username = username).exists(): messages.error(request, "Username already exists") return redirect('/') if User.objects.filter(email = email).exists(): messages.error(request, "Email already exists") return redirect('/') if not request.POST.get('email').endswith('@northsouth.edu'): messages.error(request, "Enter valid NSU Email") return redirect('/') else: user = User.objects.create(first_name=fname, last_name=lname, username = username, id=id, email=email, password=password) user.save() if user is not None: return redirect('register') reg = request.POST.get('username') messages.info(request, 'Account created for - Mr. ' + reg) return redirect('/') else: return render (request, 'registration.html') -
Django: Access context data in POST and GET
I am very new to Django and I cannot work out how to access context data within a POST request so I don't have to repeat myself. I believe that POST runs before get_context_data, but again unsure of what exactly to do here. The page displays some data using a default of 30 days. Then on the page there is a form to override that value, which is passed back to the POST method to then re-render the page. Example of page. views.py model = Producer template_name = 'producer_detail3.html' def get_queryset(self, **kwargs): #-date_check means to descending order based on that column return Producer.objects.filter(owner_name__exact=self.kwargs['pk'],metasnapshot_date=date(1980, 1, 1)) # Update context with more information def get_context_data(self, **kwargs): # Call the base implementation first to get the context context = super().get_context_data(**kwargs) # Cannot update context here as you are accessing existing producer object context data. # Create any data and add it to the context how_many_days = self.kwargs['days'] # get DAYS from URL. KWARGS are passed in from the get request context['day_filter'] = reverse('results:producer_detail', args=[self.kwargs['pk'], '300']) context['results'] = Results.objects.all().filter(owner_name__exact=self.kwargs['pk']).order_by('-date_check') context['chains_json_count'] = Results.objects.filter(owner_name__exact=self.kwargs['pk'],chains_json=True,date_check__gte=datetime.now()-timedelta(days=how_many_days)).count() return context def post(self, request, **kwargs): day_filter = int(request.POST.get('day_filter')) producer = Producer.objects.get(owner_name__exact=kwargs['pk'],metasnapshot_date=date(1980, 1, 1)) # Using reverse we create a URL to … -
How to add a rich text field in django?
how do i add a rich text field in django that would have to the option to add a Code Sample just like stack overflow text editor -
Getting 405 http error in POST on Django, the is problem in the urls?
Getting 405 status after using POST method in this django aplication #urls """Configuracoes de URL dos Resultados das Buscas https://docs.djangoproject.com/en/3.1/topics/http/urls/ """ from django.conf.urls import url from django.urls import path from . views import BuscaHorarios, AgendaHorario app_name = "agendamento" urlpatterns = [ url(r'^(?P<prestadorservicosid>[0-9]+)(?:/(?P<unidadeid>[0-9]+))/$', AgendaHorario.as_view(), name='horarios', ), url('/', AgendaHorario.as_view(), name="agenda_horario"), ] I think the problem occurs over here, but i'm not sure ##forms from django.forms import Form, CharField, EmailField, EmailInput, TextInput class AgendaHorarioForm(Form): nome_paciente = CharField(required=True, widget=TextInput( attrs={'placeholder': 'Digite seu nome completo', 'class': 'form-control', 'label_tag': 'Nome do paciente'})) email_paciente = EmailField(widget=EmailInput(attrs={'placeholder': 'Digite seu e-mail', 'class': 'form-control', 'label_tag': 'E-mail'})) telefone_paciente = CharField(required=True, widget=TextInput( attrs={'placeholder': 'Digite seu telefone com DDD', 'data-mask': '(00) 00000-0000', 'class': 'form-control', 'label_tag': 'Telefone com DDD'})) views class AgendaHorario(View): form_class_agenda = AgendaHorarioForm paciente = {} prestadorunidade = None prestadorservicos = None servicoregioes = None agenda_service = None horario_marcado = None def get_context_data(self, **kwargs): print('a') context = super().get_context_data(**kwargs) context['prestadorunidade'] = self.prestadorunidade context['prestadorservicos'] = self.prestadorservicos context['horario_marcado'] = self.horario_marcado context['paciente'] = self.paciente print('a') return context def post(self, *args, **kwargs): print('b') if self.request.is_ajax and self.request.method == "POST": form = self.form_class_agenda(self.request.POST) if form.is_valid(): post_data = form.cleaned_data self.paciente['nome'] = post_data['nome_paciente'] self.paciente['email'] = post_data['email_paciente'] self.paciente['telefone'] = post_data['telefone_paciente'] lista_unidades = list(cache.get('PrestadorUnidades', PrestadorUnidades.objects.values())) unidadeid = int(self.request.POST.get('prestadorunidadeid')) self.prestadorunidade = [item for … -
django admin, instance save issue
On django admin (list or change view), I would like to do the following: When somes fields are checked, the instance of the model could not be modified anymore. I tried to override model save: if self.is_prepared is False: if self.A and self.B: self.is_prepared = True super(MyModel, self).save(*args, **kwargs) But in the admin page (list or change view), on a 'is_prepared == True' instance I could still change all field of the instance. Seems like the admin is not using the model save. My admin looks like this: form = MyForm def save_model(self, request, obj, form, change): """ Force form to use model save """ if obj.is_prepared is False: obj.save() -
Second Order SQL Injection
def find_or_create_bp(bp_metadata): """ Returns a BusinessProcess, creating a new one if not found. """ bp_id = bp_metadata['id'] bp_name = bp_metadata['name'] bp_matches = BusinessProcess.objects.filter( bp_id=bp_id, bp_name=bp_name ).order_by('-id') if bp_matches: bp = bp_matches[0] else: bp = BusinessProcess( bp_id=bp_id, bp_name=bp_name ) bp.save() print("BusinessProcess created: " + bp_name) return bp Method find_or_create_bp at line 42 of project/api/src/monitoring_backend/monitoring_app/management/commands/migrate_watchitemconfigs.py gets database data from the filter element. This element’s value then flows through the code without being properly sanitized or validated, and is eventually used in a database query in method find_or_create_step at line 64 of project/api/src/monitoring_backend/monitoring_app/management/commands/migrate_watchitemconfigs.py. This may enable an Second-Order SQL Injection attack. -
Django reload - ajax GET after POST does not get latest database model instances
This question has been posted in different ways already but I can't get it to work.. I don't use AJAX yet in my script but I should use it as my database update is not visible in my application. Only when I restart the application, I can see the change. Can someone help me? I currently have this: .html {% block content %} <form id="post-setting-form" class="card" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="card-body"> <h3 class="card-title">Update Mail Settings</h3> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label class="form-label">Send Emails:</label> <p></p> <input type="radio" name="update_type" value="manual" {% if view.manualSetting %}checked {%endif%}> Manual {% if view.manualSetting is 1 %} ( Current setting ) {% else %} {% endif %}</input> <p></p> <input type="radio" name="update_type" value="auto" {% if view.autoSetting %}checked {%endif%}> Automated {% if view.autoSetting is 1 %} ( Current setting ) {% else %} {% endif %}</input> <p></p> <button type="submit" class="btn btn-primary">Update</button> </div> </div> </div> </div> </form> {% endblock %} .views class AutoSendView(generic.TemplateView): template_name = 'core/mailbox/autoSendMail.html' context_object_name = 'autosend' extra_context = {"mailbox_page": "active"} model = AutoSendMail.objects.get(pk=1) model.save() model.reload model.refresh_from_db() autoSetting = int(model.auto == True) manualSetting = int(model.manual == True) def post(self, request, *args, **kwargs): id_ = self.kwargs.get("pk") logger.info("testestest") update_type = self.request.POST.get('update_type') logger.info(update_type) if update_type == 'manual': … -
The Django test client redirects to the login page with a logged-in superuser
I am trying to connect a superuser to the Django test client, and then access a page in the Django administration interface with a GET method. However, I get a redirect to the login page, even though the superuser is properly logged in. Here is my code: def test(self) -> None: client = Client() user = User.objects.create(username='user', is_superuser=True) client.force_login(user) response = client.get(f'/admin/management/establishment/', follow=True) print("Redirect chain\t", response.redirect_chain) print("Request user\t", response.wsgi_request.user) print("Is superuser\t", response.wsgi_request.user.is_superuser) Here is the output: Redirect chain [('/admin/login/?next=/admin/management/establishment/', 302)] Request user user Is superuser True Do you know why I have this redirection and how I can avoid it? -
Updating postgres database by psql instead of django migrate-command and pg_catalog
I have a django server running in such production environment that cannot be copied to any test server as such (somebody must have changed the virtual environment manually since pip refuses to install the used versions as incompatible). However I should change the postgres database structure. I'm not sure if the django migration commands (python manage.py makemigrations & python manage.py migrate) will pass, thus I'm planning to prepare for running psql-commands instead, if needed. So I compared to sql-dumps (taken by pg_dump on test server) before and after migration command to obtain the needed psql-commands and detected that also an ineternal table pg_catalog had changed as below: < SELECT pg_catalog.setval('public.django_migrations_id_seq', 29, true); --- > SELECT pg_catalog.setval('public.django_migrations_id_seq', 32, true); What can be the meaning of this pg_catalog and does it make sense in trying to updata it by psql-command ? On the other hand, if the migrate-commands do not work and I need to run them with --fake qualifier, can I trust the result will still be what I wanted ? -
i want to update paypal subscription (classic mathod i guess)
i have implement subscription using this link : https://overiq.com/django-paypal-integration-with-django-paypal/ this mathod is using ipn now i want to update the exising subscription, i show the paypal documentation but this is the another mathod to integrate paypal, and i had integrate paypal only using email, i think this is the classic subscription using paypal, and i can not found any official docs for subscription for paypal with this mathod, so how to update subscription with this mathod? also if anyone find any official docs please share thanks in advance !! -
how do i configure os path directory
I keep getting the following response when I querry to get static files: (.venv) PS C:\Users\USER\Documents\estar app> python anchor/manage.py collectstatic --no-input STATIC_ROOT = os.path.join(BASE_DIR, "<where all static files will be collected>") NameError: name 'os' is not defined Who can help out, please? I tried: python manage.py collectstatic --no-input -
Django multiple user login on multiple tab session issue
I have an issue with my Django app. If I use to login to the app with different users from different browser tab , then it is loging out the first user. I am using django file bases session, which create session file. But if I login with a second user the first session file is over writing . So my question is , is there a way to set the session file name to a unique name for each login using any middleware or other options in django. May be and extended class using SessionMidleware I am sort of lost, I tried different solutions , but none of this works. If any one know how to implement it , please guide me, Thanks for any help. -
Django Foreign Key error ......What should I do now?
```In [1]: import json In [2]: from Bugijugi. models import Post In [3]: with open('posts.json') as f: ...: posts_json = json.load(f) ...: In [4]: for post in posts_json: ...: post = Post(title=post['title'], content=post['content'], author_id=post['us ...: er_id']) ...: post.save() ...: ``` --------------------------------------------------------------------------- IntegrityError Traceback (most recent call last) File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\utils.py:97, in DatabaseErrorWrapper.call..inner(*args, **kwargs) 96 with self: ---> 97 return func(*args, **kwargs) IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: IntegrityError Traceback (most recent call last) Input In [4], in <cell line: 1>() 1 for post in posts_json: 2 post = Post(title=post['title'], content=post['content'], author_id=post['user_id']) ----> 3 post.save() File F:\IMPORTANT\GAME\vrsty life\CSE 347\Project\Sample\Bugijugi\models.py:27, in Post.save(self) 26 def save(self): ---> 27 return super().save() File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py:743, in Model.save(self, force_insert, force_update, using, update_fields) 740 if loaded_fields: 741 update_fields = frozenset(loaded_fields) --> 743 self.save_base(using=using, force_insert=force_insert, 744 force_update=force_update, update_fields=update_fields) File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py:780, in Model.save_base(self, raw, force_insert, force_update, using, update_fields) 778 if not raw: 779 parent_inserted = self._save_parents(cls, using, update_fields) --> 780 updated = self._save_table( 781 raw, cls, force_insert or parent_inserted, 782 force_update, using, update_fields, 783 ) 784 # Store the database on which the object was saved 785 self._state.db = using File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py:885, in Model._save_table(self, raw, cls, force_insert, force_update, using, update_fields) 882 … -
expected str, bytes or os.PathLike object, not InMemoryUploadedFile when uploading a picture
My project is a django website to predict if a person has brain Tumour or not. def tumor_pred(imageTumor): model = load_model("bestmodel2.h5") path = imageTumor img = load_img(path, target_size=(224, 224)) input_arr = img_to_array(img)/225 input_arr.shape input_arr = np.expand_dims(input_arr, axis=0) pred = model.predict_classes(input_arr)[0][0] if pred == 0: return 'no' elif pred == 1: return 'yes' else: return 'error' mriReport function def mriReport(request, aid): appoitment_details = Appoitment.objects.all().filter(id=aid) if request.method == "POST": Appoitment_ID = request.POST['SessionID'] Patient_ID = request.POST['PatientID'] PatientName = request.POST['PatientName'] PatientEmail = request.POST['PatientEmail'] Date = request.POST['Date'] imageTumor = request.FILES['imageTumor'] result = tumor_pred(imageTumor) try: MRIReport.objects.create(Appoitment_ID_id=Appoitment_ID, Patient_ID_id=Patient_ID, PatientName=PatientName, Date=Date, PatientEmail=PatientEmail, image=imageTumor, result=result) return redirect('labWorkshop') except Exception as e: raise e return render(request, 'MRIReport.html', {'appoitment_details': appoitment_details}) I get the error expected str, bytes or os.PathLike object, not InMemoryUploadedFile when i try to run my machine learning model I have seen other stackoverflow solutions where it is reported that it is trying to open an already opened file. Therefore i tried by to removing: img = load_img(path, target_size=(224, 224)) New function def tumor_pred(imageTumor): model = load_model("bestmodel2.h5") img = imageTumor # img = load_img(path, target_size=(224, 224)) input_arr = img_to_array(img)/225 input_arr.shape input_arr = np.expand_dims(input_arr, axis=0) pred = model.predict_classes(input_arr)[0][0] if pred == 0: return 'no' elif pred == 1: return 'yes' … -
Django 4.0.1 cannot import name 'SortedDict' from 'django.utils.datastructures'
My project isn't working! I need help! I'm just fill in the forms. And run the project. Error: Traceback (most recent call last): File "/home/pc/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/pc/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pc/Documents/Projects/Django/Travel/Web/views.py", line 92, in sign_in user = auth.authenticate(username=username, password=password) File "/home/pc/.local/lib/python3.10/site-packages/django/views/decorators/debug.py", line 42, in sensitive_variables_wrapper return func(*func_args, **func_kwargs) File "/home/pc/.local/lib/python3.10/site-packages/django/contrib/auth/__init__.py", line 77, in authenticate user = backend.authenticate(request, **credentials) File "/home/pc/.local/lib/python3.10/site-packages/django/contrib/auth/backends.py", line 48, in authenticate if user.check_password(password) and self.user_can_authenticate(user): File "/home/pc/.local/lib/python3.10/site-packages/django/contrib/auth/base_user.py", line 115, in check_password return check_password(raw_password, self.password, setter) File "/home/pc/.local/lib/python3.10/site-packages/django/contrib/auth/hashers.py", line 47, in check_password preferred = get_hasher(preferred) File "/home/pc/.local/lib/python3.10/site-packages/django/contrib/auth/hashers.py", line 129, in get_hasher return get_hashers()[0] File "/home/pc/.local/lib/python3.10/site-packages/django/contrib/auth/hashers.py", line 96, in get_hashers hasher_cls = import_string(hasher_path) File "/home/pc/.local/lib/python3.10/site-packages/django/utils/module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "/home/pc/.local/lib/python3.10/site-packages/django/utils/module_loading.py", line 15, in cached_import 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/pc/.local/lib/python3.10/site-packages/django_scrypt/hashers.py", line 2, in <module> from django.utils.datastructures import SortedDict ImportError: cannot import name … -
Django create get api from different table return
I am trying to use the def list function Django from these two which I have tables Batch and BatchYield the table of Batch look like batch_id | batch_status | `````````|```````````````| 11 | completed | and the table of BatchYield look like id | grade_a_produce | grade_b_produce | grade_c_rejection | harvest_date | batch_id | ```|`````````````````|`````````````````|```````````````````|``````````````|``````````| 23 | 100 | 120 | 212 | 22-02-12 | 11 | 25 | 110 | 122 | 242 | 21-01-14 | 11 | So I wrote a def list function in Django in which I have joined these two table with this code def list(self, request, *args, **kwargs): try: for data in request.data: batch_id = data.get('batch_id') all_batchyield = BatchYield.objects.filter(batch_id=batch_id).values('grade_a_produce', 'id', 'grade_b_produce', 'grade_c_rejection', 'harvest_date', 'batch_id') if all_batchyield.count == 0: return Response({"response": "Data not Found"}, status=status.HTTP_200_OK) all_batchyield_df = pd.DataFrame(all_batchyield) all_batchyield_df = all_batchyield_df.replace({np.nan: None}) all_completed_batchs = Batch.objects.filter(id=batch_id).values('batch_status', 'id') completed_batch_df = pd.DataFrame(all_completed_batchs) completed_batch_df = completed_batch_df.replace({np.nan: None}) completed_batch_df.rename(columns={'id': 'batch_id'}, inplace=True) final = pd.merge(completed_batch_df, all_batchyield_df, on='batch_id') final = final.drop('batch_id', axis=1) except Exception as e: return Response({"response": str(e)}, status=status.HTTP_400_BAD_REQUEST) return Response(final.to_dict('record'), status=status.HTTP_200_OK) From this code I got the and output which look like this [ { "batch_status": "completed", "grade_a_produce": 100.0, "id": 23, "grade_b_produce": 120.0, "grade_c_rejection": 212.0, "harvest_date": "2022-02-12T00:00:00Z" }, { "batch_status": … -
Pre populating a django form using Initial not working
I am trying to save a modelform by prepopulating 'template_name' field . As per django documentation and other threads it is clear that initial parameter should work but i just can't make it work for my code. I am getting the error that template_name field is empty. Any help on what am I missing and any other approach towards this will be great. Here is the code models.py class TemplateNameModel(models.Model): "Model to add the template name" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) tna_template_name = models.CharField(verbose_name="Template name",max_length = 128, unique = True, null = False, blank = False, help_text="please enter name of the new tna template") description = models.CharField(verbose_name="template description", max_length = 256, null = True, blank = True, help_text ="Please enter the description(optional)") created_by = models.TextField(verbose_name="Template created by", max_length= 128, null = False, blank = False,help_text ="Please enter the name of creator") date_created = models.DateTimeField(auto_created= True, null = True, blank = True) is_active = models.BooleanField(verbose_name="Template status",null = False , blank= False) def __str__(self): return self.tna_template_name class TnaTemplateModel(models.Model): id = models.AutoField(primary_key=True, editable=False) template_name = models.ForeignKey(TemplateNameModel, verbose_name="template name", null=False, blank=False, on_delete=models.CASCADE, help_text="Select the template") process_name = models.ForeignKey(ProcessModel, verbose_name="process name", null=False, blank=False, on_delete=models.CASCADE, help_text="Select the process") sequence = models.IntegerField(verbose_name="Process Sequence",null = False,blank = False) … -
add filter_horizontal into a model form in django
I am trying to add filter_horizontal like in admin for the "genre" of a book model form and I am using widgets.FilteredSelectMultiple but the result was this not this. How can I fix this? This is my code for bookform class BookForm(forms.ModelForm): publisher = forms.ModelChoiceField(queryset=Publisher.objects.all()) genre = forms.ModelMultipleChoiceField( widget=widgets.FilteredSelectMultiple('Genre', False), queryset=Genre.objects.all(), ) class Meta: model = Book fields = ['language', 'number_of_pages', 'summary', 'isbn', 'publisher', 'genre'] -
Redis not working. __init__() got an unexpected keyword argument 'username'
i am trying to run the celery -A project worker -l info. But each time it returns an error like init got unexpected error. Kindly Help. Thanks in advance. -
JavaScript not functioning after htmx get/post request swapped
I'm building a Django project and trying to get and post data using htmx and everything works, which means I can get and post data there is no problem with that, but the problem is after data is swapped the bootstrap dropdown or tooltips or other elements that need some javascript to function is not working, I think the error is because after htmx swapped there is always new data added or replaced to the DOM, so the new data is no longer supported to any script. so how can I handle this?