Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save div elements in form post
I have a form currently with a text area. However, I want it to have rich-text formatting (bold, bullet points etc..) and for that, I have found Quill, which is amazing. I'm not sure how to get the contents of div id=editor and save that to the Django function, because it won't be part of the post, will it? <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet"> <!-- Create the editor container --> <div id="editor"> <p>Hello World!</p> <p>Some initial <strong>bold</strong> text</p> <p><br></p> </div> <!-- Include the Quill library --> <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script> <!-- Initialize Quill editor --> <script> var quill = new Quill('#editor', { theme: 'snow' }); </script> -
Redirect the user to the previous page which uses a Primary Key (PK)
I'm currently trying to create a form that, upon success, redirects the user to the previous page (which is using a PK key). Example of previous page : http://127.0.0.1:8000/object/update/8/ (1) What I tried: def get_success_url(self, **kwargs): return reverse_lazy('task_update:update', kwargs={'id': self.object.id}) (2) And currently I'm trying to load my form with the same pk than the precedent form (he don't need pk, example : http://127.0.0.1:8000/tag/create/8/) And then use that PK in the URL for load the precedent page like that : def get_success_url(self, **kwargs): return reverse_lazy('task_create', self.kwargs.get('pk')) but it generates an error : The included URLconf '8' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. The goal: Globally, users start at "http://127.0.0.1:8000/object/update/8/", then they press a button which redirects them to a new page to create a tag, and then they get redirected back to the first page. -
Python package for API development, testing and consume/invoke other APIs
I have been using Flask for API development for a while and requests module for test automation of APIs. I found lot of materials over internet but I am still bit confused about some of these fundamentals. If i need to develop API shall I use 'requests' module in python or that is only meant to use it for api testing/automation or just to call other apis ? is it always better to use frameworks like flask,fastapi, or Django to develop API in python platform ? and for example if I develop a API in flask and also I need a call another API within Flask, should I use the functionality of Flask to call external APIs or should I use 'requests' library only ? so some one who has well experienced all these frameworks suggest please .. thanks -
Validation message "Please fill out this field" displaying with <form novalidate>
I'm attempting to create a form with an <input type="text" /> field where client side validation is disabled with the novalidate keyword. Yet when the Enter key is pressed the Please fill out this field message is still displayed when no input value is provided. When a value is provided, the message is not displayed. How can the validation message be disabled for simply pressing Enter in the input box with no value? class UserSearchForm(Form): search = CharField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['search'].widget.attrs.update({ "placeholder": "Filter by user", "autocomplete": False, "required": False, }) <form id="api_user_search_form" novalidate> {% for field in form %} {{ field }} {% endfor %} </form> let form = document.querySelector("#api_user_search_form"); form.addEventListener("submit", function(event) { event.preventDefault() }) -
I am beginner to programming .I have started learning python and django. I want my dropdown to get data from my dataset
I'm trying to build a machine learning algorithm and then deploy it to my website using django.So here comes the problem I want drop downs on my forms and.Im using the select tag on html while creating my dropdown but it is very hectic to give each value/option individually.Is there anyway i could get my values from dataset in my dropdowns so i dont have to go through above process. I imported my model and done it successfully using streamlit.I am expecting to do same with my website that m building in django.I want those values from my dataset that i have loaded in my views.py to be diplay on my drop down. kindly help in this regard.[enter image description here](https://i.stack.imgur.com/Z6vmZ.png) -
How to get iteration number of outer loop jinja
I need to get the iteration number of the outer loop in jija templates, for example: {% for el in data %} {% if el == '' %} Nothing found. {% else %} Iteration {# here I need to get iteration number #}. Found {{ el }} {% endif %} {% endfor %} I tryed to use {% loop.index %} but I get this error: jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'loop'. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'. -
django.db.utils.OperationalError: (2013, 'Lost connection to MySQL server during query')
I create a django app to shared hosting. Everything is good but when i came to createsuperuser i see this problem... I made lots of things, i increased connect timeout and read timeout but nothing changed. How can i solve this? i made connect_timeout=100000, i made read_timeout=120, i tried to shell for create super user, i wrote username, no error, i wrote email, no error, i wrote pass and i got this error.... -
Problems with changing the value of useState when running components repeatedly through the response map
I want to repeat the components through the map and display the information that received the aixos on each tag, but when I checked, only the last value of the repetition is being posted. When I printed it out as console, the value of searchHospitalAdd, searchHospitalName didn't change immediately, and it seems that only the last value is included Why is it like this? Am I using it wrong? Or is the problem with the time to reply after sending the post request? I don't think this is right, but I don't know I mean the SetPendPatientView tag! We're developing React and Django drf I want you to give me a solution const Hospitals = () => { const state = useLocation().state; const [hospitals, setHospitals] = useState([]); const [ScrollActive, setScrollActive] = useState(false); const [hospitalInfoModalOn, setHospitalInfoModalOn] = useState(false); const [hospitalInfo, setHospitalInfo] = useState([]); const [wait_count, setWait_count] = useState(''); const [searchHospitalAdd, setSearchHospitalAdd] = useState(''); const [searchHospitalName, setSearchHospitalName] = useState(''); useEffect(() => { axios .post('http://localhost:8000/patient/hospital_srch/', { hospitalDep: state.hospital_dep }) .then(function (response) { const hospital = JSON.parse(response.data); setHospitals(hospital); console.log(state.hospital_dep); console.log(hospital); }) .catch(function (error) { alert(error); }); return () => {}; }, [state]); useEffect(() => { axios .post( 'http://localhost:8000/reservation/wait_search/', { hospital_address: searchHospitalAdd, hospital_name: searchHospitalName }, … -
Django migrations are faked after reverse
I am working on different tasks in the project, so i have to switch between git branches and do reverse migrations. But after reversing the migrations, when re-building the project on the same branch, these migrations are launched as faked and are not applied. I have to remove them from the django migrations table and run them again with the migrate command. Please tell me what is this effect and if it can be somehow avoided. Didn't find any information about this. I reverse migrations with the command django-admin migrate <app_name> <number_migration> -
How to add multiple models to a single listview?
i need to be able to display information from multiple models in a single listview but haven't a clue how to go about doing this any help would be very helpful... here is my code for me views.py: from django.shortcuts import render, redirect from django.views.generic import ListView, DetailView from . models import Post, Task from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator @method_decorator(login_required, name='dispatch') class HomeView(ListView): template_name = 'home.html' model = Post @method_decorator(login_required, name='dispatch') class Task(ListView): model = Task template_name = 'tasks.html' here is my code for me models.py: from django.db import models from django.contrib.auth.models import User class Post(models.Model): type = models.CharField(max_length=255) title = models.CharField(max_length=255) link = models.CharField(max_length=255) auther = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() def __str__(self): return self.title + ' | ' + str(self.auther) class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) urgency = models.CharField(max_length=255) title = models.CharField(max_length=255) description = models.TextField() def __str__(self,): return str(self.user.username) + ' | ' + 'Tasks' here is my html: {% for task in object_list %} <a href="#" class="list-group-item list-group-item-action bg-transparent border border-secondary"> <h class="mb-1">{{task.title}}</h> <p class="mb-1">{{task.description}}</p> <a class="mb-1">{{task.urgency}}</a> </a> {% endfor %} {% for post in object_list %} <span> <div class="card text-secondary-emphasis border border-secondary mb-4" style="background-color: #0d1117;"> <div class="card-header border border-secondary">{{post.type}}</div> <div class="card-body"> <h5 class="card-title"style="color: … -
Is there any python specific solution for conversion of an excel file to its respective pdf?
I have been trying to convert an excel file to its pdf form. But the django server is getting hanged. I read about this issue with flask server also https://forum.aspose.com/t/python-flask-web-server-hang-at-aspose-cells/232218/6 As of now have used aspose-cells python library which has dependency upon Java. It works fine inside console but not with Django web server (as the server is getting hanged indefinitely) import asposecells import jpype jpype.startJVM() from asposecells.api import Workbook workbook = Workbook("input.xlsx") workbook.save("output.pdf") jpype.shutdownJVM() I am trying it out on mac M2. -
django filter is not working Plz solve this as soon as posible
i have two same code in Django views.py file shown in pis This is code in my Views.py file and this is Output of my code but Queryset is not working enter image description here plz help me to solve this solve plz, i had try many time on this code -
Filtering queryset for a formset doesn't work
I'm trying to display a formset with a ChoiceField and I want to filter this ChoiceField queryset. But it just doesn't work. So I've tried this def create_formation_template(request, pk): formation = Formation.objects.get(id=pk) def_formation_template = inlineformset_factory(Formation, FormationTemplate, fields=('position',), extra=formation.defender_number) defenders_queryset = FormationTemplate.objects.filter(position__type='Defender') def_formset = def_formation_template(queryset=defenders_queryset, instance=formation) return render(request, 'formation_template_form.html', {'def_formset': def_formset} When I display the formset on a template, there are no errors but it does not filter the ChoiceField queryset at all -
unique_together not working as expected in view
I added unique_together in the Django model. It works fine in the Django admin panel but doesn't work when I create model instances in a for loop in the Django view. My Model: class Parent(models.Model): attribute_1 = models.CharField(max_length=100) attribute_2 = models.IntegerField() attribute_3 = models.CharField(max_length=100) class Meta: unique_together = (("attribute_1", "attribute_2"),) View: class ParentView(View): template_name = "app/index.html" def get(self, *args, **kwargs): for i in range(10): Parent.objects.create( attribute_1=f"value-{i}", attribute_2=i, attribute_3=f"value-{i}", ) return render(self.request, self.template_name) Problem: When I open this view, it creates the entries in the Parent model. when I refresh the page, I expect a unique value error but it doesn't give any error at all and creates entries again. No matter how much time I reload the page, it creates duplicate entries without giving an error. What I tried? I tried to change my DB from sqlite3 to PostgreSQL but it didn't work. I tried to switch attributes but no luck. It works perfectly fine on the admin panel. -
How to convert text file (raw data) data into excel in pandas or python?
** How to conver text file data into excel arrange into header and values in excel ? **text.file data [GDIP] Host address - 200.00.99.22 Host address (decimal) - 122345560 Host address (hex) - B00009 Net address - 19.0.0.8 Networker - 2.2.2.2.2 Host address - 500.00.00.00 Host address (decimal) - 987654 Host address (hex) - D00008 Net address - 197.0.0.99.00 Networker - 3.3.3.3.3 Output Excel data Host address Host address (decimal) Host address (hex) Net address Networker 200.00.99.22 122345560 B00009 19.0.0.8 2.2.2.2.2 500.00.00.00 987654 D00008 197.0.0.99.00 3.3.3.3.3 -
Django's Generic UpdateView: How to pass value to the hidden form field?
I am trying to combine Django's generic UpdateView and hidden input field. My purpose is to track whether a post was edited after it was created or not. Hidden field name is "updated". views.py: class PostUpdateView(UpdateView): model = Post template_name = 'journal/post_update_form.html' form_class = PostUpdateForm success_url = reverse_lazy('my_posts') models.py: class Post(models.Model): title = models.CharField(max_length=500) text = models.TextField(max_length=2000, null=True, blank=True) owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) #storing the link to media files in CharField image = models.CharField(max_length=500, null=True, blank=True) audio = models.CharField(max_length=500, null=True, blank=True) video = models.CharField(max_length=500, null=True, blank=True) rubric = models.CharField(max_length=100, default="No rubric", choices=RUBRIC_CHOICES) private = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) updated = models.CharField(max_length=10, default="False") forms.py: from django import forms from .models import Post class PostUpdateForm(forms.ModelForm): class Meta: model = Post fields = ["title", "text", "image", "audio", "video", "rubric", "private", "updated"] widgets = {'updated': forms.HiddenInput(attrs={'value':"updated"})} relevant part of update form template: <form action="" method="POST"> {% csrf_token %} {% for field in form %} {% if field != form.rubric and field != form.private %} <div class="mb-3 form-group"> <label for="{{field.name}}" class="form-label">{{field.label}}</label> {{field.errors}} {% if field == form.text %} <textarea type="text" class="form-control" id="{{field.name}}" name="{{field.name}}">{{field.value|default_if_none:"" }}</textarea> {% elif field == form.updated %} <input type="hidden" id="{{field.name}}" name="{{field.name}}" value="updated"> {% else %} <input type="text" … -
How to authenticate user in Django
I am trying to log in a user in Django and redirect them back to the homepage with an if statement in the navbar that will display logout if the user is logged in or authenticated and register and login links if they're not authenticated. However, when I click login it goes back to the homepage but none of the expected changes are visible, if you see my views.py file the view is supposed to print a message depending on the action taken but these messages are only displayed on the Django admin page. What am I not doing? This is the login form: <form action="" method="POST"> {% csrf_token %} <!-- Email input --> <div class="form-outline mb-4"> <input type="email" id="user-email" class="form-control" name="login-email" placeholder="Enter email"/> <label class="form-label" for="user-email">Email address</label> </div> <!-- Password input --> <div class="form-outline mb-4"> <input type="password" id="user-password" class="form-control" name="login-password" placeholder="Enter password"/> <label class="form-label" for="form2Example2">Password</label> </div> <!-- 2 column grid layout for inline styling --> <div class="row mb-4"> <div class="col d-flex justify-content-center"> <!-- Checkbox --> <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="form2Example31" checked /> <label class="form-check-label" for="form2Example31"> Remember me </label> </div> </div> <div class="col"> <!-- Simple link --> <a href="#!">Forgot password?</a> </div> </div> <!-- Submit button --> <button type="submit" … -
django-admin startproject webproject . The system cannot find the file specified
When I tried following the instructions to create my Django project with these steps: Create the Django project In the VS Code Terminal where your virtual environment is activated, run the following command: django-admin startproject web_project . It didn't work. Ran in (venv): django-admin startproject webproject . Got: The system cannot find the file specified -
Django celery beat does seems to get triggered when on my EC2 instance
so this task runs completely fine when locally : @shared_task def test(): print('test') app.conf.beat_schedule = { 'my-task-every-1-minutes': { 'task': 'statistic_status.tasks.test', 'schedule': crontab(minute='*/1'), }, } when on my EC2 and i start the worker it shows my tasks correctly but when starting the beat the server looks like running fine but it does no get triggered. Locally everything works fine and on EC2 the only way I could triggered my tasks is from the python shell. Any help here ?? -
Django generate thumbnail with MoviePy, problem with Path
How to get the absolute path to a video, that works in development (Windows) and production (Ubuntu), ive tried almost anything, here is the closest i got to getting it right, I am trying to generate a thumbnail for a video when its posted ` from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent def generate_thumbnail(instance): filename = Path.joinpath(BASE_DIR, 'media/video_files') print(filename) thumbnail = VideoFileClip(str(filename)+instance.video.url) name = instance.video.url + '.png' time = random.randrange(60) thumbnail.save_frame('media/uploads/thumbnail' + name, t=time, withmask=True) instance.thumbnail = name ` It never gives me a good path, its ether with '/' or with ''. MoviePy error: the file C:\Users\User 1\Desktop\django\lumen\media\video_files/media/uploads/video_files/22/29/Elvis_-_If_I_Can_Dream_Official_Live_Performance_fcw0WKp.mp4 could not be found! Please check that you entered the correct path. -
Django product count per category
Have below models class TreatmentCategory(models.Model): name = models.CharField(max_length=255, unique=True) def __str__(self): return self.name class Treatment(models.Model): unique_id = models.UUIDField('Unique Record ID', default=uuid.uuid4, editable=False) name = models.CharField('Treatment Name', max_length=255, db_index=True, unique=True) category = models.ForeignKey(TreatmentCategory, on_delete=models.PROTECT) duration = models.PositiveSmallIntegerField('Treatment Duration (min)') price = models.DecimalField('Treatment Cost', max_digits=9, decimal_places=2) description = models.TextField(null=True, blank=True) active = models.BooleanField(default=True) def __str__(self): return self.name class Therapist(models.Model): day_options = [ ("Off Day", "Off Day"), ("On Leave", "On Leave"), ("On Duty", "On Duty"), ] unique_id = models.UUIDField('Unique Record ID', default=uuid.uuid4, editable=False) name = models.CharField('Therapist Name', max_length=255) contact = models.CharField('Phone Number', max_length=12, blank=True, null=True) day_status = models.CharField( 'Duty Status', max_length=255, choices=day_options, default='On Duty' ) status = models.BooleanField( 'Status of Therapist', default=True, ) treatments = models.ManyToManyField(Treatment, related_name='therapists') def __str__(self): return self.name Would like to output all therapists and a total count of treatments per category they have records i.e each therapist may have different treatments per category thus they wont have same number of treatments therapist1 | treatmentcategory1 (number of treatments) | treatmentcategory2 (number of treatments) | treatmentcategory3 (number of treatments) therapist2 | treatmentcategory1 (number of treatments) My current code as below, its displaying therapists however, instead of treatmentcategories, it showing treatments category = (TreatmentCategory.objects.filter(treatment__active=True) .prefetch_related('treatment_set') .annotate(treatment_count=Count('treatment__name')) ) queryset = (Therapist.objects.filter(status=True) .prefetch_related( Prefetch('mytreatments', … -
Django does not find the Urls.py in the app
these are my settings, where I've always worked. I've been working with Django for 3 months but I haven't had anything like that until now. my thoughts are by '' at the beginning of the urlspattern to make the home template the main template from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('inventory.urls')), # code urls.py in the app from . import views from django.urls import path urlpatterns = [ path('', views.home, name='home'), path('base/', views.BaseTemplateView.as_view(), name='base'), # Menu Item URLs path('menu/', views.MenuItemListView.as_view(), name='menu_item_list'), path('menu/<int:pk>/', views.MenuItemDetailView.as_view(), name='menu_item_detail'), #the View def home(request): return render(request, 'home.html') class BaseTemplateView(TemplateView): template_name = 'base.html' class MenuItemListView(ListView): model = MenuItem template_name = 'menu_item_list.html' context_object_name = 'menu_items' class MenuItemDetailView(DetailView): model = MenuItem template_name = 'menu_item_detail.html' # the setting for the template folder OOT_URLCONF = 'djangodelights.urls' TEMPLATE_DIR = os.path.join(BASE_DIR,"templates") TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], # Installed apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'inventory.apps.InventoryConfig', **I was expecting ,when a start the server e get the home.html template.no matter which path I enter manually, I always get the same message ** *Using the URLconf defined in … -
pass the value from form with autocomplete jquery to view in django
I made a form to send data to a view. The form input has a jquery autocomplete. <form method="get" action=""{% url 'ville_detail' %}""> <label for="villeselect">Product</label> <input type="text" name="id" id="villeselect"> <button type="submit">Go</button> </form> </div> <script> $(function () { $("#villeselect").autocomplete({ source: '{% url 'autorecherche' %}', minLength: 3 }); }); </script> the method in views.py "autorecherche" manages this form and the autocomplete def autorecherche(request): if 'term' in request.GET: qs = VilleFrance.objects.filter(name__istartswith=request.GET.get('term')) cible = list() for product in qs: cible.append(product.name) return JsonResponse(cible, safe=False) return render(request, 'ville/ville_recherche.html') how to pass the submit valueto this view. I tried but I can't find the solution class TestDetailView(DetailView): template_name = 'ville/ville_detail.html' model = Article def get_context_data(self, **kwargs): context = super(TestDetailView, self).get_context_data(**kwargs) my_id = self.kwargs['pk'] item = Article.objects.values_list(('nomVille'),flat=True).get(pk=my_id) context['item'] = item return context the url looks like this path('ville/<int:pk>/city_detail', VilleDetail.as_view(), name='ville_detail'), thank for any help. -
when i clicked on add to cart button it first check "is user login??" then execute jquery
when i clicked on Add to cart button , it first chek that user login or not if login then continue otherwise redirect to login page $('.divpr').on('click', 'button.cart' ,function () { var idstr = this.id.toString(); if (cart[idstr] != undefined) { console.log("exist"); cart[idstr][0] = cart[idstr][0] + 1; cart[idstr][4]=cart[idstr][4]+cart[idstr][3] localStorage.setItem('cart', JSON.stringify(cart)); } else { qty = 1; price = document.getElementById('price' + idstr).innerHTML; totalPrice=document.getElementById('price' + idstr).innerHTML; image = document.getElementById('img' + idstr).src; aname = document.getElementById('name' + idstr).innerHTML; console.log("not"); cart[idstr] = [qty, aname, image, parseInt(price),parseInt(totalPrice)]; } localStorage.setItem('cart', JSON.stringify(cart)); console.log(cart) }); it add item to cart even i am not login i want it redirect when i am not loggedin -
How do I register a custom user type in Django 4.1?
So, I am a beginner and I'm coding a django application that has a 3 user types in total but to make the code readable and understandable I'm just gonna assume we have 2 user types. One is a doctor and one is a patient. I've created this custom user so far: in models.py class User(AbstractUser): is_doc = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) objects = UserManager() manager.py class UserManager(BaseUserManager): def create_user(self, email, password=None): if email is None: raise TypeError('Users must have an email address.') user = self.model(email=self.normalize_email(email)) user.set_password(password) user.save() return user def create_patient(self, email, password): if password is None: raise TypeError('Must have a password') user = self.model(email=self.normalize_email(email)) user.set_password(password) user.is_patient = True user.save() def create_superuser(self, email, password): if password is None: raise TypeError('Superusers must have a password.') user = self.create_user(email, password) user.is_superuser = True user.is_staff = True user.save() return user Patient Model is as follows: class Patient(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=70) last_name = models.CharField(max_length=70) address = models.CharField(max_length=210) phone = models.CharField(max_length=15) email = models.EmailField(max_length=110) password = models.CharField(max_length=65) def __str__(self): return self.first_name + " " + self.last_name I have separate signups for patient and doctor and don't want a user type field in my form so I have all the detail …