Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display labels of ModelMultipleChoiceField
How to display the labels of the choices in a ModelMultipleChoiceField ? This is the form : class MakeAnAppointmentForm(forms.Form): time_slot = forms.ModelMultipleChoiceField(queryset = None, widget=forms.CheckboxSelectMultiple()) def __init__(self,*args,**kwargs): date = kwargs.pop('date') super().__init__(*args,**kwargs) self.fields['time_slot'].queryset = Appointment.objects.filter(date = date).values_list('time_slot', flat = True) self.fields['time_slot'].label = "date" But it displays this : And I want this : in accordance to this : TIMESLOT_CHOICES = (('0', '09:00 - 09:30'), ('1', '09:30 - 10:00'), ('2', '10:00 - 10:30'), ('3', '10:30 – 11:00')... How is this possible ? Thank you. -
Django annotate count unique user from 2 tables
Is it possible to do an annotate count on technically 2 different tables, but same FK? Example: queryset = ModelName.objects .annotate(mileage_emp_count=Count('mileageclaim__user',distinct=True)) .annotate(general_emp_count=Count('expenseclaim__user', distinct=True)) For instance using this, is User A has a mileage and an expense claim, they will appear in both queries. So I will have result of 2 if i add them together. What i need to do, is get a total of 1 unique user instead. Is it possible without a lot of extra checks? -
Django can't save parent id of child objects
I am tying to save parent id when the forms will be save but I am not understanding where I am doing mistake. I am using <input type="hidden" name="parent" id={{i.sno}}> for save parent id and I can see the id number if I inspect html from browser. models.py class Contact(MPTTModel): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True,related_name='contact_user') parent =TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='contact_parent') sno = models.AutoField(primary_key=True,) #my others fields.... forms.py class TicketForm(forms.ModelForm): class Meta: model = Contact fields = ['message','parent','sno','existing_customer','technical_service'] views.py def SupportPageView(request): if request.method == "POST": support_form = TicketForm(request.POST or None) if support_form.is_valid(): isinstance = support_form.save(commit=False) isinstance.user = request.user isinstance.name = request.user.first_name isinstance.email = request.user.email isinstance.save() name = request.user.first_name messages.add_message(request, messages.INFO, f'{name} Thanks for your message. We will get back to you very soon') return redirect('contact:support-ticket') else: support_form = TicketForm() user = request.user support_object = Contact.objects.filter(user=user) context = {"support_form":support_form,'support_object':support_object} return render(request,"contact/support.html",context) HTML {%for i in support_object%} <form method="POST"> {%csrf_token%} <textarea name="message" class="form-control" style="height: 150px;"></textarea><br> <input type="hidden" name="parent" id={{i.sno}}> <button type="submit" class="btn btn-info">Submit</button> </form> {%endfor%} my forms is saving as a parent but I want they will save as child. -
How can I show last 4 posts in django?
I try to show last 4 posts with Django by using Class-Based Views, but No data (post) shows on page. that's code: views.py : class PostList(ListView): model=Post paginate_by=10 context_object_name='all_posts' ordering=['-created_at'] latest=model.objects.order_by('-created_at')[:4] templates/post_list.html : {% for post in latest %} <div class="col-sm-12 col-md-6 col-lg-3" > <!-- cards--> <div class="card "> <img src="{{post.image.url}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{post.title}}</h5> <p class="card-text">{{post.content}}</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> <!-- ends cards--> </div> {% endfor %} my thanks -
Count every hit with django-hitcount
Is there a way to make Django hitcount module count every hit? Currently, it counts once for a single IP but I want it to every hit. How can I achieve this? -
django getting values from form
I need to filter the table by column and value, nothing better comes to my mind (I'm new in django) view def get_queryset(self): column = self.request.GET.get('column') condition = self.request.GET.get('condition') queryset = Table.objects.all() if condition == 'contains' and column == 'title': queryset = Table.objects.filter( title__icontains=self.request.GET.get('title') ) elif condition == 'greater' and column == 'quantity': queryset = Table.objects.filter(quantity__gt=self.request.GET.get('title')) elif condition == 'greater' and column == 'distance': queryset = Table.objects.filter(distance__gt=self.request.GET.get('title')) elif condition == 'lower' and column == 'quantity': queryset = Table.objects.filter(quantity__lt=self.request.GET.get('title')) elif condition == 'lower' and column == 'distance': queryset = Table.objects.filter(distance__lt=self.request.GET.get('title')) elif condition == 'equals' and column == 'quantity': queryset = Table.objects.filter(quantity__exact=self.request.GET.get('title')) elif condition == 'equals' and column == 'distance': queryset = Table.objects.filter(distance__exact=self.request.GET.get('title')) return queryset i knew it looks like **** please give me more elegant idea) there my table the idea is as follows, the user selects a column and the condition by which the table will be filtered thanks -
try to implement the live search by using django and AJAX
I am new to the Django and AJAX. I am trying to implement "live search" function by using django framework and the AJAX. This function will search the applications by using the name. The application model has its title. Then user can use search bar to make live search, which will show up results when you type the title. However, I did not figure out how it works. Hopefully someone can give me a hint. It will be appreciated if someone can help. JQuery $('document').ready(function(){ $('#search').keyup(function(e){ let csrftoken = '{{ csrf_token }}'; $.ajax({ type : 'POST', headers:{'X-CSRFToken':csrftoken}, url: "{% url 'search' %}", data: { 'search_text': $('#search').val() }, success: function(data){ console.log(data); $('html').load(data); } }); }); }); View.py @login_required(login_url='login') @allowed_users(allowed_roles=['student']) def search(request): data = dict() if request.method == "POST": search_text = request.POST["search_text"] if search_text is not None: applications = Application.objects.filter(user=request.user, title=search_text) data['result'] = applications print(data) return JsonResponse(data) However, in the view.py , the "data" cannot print out Also, is there another way to pass "applications" to the HTML and update the webpage? Since this code does not work for the live search -
django can't reverse match url from template
I ma having difficulty reverse matching a url, getting the error: NoReverseMatch at /patient/46cb4bd5-ef39-4697-84ff-9aa2b6e85e6b/ Reverse for 'treatment_detail' with no arguments not found. 1 pattern(s) tried: ['patient/(?P<patient_id>[^/]+)/$'] The url is: /patient/46cb4bd5-ef39-4697-84ff-9aa2b6e85e6b/ (the string is the 'apatient_id' and changes each time the user submits the 'add' page) urls.py is app_name = "patient" urlpatterns = [ path( route='add/', view=views.PatientAddView.as_view(), name="patient_add"), path( route='<patient_id>/', view=views.TreatmentTemplateView.as_view(), name='treatment_detail'), ] html <form action="{% url 'patient:treatment_detail' %}" method="get"> <input type="submit" class="btn btn-primary" value="get_doc" name="get_doc"> </form> views.py class TreatmentTemplateView(TemplateView): template_name = "../templates/patient/treatment_detail.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["patient_id"] = self.kwargs["patient_id"] result = find_treatment(context["patient_id"]) context = result[0] context["patient"] = result[1] return context If I have 'patient:patient_add' instead of 'patient:treatment_detail' it works fine so the issue seems to be about the route="<patient_id>"/ In urls.py -
Django-Filter Nested Serializer MultipleObjectsReturned
I have created an drf app and which includes nested relations. enter image description here As shown below I put the relations in my parent serializer.Then I am using it as an list and retrieve method supported by modelviewset enter image description here -
Django Filter on Distinct with orderby created at
How can I filter with distinct and order by IncomingCallRecording.objects.filter( ).order_by("lead_id","-created_at").distinct("lead_id") Problem Order by is not working with created at Is there an alternative solution that might help -
OSError('Tunnel connection failed: 403 Forbidden')))
Am trying to initiate a request to an API (https://theteller.net/documentation#theTeller_Standard) but i keep getting this error. The idea is that will take details of the user and pass it to my views.py to send a request to to make payment and be redirected back to my website. This is the error ProxyError at /vote/test/robert-yenji/ HTTPSConnectionPool(host='test.theteller.net', port=443): Max retries exceeded with url: /checkout/initiate (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden'))) this is my code views.py def nomination_payView(request, slug): if request.method == 'GET': model = get_object_or_404(Nomination, slug=slug) template_name = 'Payment.html' context = { 'nomination': model } return render(request, 'Payment.html', context) elif request.method == 'POST': amount = (str(int(request.POST['amount']) * 0.5) + '0').replace('.', '') zeros = '0' * (12 - len(amount)) amount = zeros + amount email = request.POST['email'] desc = request.POST['desc'] url = 'https://test.theteller.net/checkout/initiate' transaction_id = random.randint(100000000000, 999999999999) data = { "merchant_id": "TTM-00000740", "transaction_id": transaction_id, "amount": amount, "redirect_url": f"http://127.0.0.1:8000/process-payment/{slug}/{amount}", "apiuser": "halotech5d525bfd6ead3", "API_Key": "ZDQ2OGEyZDNjN2YzMDY5ZDVkY2MyM2U5YTRiMGI0N2Q=", "email": email, # you would need to change this to the actual users email "desc": desc, # this as well... } encoded = base64.b64encode( b'halotech5d525bfd6ead3:ZDQ2OGEyZDNjN2YzMDY5ZDVkY2MyM2U5YTRiMGI0N2Q=') # change this as well headers = { 'Content-Type': 'application/json', 'Authorization': f'Basic {encoded.decode("utf-8")}', 'Cache-Control': 'no-cache' } res = requests.post(url, data=json.dumps(data), headers=headers).json() … -
Django date field enable/ highlight only certain dates
My files are as below : Forms.py class FilterDaywiseNew(forms.Form): search_Day = forms.DateField(widget=NumberInput(attrs={'type': 'date'}),required=True,initial=datetime.date.today) Views.py def DayWiseFilterPage(request): form = FilterDaywiseNew() return render(request, 'agelist.html',{'form': form}) agelist.html <form method="post" action="SearchDisplay" id="searchFilterForm"> <div class="form-row"> <div class="col-md-8 mb-0"> {{ form.search_Day|as_crispy_field }} </div> </div> </form> My rendered html is like this <div id="div_id_search_Day" class="form-group"> <label for="id_search_Day" class=" requiredField"> Search day<span class="asteriskField">*</span> </label> I have a bunch of dates, that I would want to populate the datefield with, so that only these dates are enabled/ highlighted/ can be selected, like this Solutions given use JQuery to do this. I dont want to use JQuery. Is there a way this can be achieved? Thanks, -
Case insensitive search doesn't work on Django (Postgres) with non-latin characters
PostgreSQL 13.4 Django 3.2 MacOS 11.2 I try to implement a search function for finding a model instance by the "name" field. models.py class LatestConfiguration(models.Model): # Primary key name = models.CharField(verbose_name='Имя', max_length=150, unique=True, primary_key=True) Database encoding is UTF8: ➜ ~ psql <DB_NAME> -c 'SHOW SERVER_ENCODING' server_encoding ----------------- UTF8 (1 row) Database contains records, eg: Бухгалтерия для Казахстана, редакция 3.0 I try to search a model instance like that: LatestConfiguration.objects.filter(name__icontains='Бух') the output is ok: >>> LatestConfiguration.objects.filter(name__icontains='Бух') <QuerySet [Бухгалтерия для Казахстана, редакция 3.0]> I lower-cased the first letter in 'Бух' to 'бух' and repeated the search >>> LatestConfiguration.objects.filter(name__icontains='бух') <QuerySet []> so now I get an empty queryset but I shouldn't I also tried Q-objects: Q(name__istartswith='бух') but didn't get any results Tried to use postgres full text search by adding: 'django.contrib.postgres', to INSTALLED_APPS in settings.py and repeated searching this way: >>> LatestConfiguration.objects.filter(name__icontains='бух') <QuerySet []> Anyone else got the same error? -
Heroku can't load my css file because its a mimetype
I deployed my website it all works and main css loaded but for some reason my another css refusing to load in the console it say Refused to apply style from '......' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. This is my setting.py Am i missing something ? MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] STATICFILES_DIRS = [ BASE_DIR / "static", BASE_DIR / 'media', ] STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn') MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn') TEMP = os.path.join(BASE_DIR, 'media_cdn/temp') -
how to write django view testcases that use regex
i have my url patterns in regex format see below two examples re_path(r'^all/labwork$', av.all_labwork, name='all-labwork'), re_path(r'^patient/labwork/(?P[0-9A-Za-z-]+)/$', av.new_labwork, name='labwork') I am trying to write testcases to test them, just need a little direction to get started for example a testcase 'HomePageTest' class HomePageTests(TestCase): def test_home_page_status_code(self): response = self.client.get('labwork/')) self.assertEquals(response.status_code, 200) The issue is the arguement 'labwork/' passed to client.get() above will not work with the urlpatterns i have used, in normal conditions the routes all work, i figure i have to pass a regex into the get function. help needed and appreciated -
django settings default time zone
here is a question i can use django time zone for utc and it worked fine but when i switch the default time zone to 'Asia/Tehran' it wont work and i get the error ValueError: Incorrect timezone setting: ASIA/TEHRAN the actual code in settings.py is: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Tehran' USE_I18N = True USE_L10N = True USE_TZ = True and it is on django time zone list i checked it the system is ubuntu 20 and django version is 3.2 -
How can I integrate React Template Folder with Django Project
I bought a template for my news & magazine website and website maked With django. So I want to integrate react folder and app in my django project. How can I do it? This is template Folder Structure -
Generate Django Model Fields
I want to add the field according to the type chosen. Suppose if I choose Charfield I want to have option name as Char and if DateFied is chosen I want to have a Date field in my model. Is is possible to do it in Django? class Options(models.Model): TYPE= ( ('Charfield','Charfield'), ('Integerfield','Integerfield'), ('Datefield','Datefield'), ) optiontype = models.CharField(max_length=20, choices=TYPE) optionname= models.CharField(max_length=50) -
How to automate Django - React app deployment
I have Django as backend and React as frontend, my current deployment process is I use WinSCP to transfer react build to django backend and then with Putty I use python manage.py collectstatic. Then I update git repo at aws, do migrations (if any) manually. I want to automate this in way that There is no need to build and copy react to backend also not to pull current repo changes or use WinSCP or Putty etc. I just want simple script or any standard way by which, whenever I update code in my production branch at backend and frontend, deployment will be done automatically. Pls suggest me the way. TIA -
meta tags shows in <body> While Should be placed in the <head>
I have a website based on the django framework. I want to add meta tags to the website With conditions : """Definition of models.""" from django.db import models class Pages_Meta(models.Model): Page_name = models.TextField(null=False) Page_meta = models.TextField(null=False) page_title = models.TextField(null=False) And html page is: <html> <head> <title> {{ title }} - Farhad Dorod </title> {{ meta }} </head> </html> <body> ... </body> And urls.py is: path('index/', LoginView.as_view( template_name='app/index.html', extra_context= { 'title': Pages_Meta.objects.get(id = 1).page_title, 'meta' : Pages_Meta.objects.get(id = 1).Page_meta, }), name='index') result: all meta tags shows in body While Should be placed in the head enter image description here -
Django does not redirect after receiving POST request
After taking google credentials through POST request, I want Django to log the user in and redirect to home page from google.auth import jwt def google_login(request): if request.method == "POST": credential = request.body profile_info = jwt.decode(credential, verify = False) email = profile_info["email"] user = User.objects.filter(email = email) if user: login(request, user.first()) print("---------------login success") return HttpResponseRedirect(reverse("index")) else: return render(request, "network/login.html", { "message": "Invalid username and/or password." }) else: return render(request, "network/login.html") login success is printed but the page is not redirected nor refresh. The terminal doesn't show much ---------------login success [22/Sep/2021 16:05:59] "POST /google_login HTTP/1.1" 302 0 [22/Sep/2021 16:05:59] "GET / HTTP/1.1" 200 13957 [22/Sep/2021 16:06:03] "GET /static/network/styles.css.map HTTP/1.1" 404 1825 [22/Sep/2021 16:06:10] "GET /account/login HTTP/1.1" 200 4342 [22/Sep/2021 16:06:10] "GET /static/network/styles.css.map HTTP/1.1" 404 1825 [22/Sep/2021 16:06:10] "GET /account/login HTTP/1.1" 200 4342 My code in the front end is liked this const csrftoken = Cookies.get('csrftoken'); function handleCredentialResponse(response) { fetch(`/google_login`, { method: 'POST', headers: { 'X-CSRFToken': csrftoken }, body: response.credential }) } -
getting button to perform function in django
I am wanting webpage where the user clicks a button to produce a word document. Currently, however, when the user clicks the button, the page simply reloads and appends '?get_doc=get_doc#' to the url. Instead I would like a prompt for the user to download the generated document urls.py app_name = "patient" urlpatterns = [ path('add/', views.PatientAddView.as_view(), name="patient_add"), path( route='<patient_id>/', view=views.TreatmentTemplateView.as_view(), name='treatment_detail'), ] views.py class TreatmentTemplateView(TemplateView): template_name = "../templates/patient/treatment_detail.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["patient_id"] = self.kwargs["patient_id"] result = find_treatment(context["patient_id"]) context = result[0] context["patient"] = result[1] return context def get_doc(request): print('running9') # if(request.GET.get('get_doc')): if 'get_doc' in request.GET: print('running') document = Document() docx_title="TEST_DOCUMENT.docx" # ---- Cover Letter ---- document.add_paragraph() document.add_paragraph("%s" % date.today().strftime('%B %d, %Y')) document.add_paragraph('Dear Sir or Madam:') document.add_paragraph('We are pleased to help you with your widgets.') document.add_paragraph('Please feel free to contact me') document.add_paragraph('I look forward to assisting you in this project.') document.add_paragraph('Best regards,') document.add_paragraph('Acme Specialist 1]') document.add_page_break() # Prepare document for download # ----------------------------- f = BytesIO() document.save(f) length = f.tell() f.seek(0) response = HttpResponse( f.getvalue(), content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) response['Content-Disposition'] = 'attachment; filename=' + docx_title response['Content-Length'] = length return response html {% extends "base.html" %} <!-- {% block title %}Patient: {{ patient.name }}{% endblock %} --> {% block content … -
Django: Dependency on swappable model (lazy reference)
Disclaimer, I have read the following posts, and they did not provide a helpful answer for my case: lazy reference: doesn't provide model user? django custom user model gives me lazy reference error django-swappable-models I have written a reusable app that handels authentication methods and user management. In its core, it overrides the AUTH_USER_MODEL (lets call the model CustomUser and provides a swappable model Person, which has O2O field to a CustomUser: class CustomUser(AbstractUser): def save(self, *args, **kwargs): if not self.pk or hasattr(self, 'person') is False: super().save(*args, **kwargs) get_person_model().objects.create(birthdate=None, user=self) else: super().save(*args, **kwargs) class AbstractPerson(models.Model): user = models.OneToOneField(settings.MY_APP_PERSON_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name='person') birthdate = DateField(null=True, default=None) class Meta: abstract = True class Person(AbstractPerson): class Meta(AbstractPerson.Meta): swappable = 'REUSABLE_APP_PERSON_MODEL' To create the migrations in my reusable app, I have setup a "dummy" django project which includes this app, and sets REUSABLE_APP_PERSON_MODEL to reusable_app.Person. This works flawlessly, in my real django project, I can set REUSABLE_APP_PERSON_MODEL to a model that inherits from reusable_app.AbstractPerson. The problem arises, when my reusable app has another model that holds a foreign key to REUSABLE_APP_PERSON_MODEL: class Invite(models.Model): email = models.EmailField() person = models.OneToOneField(settings.REUSABLE_APP_PERSON_MODEL, on_delete=models.CASCADE, null=False, related_name='+') code = models.CharField(max_length=5) Again, I created a migration for this model … -
ValueError at / The view leads.views.home_page didn't return an HttpResponse object. It returned None instead python django template error how to fix
ValueError at / The view leads.views.home_page didn't return an HttpResponse object. It returned None instead. this is my code: views.py: from django.shortcuts import render from django.http import HttpResponse def home_page(request): # return HttpResponse('Hello world') render(request, 'leads/home_page.html') and here's the urls.py: from django.contrib import admin from django.urls import path from leads.views import home_page urlpatterns = [ path('admin/', admin.site.urls), path('', home_page), ] and here's the template: -
How to handle multiple Django forms in a request.POST
Let's say I have a form that contains the following values after I submit the form: print(request.POST): <QueryDict: {'csrfmiddlewaretoken': ['3oveeCkYroBwKNSLw8wOr8dtURYGcO9AtOKYfPoNbf8q3L5Az7aEAnJaQldYmnaG'], 'user': ['1'], 'reset': ['false'], 'project': ['100001'], 'contents': ['test'], 'amount': ['3'], 'currency': ['JPY'], 'expense_date': ['09/22/2021'], 'store_company_client_name': ['test'], 'expense_category': ['Staffing payments'], 'note': ['fdv']}> What if I have multiple inputs and I get a request.POST like this: <QueryDict: {'csrfmiddlewaretoken': ['xbdRWXh4LdKTTJoCMJa7O53lApbY03byXBsBXalTv4hNcHBrPIOXXkz2wTqgaCcE'], 'user': ['1','1','1'], 'expense_date': ['09/22/2021', '09/21/2021', '09/20/2021'], 'project': ['100001', '100002', '100002'], 'expense_category': ['Staffing payments', 'Staffing payments', 'Staffing payments'], 'expense_type': ['Salaries', 'Salaries', 'Salaries'], 'contents': ['test', 'test', 'test'], 'currency': ['1', '1', '1'], 'amount': ['12', '1', '4'], 'store_company_client_name': ['customer1', 'customer2', 'customer3'], 'note': ['lorem ipsum', 'lorem ipsum', 'lorem ipsum']}> How can I process it in the back-end? Right now for a simple form I have this view: def new_expense(request): data = { 'title': "New Expense", } data['projects'] = Project.objects.filter(is_visible=True).values('id') data['expense_category'] = dict((y, x) for x, y in EXPENSE_CATEGORY) data['expense_type'] = dict((y, x) for x, y in EXPENSE_TYPE) form = ExpenseForm() if request.method == "POST": print(request.POST) reset = request.POST['reset'] form = ExpenseForm(request.POST) if form.is_valid(): form.save() if reset == 'true': form = ExpenseForm() data['form'] = form return render(request, "expense/new_expense.html", data) And I want to create a new view capable of doing exactly the same thing as new_expense but just for …