Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ability to find certain pages through search
I want to have a search bar that search all the views that are static and supplies search results for example this page here has the function I need: https://cagenix.com/ . If you click the magnifying glass it opens a search bar and allows you to search all their static pages and supplies the user with results. Is there any way to do this in Django views? -
Django Rest Framework Grouping results by Foreign Key value
I am trying to do a child list model. This model has parent foreign key and child foreign key. What I want to do is to gather the ones with the same parent value under a single group. If the parent 1 has 3 child, the result should look like this: { first_name: "bla bla" last_name: "bla bla" children: [ { first_name: "bla bla"} { first_name: "bla bla"} { first_name: "bla bla"} ] } Is there any way to do this in child list serializer? I just couldn't make it. I want to go to the url address according to the parent value and make a grouping as above. First solution that came to mind is using the related name field. I tried to do this, but I was unsuccessful. I can write similar codes, I have already written for other apps on this project. However, when the subject comes to the list of children, my brain is failing me. I can't find the right thing to do, I can't understand. Models class ChildProfile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True, verbose_name=AccountStrings.ChildProfileStrings.user_verbose_name, related_name="user_child") city = models.ForeignKey( City, on_delete=models.SET_NULL, null=True, blank=True, verbose_name=AccountStrings.ChildProfileStrings.city_verbose_name, related_name="city_child_profiles") hobbies = models.CharField( max_length=500, null=True, blank=True, verbose_name=AccountStrings.ChildProfileStrings.hobbies_verbose_name) class ParentProfile(models.Model): … -
Blank page on mobile when Debug is off
I built an app on Django & React which displays a blank page on mobile browsers & Safari (desktop) as soon as I set DEBUG=False in my Django settings.py file. I inspected the browser consoles network tab and noticed that Safari seems to be unable to read my react javascript bundle. I inspected the network tab on Safari with both Debug on and off to see if there are any differences in how the file is served and found this: Debug=False (app not loading) As you can see, the response Content-Disposition is telling me that the file's extension is .js.gz - this ends up showing the "corrupted" version of the file which I linked in the first screenshot. Debug=True (app works as expected) When setting debug to true, it loads a different version of the same file. The filename is slightly different and the file extension is .js I use webpack to bundle these files and a package called django-webpack-loader to inject them into my HTML template. Code in settings.py that might be relevant: # django-webpack-loader if DEBUG: WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': '', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), 'TIMEOUT': 10, }, } if not DEBUG: WEBPACK_LOADER = { 'DEFAULT': { … -
NameError: name 'appointment' is not defined
My code should Post data into their respective db tables But on Post request I'm getting NameError: name 'appointment' is not defined [18/Jul/2021 12:27:31] "POST /api/appointment/make/ HTTP/1.1" 500 108215 I checked already asked questions like that but I'm unable to reproduce the solution. views.py @api_view(['POST']) @permission_classes([IsAuthenticated]) def makeAppointments(request): user = request.user data = request.data membersToHeldMeeting = data['membersToHeldMeeting'] if membersToHeldMeeting and len(membersToHeldMeeting) == 0: return Response({'detail': 'No Appointment Has Been Set'}, status=status.HTTP_400_BAD_REQUEST) else: # (1) Create Appointment createappointment = MakeAppointment.objects.create( user=user, reasonOfAppointment=data['reasonOfAppointment'], meetingWillBeConductedOn=data['meetingWillBeConductedOn'], paymentMethod=data['paymentMethod'], taxPrice=data['taxPrice'], consultancyServiceFee=data['consultancyServiceFee'], totalFee=data['totalFee'] ) # (2) Create AppointmentDetails appointmentdetails = AppointmentDetails.objects.create( appointment=appointment, #error coming from this line,why this is undefined im not able to understand that , appointmentReason=data['appointmentDetails']['appointmentReason'], dateOfBirth=data['appointmentDetails']['dateOfBirth'], gender=data['appointmentDetails']['gender'], maritalStatus=data['appointmentDetails']['maritalStatus'], phoneNumber=data['appointmentDetails']['phoneNumber'], emergencyContactNo=data['appointmentDetails']['emergencyContactNo'], medicalHistory=data['appointmentDetails']['medicalHistory'], previousTreatmentDetails=data['appointmentDetails']['previousTreatmentDetails'], allergicTo=data['appointmentDetails']['allergicTo'], address=data['appointmentDetails']['address'], city=data['appointmentDetails']['city'], postalCode=data['appointmentDetails']['postalCode'], country=data['appointmentDetails']['country'], ) # (3) Create all appointments and set appointment to MembersOfPanelToHeldMeeting relationship for i in membersToHeldMeeting: panelmember = PanelMember.objects.get(_id=i['panelmember']) allmeetings = MembersOfPanelToHeldMeeting.objects.create( panel=panelmember, appointment=appointment, name=panelmember.name, totalFee=i['totalFee'], image=panelmember.image.url, ) serializer = MakeAppointmentSerializer(createappointment, many=False) return Response(serializer.data) Respective Models `models.py` class MakeAppointment(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) reasonOfAppointment = models.TextField(null=True, blank=True) paymentMethod = models.CharField(max_length=200, null=True, blank=True) taxPrice = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) consultancyServiceFee = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) totalFee = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) isPaid = models.BooleanField(default=False) … -
Page not updating after adding image to django admin
I've created a model HomeImage. I have FOR LOOP in my template, where I render images to a page from my database. What I did is that you can add images through admin site and my problem is, that after I add image to admin it doesn't render added image/s. I have to shutdown the running server and run it again to see those images I added. I would like to have my page updated after I add image through admin site. Is there any solution? class HomeImage(models.Model): thumbnail = models.ImageField(upload_to="images/") -
Validate HTML tags if they are valid HTML tag or not python?
I am using Django to build website and I want to check if I am using a valid HTML tag or not. This is my code. class Actions: view_class = None action_name = None action_code = None action_icon = None action_attr = None action_title = "icon" # icon,text ,both with_url = False actions_template = "core/core/actions/action.html" action_css = [] action_js = [] action_class = "btn btn-secondary hide action-item" action_position = "above_form" # above_form, above_grid, both ,on_form , on_grid action_tag = "a" def render_actions(self, request): return render_to_string( self.actions_template, { "action_name": self.action_name, "action_code": self.action_code, "action_icon": self.action_icon, "action_class": self.action_class, "action_title": self.action_title, "action_tag": self.action_tag, "with_url": self.with_url, "action_attr": self.action_attr, "with_modal": self.with_modal, "form_name": form_name, "action_url": reverse_lazy(self._related.__class__.__name__.lower()) if self.with_url else "", }, ) For example if action_tag value is buttun the code should raise error, if action_tag value is button or any valid HTML tag there is no error raised. How can I do this offline not online. -
Unable to send json in ajax to django without jquery
I am trying to use AJAX with Django but without jQuery, almost I am successful in doing so but only urlencoded data can be sent from AJAX to Django and unable to send data in JSON format, but I am able to get a response from Django to AJAX in JSON format too. I have tried a lot as you can see comments in these files: senddata.html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <title>Send AJAX data</title> </head> <body> <h2>Send AJAX data by using the button</h2> <button id="btn-submit" class="btn btn-outline-dark">SEND</button> <script> var sendbtn = document.getElementById('btn-submit') sendbtn.addEventListener('click', sendBtnHandler) function sendBtnHandler() { console.log('sendBtn is clicked') const xhr = new XMLHttpRequest() xhr.open('POST', 'http://localhost:8000/contact/send', true) // xhr.getResponseHeader("Content-type", "application/json"); // xhr.getResponseHeader("Content-type", "application/x-www-form-urlencoded"); // xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // xhr.setRequestHeader("Content-type", "application/json"); xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8"); xhr.onprogress = function () { console.log("on progress, wait a while until data is fetched") } xhr.onload = function () { console.log('success') console.log(this.responseText) } let params = `{"name":"mayur90","salary":"12213","age":"23"}` let b = 2 let d = 4 // let params = `a=${b}&c=${d}` xhr.send(params) // xhr.send(b) console.log(params) } </script> <!-- Optional JavaScript; choose one of the two! --> <!-- Option … -
How to set up my Django models for this ManyToMany scenario?
I gather keywords with their monthly values over a period of time. Then I want to relate certain keyword combinations (average the values for example) for certain topics. So here is a basic table structure with some sample data so you can picture what I am dealing with: Table 1 - columns 1,2,3 are "unique together" keyword | location boolean (inUSA true/false) | Date | Value dog | true | 01/01/2020 | 10 dog | true | 02/01/2020 | 20 dog | true | 03/01/2020 | 10 dog | false | 01/01/2020 | 10 cat | false | 01/01/2020 | 10 Table 2 Topic | has many keywords | extra info dogs in USA | should reference 3 entries dogs everywhere | 4 entries dogs and cats outside of USA | 2 entries dogs out of USA | 1 entry cats out of USA | 1 entry Keywords can belong to many topics, topics can have many keywords. Can a simple ManyToMany relationship between 2 models work? Or do I need something more complicated? I tried setting it up with 2 models, but having 3 primary keys for table1 (dog,inUSA,date) gets too complicated and I don't know if Django can … -
Django form field validation not working and no errors
I have a form in Django for which I need to validate the phone number. No validation is taking place after the "next" button is executed. I have made a print to check if validation is called and I can see that it is not called and I have made sure that validators.py is in the same app folder as my form. forms.py from django import forms from .validators import phoneNumberValidation class customerLocalDeliveryForm(forms.Form): customerName = forms.CharField(label = 'Name', max_length=20, required=True) customerEmail = forms.EmailField(label = 'Email', max_length=50, required=True) customerMobile = forms.CharField(label = 'Mobile', max_length = 20, required = True, validators=[phoneNumberValidation]) comments = forms.CharField(label = 'Comments', max_length = 300, widget=forms.Textarea, required = False) deliveryTime = forms.ChoiceField(choices = (), required=True) def __init__(self, *args, **kwargs): self.deliveryTimeList = kwargs.pop('deliveryTimeList') super().__init__(*args, **kwargs) self.fields['deliveryTime'].choices = self.deliveryTimeList In my validators.py which is in the same folder as my form. I have no idea why this validation is not called as I don't see the print in my console when I tested the validation from the webpage. from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ def phoneNumberValidation(value): print('here is the value') print(value) if len(value) <= 7: print('we are here') raise ValidationError(_("The phone number must be 8 digits")) … -
facing problem to push data to backend from local storage in react
I tried alot to fix that but I need little help to figure out what I'm doing wrong. When I make post request POST /api/appointment/make/ Request gets failed with status code 500 Internal Server Error: /api/appointment/make/ Traceback (most recent call last): File "E:\eCommerce_Projects\remote-hospital-v3\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\eCommerce_Projects\remote-hospital-v3\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\eCommerce_Projects\remote-hospital-v3\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "E:\eCommerce_Projects\remote-hospital-v3\venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "E:\eCommerce_Projects\remote-hospital-v3\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "E:\eCommerce_Projects\remote-hospital-v3\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "E:\eCommerce_Projects\remote-hospital-v3\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "E:\eCommerce_Projects\remote-hospital-v3\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "E:\eCommerce_Projects\remote-hospital-v3\venv\lib\site-packages\rest_framework\decorators.py", line 50, in handler return func(*args, **kwargs) File "E:\eCommerce_Projects\remote-hospital-v3\panel\views\appointment_views.py", line 19, in makeAppointments membersToHeldMeeting = data['membersToHeldMeeting'] KeyError: 'membersToHeldMeeting' [17/Jul/2021 23:52:27] "POST /api/appointment/make/ HTTP/1.1" 500 106441 First take a look at backend urls path('api/appointment/make/', views.makeAppointments, name='appointment-add'), Related view @api_view(['POST']) @permission_classes([IsAuthenticated]) def makeAppointments(request): user = request.user data = request.data membersToHeldMeeting = data['membersToHeldMeeting'] if membersToHeldMeeting and len(membersToHeldMeeting) == 0: return Response({'detail': 'No Appointment Has Been Set'}, status=status.HTTP_400_BAD_REQUEST) else: # (1) Create Appointment createappointment = MakeAppointment.objects.create( user=user, reasonOfAppointment=data['reasonOfAppointment'], meetingWillBeConductedOn=data['meetingWillBeConductedOn'], paymentMethod=data['paymentMethod'], taxPrice=data['taxPrice'], consultancyServiceFee=data['consultancyServiceFee'], totalFee=data['totalFee'] ) # (2) Create … -
how to display all the data from database in django html table
I want to display the data from database using html table in django. im using mysql and already connected to django. here is my view : def table_list(request): tablelst = CompanyRate.objects.all() context = {'tablelst': tablelst} return render(request, 'articleapp/table_list.html', context) Model: class CompanyRate(models.Model): date = models.CharField(max_length=255, blank=True, null=True) notice_name = models.CharField(max_length=255, blank=True, null=True) event = models.CharField(max_length=255, blank=True, null=True) basic_amount = models.CharField(max_length=255, blank=True, null=True) num_of_company = models.CharField(max_length=255, blank=True, null=True) avg_of_1365 = models.CharField(max_length=255, blank=True, null=True) hd_rate = models.CharField(max_length=255, blank=True, null=True) hd_num = models.CharField(max_length=255, blank=True, null=True) hj_rate = models.CharField(max_length=255, blank=True, null=True) hj_num = models.CharField(max_length=255, blank=True, null=True) hm_rate = models.CharField(max_length=255, blank=True, null=True) hm_num = models.CharField(max_length=255, blank=True, null=True) url = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'company_rate' articleapp/urls.py urlpatterns = [ path('table_list/', TemplateView.as_view(template_name='articleapp/table_list.html'), name='table_list'), ] main urls.py urlpatterns = [ path('articles/', include('articleapp.urls')), ] table_list.html {% extends 'base.html' %} {% block content %} <table class="table table-hover table-responsive"> <tbody> {% for article in query_results %} <tr> <td>{{ article.id }}</td> <td>{{ article.date }}</td> <td>{{ article.notice_name }}</td> <td>{{ article.event }}</td> <td>{{ article.basic_amount }}</td> <td>{{ article.num_of_company }}</td> <td>{{ article.avg_of_1365 }}</td> <td>{{ article.hd_rate }}</td> <td>{{ article.hd_num }}</td> <td>{{ article.hj_rate }}</td> <td>{{ article.hj_num }}</td> <td>{{ article.hm_rate }}</td> <td>{{ article.hm_num }}</td> <td>{{ article.url }}</td> </tr> {% endfor %} <tbody> </table> … -
How to fix 404 error on DJANGO for external URL
I am using DJANGO for the first time to make a project for a website. I am getting a 404 error message. Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/external/ Using the URLconf defined in firstwebsite.urls, Django tried these URL patterns, in this order: admin output [name='script'] external The current path, external/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Views.py from django.shortcuts import render import requests import sys from subprocess import run,PIPE def button(request): return render(request, 'home.html') def output(request): data=requests.get("/Users/myname/PycharmProject/ex2.py/coders.py") print(data.text) data=data.text return render(request, 'home.html', {'data':data}) def external(request): inp= request.POST.get('param') out= run([sys.executable,'/Users/myname/tester/tester/test.py',inp],shell=False,stdout=PIPE) print(out) return render(request, 'home.html',{'data1':out}) <!DOCTYPE html> <html> <head> <title> Python button script </title> </head> <body> <button onclick="location.href='{% url 'script' %}'">Execute Script</button> <hr> {% if data %} {{data | safe}} {% endif %} <form action="/external/" method="post"> {% csrf_token %} Input Text: <input type="text"name="param" required><br><br> {{data_external}}<br><br> {{data1}} <br><br> <input type='submit' value="Execute External Python Script"> </form> </body> </html> URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views … -
How do we combine multiple tables to create a report table displaying all the columns with an auto-incrementing, regex defined ID of its own?
I have 3 models: class Student(models.Model): roll_number=models.IntegerField(primarykey=True) name=models.CharField(max_length=50) email=models.EmailField(max_length=60) city=models.CharField(max_length=20) class Course(models.Model): roll_number=ForeignKey(Student, on_delete=CASCADE) course=ForeignKey(CourseChoices, on_delete=CASCADE) class Fee(models.Model): roll_number=ForeignKey(Student, on_delete=CASCADE) total_fee=models.DecimalField(max_digits=7, decimal_places=2, default=0) discount=models.DecimalField(max_digits=5, decimal_places=2, default=0) Final_amount=models.DecimalField(max_digits=5, decimal_places=2, default=0) Amount_received=models.DecimalField(max_digits=5, decimal_places=2, default=0) Balance=models.DecimalField(max_digits=5, decimal_places=2, default=0) batch=models.CharField(validators=[batch_pattern]) Now, whatever data these tables hold, I want to display them together as: Track ID--Roll No.--Name--Email--City--Course--Total Fee--Discount--Final Amount--Amount Received--Balance--Batch These are the Column heads I want. The 'Track ID' should be the report's own primary key which I want to define using regex. Also, I want every instance to appear in this report with different Track ID. For example, if a student pays a partial fee, it will get recorded in a row with a Track ID. Whenever he/she pays the rest of the amount, should get recorded with the relevant Track ID as per its place in the sheet. I hope I'm explaining well what I intend to achieve here. If I'm not clear, kindly let me know and I'll explain everything with an example or something. Hope I get some help on this here. -
User-specific home page Django
I am trying to create a user-specific home page for my Django site (i.e., go directly to the logged-in user's page when the site is loaded). I am having trouble figuring out how to add the username to the URL path from the get-go. This is how I've typically created the path to the home page: urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), But essentially what I think I want to do is this: urlpatterns = [ path('admin/', admin.site.urls), path('<username>/', include('blog.urls')), So that the default home page when I run the server would be something like this : http://127.0.0.1:8000/someusername Is there a way to access the logged-in user by default automatically? -
Function call in another file not working in Django rest framework
I am using Django signals to trigger a task (sending mass emails to subscribers using Django celery package)when an admin post a blogpost is created from Django admin. The signal is triggered but the task function in the task file is not called. It's because I put a print function which is not printing inside the task function. My signlas.py file: from apps.blogs.celery_files.tasks import send_mails from apps.blogs.models import BlogPost,Subscribers from django.db.models.signals import post_save from django.dispatch import receiver def email_task(sender, instance, created, **kwargs): if created: print("@signals.py") send_mails.delay(5) post_save.connect(email_task, sender=BlogPost,dispatch_uid="email_task") My task.py file from __future__ import absolute_import, unicode_literals from celery import shared_task # from celery.decorators import task from apps.blogs.models import BlogPost,Subscribers from django.core.mail import send_mail from travel_crm.settings import EMAIL_HOST_USER from time import sleep @shared_task def send_mails(duration,*args, **kwargs): print("@send_mails.py") subscribers = Subscribers.objects.all() blog = BlogPost.objects.latest('date_created') for abc in subscribers: sleep(duration) print("i am inside loop") emailad = abc.email send_mail('New Blog Post ', f" Checkout our new blog with title {blog.title} ", EMAIL_HOST_USER, [emailad], fail_silently=False) Here. the print("@send_mails.py") is not executed but print("@signals.py") in signals.py file is executed. Hence, signals is received after the Blogpost model object is created but the function inside task.py which is send_mails is not executed. I have installed both celery … -
serve react from django
i'm trying to serve react from django and when i try to connect react with django api give me this message App.js:25 POST http://localhost:8000/api/try/ net::ERR_BLOCKED_BY_CLIENT this the APP.js import React, {useEffect} from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router , Switch, Link, Route} from "react-router-dom"; import Home from './Home' import Login from './Login' import axios from 'axios'; import API from "./endpoint" // import {API_URL } from "../constants"; const App=()=>{ const getData=async()=>{ const res=await fetch(API+'api/try/', { method :"POST", headers :{ "Content-Type": "application/json" }, body :JSON.stringify({ email :"mohamed" }) }) const data=await res.json(); console.log(data) } useEffect(()=>{ getData(); }) return ( <Router> <Link to="/login">login</Link> <Link to="/home">Home</Link> <Switch> <Route path="/home" component={Home} /> <Route path="/login" component={Login}/> </Switch> </Router> ) } export default App; and i havn't put proxy:"localhost:8000" in package.json and Procfile of django is web:gunicorn backend.wsgi -log-file- -
form.is_valid(): -- with ModelForm instead of form- User specific data - Django
So I am integrating user-specific data in my Django website and I have gotten it to kind of work. Right now it is working on a model called ToDoList with one field called "name" and a (form.Form) in my forms.py file. It works but now I need to change it to work with a different model called Sheet_Building that has many fields and more importantly a new form called SheetForm_Building that is a (form.ModelForm). Problem: I can't get my view in my views.py file to be able to support a form.ModelForm instead of a form.Form. Ill link my form and HTML below but it all works except for when I try to integrate the new ModelForm into the view. views.py def adddata_building(response): if response.method == "POST": form = CreateNewList(response.POST) if form.is_valid(): n = form.cleaned_data["name"] t = ToDoList(name=n) t.save() response.user.todolist.add(t) return HttpResponseRedirect("/front_page/sheets/list_data_building/") else: form = CreateNewList() return render(response, 'sheets/add_data/add_data_building.html', {'form': form}) models.py class ToDoList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="todolist", null=True) name = models.CharField(max_length=200) def __str__(self): return self.name CURRENT FORM IN forms.py class CreateNewList(forms.Form): name = forms.CharField(label="Name ", max_length=300) FORM NEEDED TO USE IN forms.py class CreateNewList(forms.ModelForm): class Meta: model = ToDoList fields = '__all__' create HTML <h3>Create a New To Do … -
Django identify if the last reply/comment is not by post author
I am trying to develop a blog site for myself. I have developed comment reply module successfully. But i am facing issue to notify blog author a unanswered comment or unanswered reply of a comment. Here is my Comment model- class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) reply = models.ForeignKey('Comment', null=True, related_name='replies', on_delete=models.DO_NOTHING) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}' . format(self.post.title, str(self.username)) Which produce a table a bellow- | id | content | timestamp | post_id | reply_id | username_id | | -- | ------- | --------- | ------- | -------- | ----------- | | 1 | Comment 1 | 2021-07-18 03:12:54.015803 | 2 | NULL | 1 | |2|Reply 1 to Comment 1|2021-07-18 03:12:59.940654| 2| 1| 1| |3| Reply 2 to Comment 1| 2021-07-18 03:13:07.965133| 2| 1| 1| |4| Reply 3 to Comment 1 | 2021-07-18 03:13:21.053474| 2| 1| 1| |5| Comment 2| 2021-07-18 03:15:21.765414| 2| NULL| 1| I want the "Comment 2" and "Reply 3 to Comment 1" what is not replied by post author. Best Regards, Samrat -
Django LOGGING exception handling
In my Django application I have below logging. The class common.loghandler.kafkaloghandler is used as logging handler. I would like to know how to handle the case where the kafkaloghandler itself produces the exception. It is part of third party application and I cannot change the code there. I would like to take care of that at my end. Due to the exception my rest of the code block did not work. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'common.loghandler.kafkaloghandler', 'filename': '/path/to/django/debug.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } -
Virtualenv for django in VS Code not working, What am I doing wrong?
I've been following a tutorial on how to start using django and creating a virtual env on VS Code, but it doesn't work.. For what it shows in the tutorial, it's supposed to create a folder called ".vscode" with a json file inside called "settings.json" that contains the python path to the python interpreter.. But in my case, none of those files appear.. I THINK there might be sth wrong with the path where it creates the virtual env, but since I'm pretty new at this, I can hardly say.. This are the steps I followed: C:\Users\Usuario\Desktop\Andres\Programación\5. Prácticas\3. PYTHON>cd DJANGO C:\Users\Usuario\Desktop\Andres\Programación\5. Prácticas\3. PYTHON\DJANGO>mkdir storefront C:\Users\Usuario\Desktop\Andres\Programación\5. Prácticas\3. PYTHON\DJANGO>cd storefront C:\Users\Usuario\Desktop\Andres\Programación\5. Prácticas\3. PYTHON\DJANGO\storefront>pipenv install django C:\Users\Usuario\Desktop\Andres\Programación\5. Prácticas\3. PYTHON\DJANGO\storefront>code . C:\Users\Usuario\Desktop\Andres\Programación\5. Prácticas\3. PYTHON\DJANGO\storefront>pipenv shell (storefront-vT5YbUlq) C:\Users\Usuario\Desktop\Andres\Programación\5. Prácticas\3. PYTHON\DJANGO\storefront>django-admin startproject storefront . (storefront-vT5YbUlq) C:\Users\Usuario\Desktop\Andres\Programación\5. Prácticas\3. PYTHON\DJANGO\storefront>pipenv --venv ** So the command prompt returns me this: C:\Users\Usuario.virtualenvs\storefront-vT5YbUlq I'm supposed to copy that line to "Enter interpreter path" in VSCode, and after that it should create those vscode folder and json file.. but that doesn't happen, so I can't use the VS terminal to run the server I'm going insane with this, I just can't understand where's the problem I'd really appreciate if someone could help … -
django social share button icons
I'm trying to add the functionality to share a workout post to social media, and found that the django-social-share package is the best. Everything works, but I'm curious how to add an icon over the link, as it currently looks like Post to Facebook! which is very bland. I've seen examples of adding CSS, but since the package works like {% post_to_facebook object_or_url "Post to Facebook!" %} I'm not sure how you could target that with CSS. Any help is appreciated. -
What is the use of apps.py, appconfig in django project. How and why to use it? could someone explain in a simple way
from django.apps import AppConfig class App1Config(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'app1' -
Should I use abstractbaseuser or abstractuser?
My requirement is to create AUTH system which uses email as AUTH token and some extra fields like name, phone etc and get rid of username field: I can achieve this using both the abstract classes ! But confused on which to use I can just use AbstractUser and make "username=None" and then add usernanager ! Or should i use AbstractBaseUser and redo everything ? -
zappa throwing errors after uploading to lambda
Hi I am new to zapper and aws I am getting errors when i use zappa to upload using zappa==0.48.2 python 3.6 Django==3.1.5 see error below [1626571209893] [DEBUG] 2021-07-18T01:20:09.893Z 42b0c70d-dd34-45a2-a844-xxxxxxxxxxyyyyy Zappa Event: {'time': '2021-07-18T01:19:33Z', 'detail-type': 'Scheduled Event', 'source': 'aws.events', 'account': '630589988206', 'region': 'us-west-2', 'detail': {}, 'version': '0', 'resources': ['arn:aws:events:us-west-2:630589988206:rule/appname-dev-zappa-keep-warm-handler.keep_warm_callback'], 'id': '97b022f9-7ece-b2a6-49a0-9b9aa33fbac0', 'kwargs': {}} [1626571209893] [DEBUG] 2021-07-18T01:20:09.893Z 42b0c70d-dd34-45a2-a844-xxxxxxxxxxyyyyy Zappa Event: {} [1626571450446] [DEBUG] 2021-07-18T01:24:10.446Z 66301a7e-0c98-40c1-a54a-5xxxxxxxxxx Zappa Event: {'time': '2021-07-18T01:23:33Z', 'detail-type': 'Scheduled Event', 'source': 'aws.events', 'account': '630589988206', 'region': 'us-west-2', 'detail': {}, 'version': '0', 'resources': ['arn:aws:events:us-west-2:630589988206:rule/appname-dev-zappa-keep-warm-handler.keep_warm_callback'], 'id': '0513b111-9296-e9b6-73fa-fe0bdfa30215', 'kwargs': {}} [1626571450447] [DEBUG] 2021-07-18T01:24:10.447Z 66301a7e-0c98-40c1-a54a-5xxxxxxxxxx Zappa Event: {} -
Django Admin - dynamic select options with foreignkey and manytomanyfields
Here the supplier is related to Supplier model (ForeignKey) and substrate is with Substrate (ManyToManyField). The main model here is SupplierInfo from which we can filter suppliers and get their respective substrate. When ever admin clicks on the dropdown of Arrival_supplier and, SupplierInfo_substrate should be filtered with the supplier name and should be able to receive SupplierInfo_substrate inside Arrival_substrate. The Arrival model, where the filtered SupplierInfo_substrate should be saved. class Arrival(models.Model): submitted_on = DateTimeField(auto_created=True, null=True, blank=False, editable=False) edited_on = DateTimeField(auto_now_add=True) submitted_by = ForeignKey(get_user_model(), on_delete=models.SET_NULL, null=True) supplier = ForeignKey(Supplier, null=True, on_delete=models.SET_NULL) arrival_date = DateField(auto_now_add=True, null=True, blank=False) substrate = ManyToManyField(Substrate, blank=True) The Substrate and Supplier models, which are connected to Arrival and Supplier. class Substrate(models.Model): name = CharField(max_length=299, unique=True, null=True, blank=False) class Supplier(models.Model): name = CharField(max_length=299, unique=True, null=True, blank=False) The SupplierInfo model, from which supplier and its substrate should be filtered. Note: One supplier can have multiple substrates. Simply, filtering supplier returns multiple query set each with a different substrate (ForeignKey) name. class SupplierInfo(models.Model): supplier = ForeignKey(to=Supplier, on_delete=models.SET_NULL, null=True, blank=False) substrate = ForeignKey(to=Substrate, on_delete=models.SET_NULL, null=True, blank=False) mushroom = ForeignKey(to=Mushrooms, on_delete=models.SET_NULL, null=True, blank=False) weight = FloatField(null=True, validators=[MinValueValidator(0.9)],blank=False) yield_min = FloatField(null=True, validators=[MinValueValidator(0.9), MaxValueValidator(100)]) yield_max = FloatField(null=True, blank=True, validators=[MinValueValidator(0.9), MaxValueValidator(100)], ) status = BooleanField(null=True)