Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tools used to build Stack Overflow
Creating a blog site is difficult what should I use Django and heroki or what ?? What should a blog Site Contain ? Can I create an alternative to Stack Overflow -
hi i have problem with django and front_end
I want to build an online store and I want to enter the number of products that the customer wants to enter in the front and then send it to Django, for example, if he says 6 apples, I will change the number of apples to 6 in Django. -
Having a problem integrating this google calendar keep getting null setting src (Netsuite)
this is my code, and I am trying to be able to switch between different calendars. But it wont let me function googleCalendars(portlet, column) { var calendarSelect; portlet.setTitle("Sportex Calendars"); calendarSelect = portlet.addField("calendar_select", "select", "Select Calendar"); calendarSelect.setHelpText("Select a calendar"); calendarSelect.addSelectOption("humanresources", "Human Resources"); calendarSelect.addSelectOption("vacation", "Vacations"); calendarSelect.addSelectOption("appointments", "Appointments"); portlet.addField("calendar", "inlinehtml", "Some HTML").setLayoutType("outsidebelow", "startrow").setDefaultValue("" + "<div>" + '<<iframe src="https://calendar.google.com/calendar/embed?height=600&wkst=1&bgcolor=%23ffffff&ctz=America%2FPhoenix&showCalendars=0&src=c3BvcnRleGNhbGVuZGFyQGdtYWlsLmNvbQ&src=YWRkcmVzc2Jvb2sjY29udGFjdHNAZ3JvdXAudi5jYWxlbmRhci5nb29nbGUuY29t&src=ZW4udXNhI2hvbGlkYXlAZ3JvdXAudi5jYWxlbmRhci5nb29nbGUuY29t&src=aHQzamxmYWFjNWxmZDYyNjN1bGZoNHRxbDhAZ3JvdXAuY2FsZW5kYXIuZ29vZ2xlLmNvbQ&color=%23039BE5&color=%2333B679&color=%230B8043&color=%23B39DDB" style="border:solid 1px #777" width="1200px" height="600px" frameborder="1" scrolling="no"></iframe>' + "</div>"); portlet.addField("resizer", "inlinehtml", "CSS Overrides for Portlet Content Resizing").setDefaultValue("" + "<style>" + "ns-script-portlet-content-wrapper iframe," + "#main_form table, #cal_frame {" + "width: 100%;" + "}" + "</style>"); portlet.setScript("customscript_googlecalendar_client")} function fieldChange(type, name) { if(name == "calendar_select") { if(nlapiGetFieldValue("calendar_select") == "humanresources") { document.getElementById("cal_frame").src = "https://calendar.google.com/calendar/embed?src=833451c59dcb80fff2263f6cfb17fa5ae246b70d97588f1ef46ffbc04658433b%40group.calendar.google.com&ctz=America/Phoenix" }else { if(nlapiGetFieldValue("calendar_select") == "vacation") { document.getElementById("cal_frame").src = "https://calendar.google.com/calendar/embed?src=f61df42873f6d090babb273c46cd295f12795c08647b8c18088d25691cb653fb%40group.calendar.google.com&ctz=America%2FPhoenix" }else { if(nlapiGetFieldValue("calendar_select") == "appointments") { document.getElementById("cal_frame").src = "https://calendar.google.com/calendar/embed?src=clto48tqq2vmp19sfuqra8oprc%40group.calendar.google.com&ctz=America/Phoenix" } } }}nlapiResizePortlet()}; -
Always Defer a Field in Django
How do I make a field on a Django model deferred for all queries of that model? Research This was requested as a feature in 2014 and rejected in 2022. Baring such a feature, the obvious idea is to make a custom manager like this: class DeferedFieldManager(models.Manager): use_for_related_fields = True def __init__(self, defered_fields=[]): super().__init__() self.defered_fields = defered_fields def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs ).defer(*self.defered_fields) class A(models.Model): big_field = models.TextField(null=True) b = models.ForeignKey(B, related_name="a_s") objects = DeferedFieldManager(["big_field"]) class B(models.Model): pass class C(models.Model): a = models.ForeignKey(A) class D(models.Model): a = models.OneToOneField(A) However, while this works for A.objects.first() (direct lookups) and B.objects.first().a_s.all() (one-to-manys), it doesn't work for C.objects.first().a (many-to-ones) or D.objects.first().a (one-to-ones). An easy way to test this is to drop the field that should be deferred from the database, and the code will only error with an OperationalError: no such column if the field is not properly deferred. How do I make this field deferred for all ways this model is loaded (without needing to put a defer call on every query)? -
Django/python retrieving integer value from models.integerfield
class Trainingvalue(models.Model): maximalvalue= models.PositiveIntegerField(null=True,blank=True) How can I retrieve integer from maximal value , in order to use in a views.py function like to create another variable to render it to context dictionary ? -
django-filter IN lookup filter and list of strings
Using Graphene in Django to create Gql schema, now trying to filter Foreign Keys with list of strings. It kinda works, but not exactly. schema.py class CharInFilter(BaseInFilter, CharFilter): pass class ProductFilter(FilterSet): softwares__name = CharInFilter(field_name="softwares__name", lookup_expr="in") class Meta: model = Product fields = {"name": ["exact", "icontains"]} class ProductType(DjangoObjectType): class Meta: model = Product filterset_class = ProductFilter interfaces = (graphene.relay.Node,) query query authorPageProducts { user(slug: "john") { productSet(softwares_Name: "Blender") { edges { node { name softwares { name } } } } } } Here is what works and what not: softwares_Name: "Blender" -> correct softwares_Name: "Houdini" -> correct softwares_Name: "Blender,Houdini" -> empty result, not correct I am passing string separated with comma. Can/should I pass list of strings in Gql query? Im not sure if its possible/necessary. I do have Products that have both Foreign Keys with values "Houdini" and "Blender", so query with "Blender,Houdini" shouldn't be empty. I tried this query in shell, and its correct. Here I used list of strings. u = User.objects.get(id=2) p = u.product_set.filter(softwares__name__in=["Blender", "Houdini"]) Here is some info from Django Debug Toolbar, to see SQL expression for third case. SELECT COUNT(*) AS "__count" FROM "shop_product" INNER JOIN "shop_product_softwares" ON ("shop_product"."id" = "shop_product_softwares"."product_id") INNER JOIN "shop_software" … -
Unable to search from hacker news api django
I would like to search different items (jobs, stories, ask) from the hacker news api but I can't seem to figure out how to do it correctly, please check code below and tell me what I'm doing wrong as I'm unable to run it successfully. def search(request): if 'search' in request.GET: search = request.GET['search'] url = 'https://hacker-news.firebaseio.com/v0/item/{item-id}.json?print=pretty' response = requests.get(url) article_list = response.json() context = {} context['objects'] = [] for each_id in article_list[:10]: # Make a separate API call for each article. url = f"https://hacker-news.firebaseio.com/v0/item/{each_id}.json" # get response for individual articles response = requests.get(url) article_dict = response.json() context['objects'].append(article_dict) return render(request, 'SyncNews/search.html', context) {% for x in objects %} <h3 class="news-subheading">{{ x.title }}</h3> {% endfor %} <form method="GET" action="{% url 'search' %}"> <input type="text" name="item-id" placeholder="Search" /> </form> -
Default task list in new instance of 'To Do' app in Django
I am learning Django and creating ToDo app. I need to get a hint on logic how to implement default task list while user is creating a new record (instance) of ToDo app. Simply, I want to avoid hardcoding of any specific task list into the HTML, rather I want to have pre-populated (based on app specifics) model class (from Django Admin) which will be added to ToDo app instance during CreateView. Also I wish to implement 'add task' feature within the ToDo app instance i.e. add any extra task user wants on top of default tasks. Hope my question is clear. -
DRF return JsonResponse from another function
I am trying to return the JsonResponse from another function but I get the following error from DRF: AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> Here is my code class SignedURL(GenericViewSet): queryset = fileUpload.objects.all() serializer_class = fileUploadSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) function1(request) def function1(request): return JsonResponse( { "message": "Pass", }, status=status.HTTP_400_BAD_REQUEST, How can I return the JsonResponse from another function without writing return JsonResponse in the def create itself? Further clarification: I have ten different functions with ten different Jsonresponses. ie, function2,function3...function10. If for example, function 4 fails, I would like to return the JSON response immediately from that function and not to proceed further with the other functions within the create call. -
Problem while creating a mofelform and editing a particular field in the modelform
I am in a middle of a project. The problem is arising from here : class PatientCreation(forms.ModelForm): class Meta: model = Patient fields = ['user','contact'] dob = forms.DateField(widget=forms.SelectDateWidget(years=range(1960,2022))) Whenever i try to save the form by using the frontend its creating an error. The model for this form is : class Appointments(models.Model): doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) app_time = models.DateTimeField() diognoses = models.TextField(max_length=1000) prescriptions = models.TextField(max_length=250) class Meta: unique_together = ('doctor', 'patient', 'app_time') def __str__(self): st = (str(self.doctor.user.name)+str(self.patient.user.name)).lower().strip() return st I am not sure if i can even define a particular field in a model form or not else the widget is working fine. So how can I implement the logic such that I get the date time widget in dob field. Also how can i default the value of the user field as the currently logged in user. -
django app app crashing when opening on heroku
I'm trying to open my heroku app but i keep getting the 'heroku logs --tail' error. I checked the logs and the only error I can see is: 'ImportError: cannot import name '_sanitize_token' from 'django.middleware.csrf' (/app/.heroku/python/lib/python3.10/site-packages/django/middleware/csrf.py)' FYI, I had some issue with the _sanitize_token when trying to run my server with manage.py before deploying. I had to change some settings in tastypies authentication: original(wouldn't let me run server): from django.middleware.csrf import _sanitize_token amended(this let me run the server): import django.middleware.csrf Now, I don't know wether the error above is actually causing the crash or if i should be looking into this: at=error code=H10 desc="App crashed" TYIA for any help on this -
how to add django-database-size to django project view?
I am trying to use django-database-size to display mysql table sizes to django admin page. The project has very limited docs to how to add the view. Here is the repo: https://github.com/chrisspen/django-database-size All it mentions about adding the view: Install the appropriate view in /sql (currently only PostgreSQL and MySQL supported). -
Does foreign key have to be primary key in Django?
Can we use any other unique column as foreign key in django model? -
Integrity Error NOT NULL constraint failed even though I have set blank=True, null=True in my model
Im getting a NOT NULL constraint error in my code when trying to save my model form, even though the fields I have left empty are optional (have set blank=True, null=True) in models.py Im very confused, what am I doing wrong? The error is popping up when I leave the first optional field blank (description). Filling any of them manually before work.save() pushes the issue to the next field, and passes when all fields are filled. EDIT: this also happens when trying to create a work instance from the admin dashboard. models.py class Work(models.Model): ## core fields creator = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, default=None) created = models.DateTimeField() modified = models.DateTimeField() work_slug = models.SlugField(max_length=50) # slug -> TBD: find way to assign default value to slug = archival number. archive = models.ForeignKey(Archive, on_delete=models.CASCADE) # superfolder -> replaces category, series etc with dynamic hierarchical database folder = models.ForeignKey(Folder, on_delete=models.CASCADE) # basic metadata fields name = models.CharField(max_length=50) year = models.CharField(max_length=50) medium = models.CharField(max_length=50) description = models.CharField(max_length=1200, blank=True, null=True) # optional metadata authors = models.CharField(max_length=50, blank=True, null=True) classification = models.CharField(max_length=50, blank=True, null=True) location = models.CharField(max_length=50, blank=True, null=True) link = models.URLField(max_length=50, blank=True, null=True) record_creator = models.CharField(max_length=50, blank=True, null=True) # revisit -> # custom descriptors cd1_name … -
Connecting a Django App Deployed to IIS to a Sql Server Database
I'm currently having difficulties connecting my Django app to a SQL Server Database after I've deployed it to IIS. My current setting for the database is: DATABASES = { 'default': { "ENGINE": 'mssql', "NAME": 'databasename', "USER": 'myusername', "PASSWORD": 'mypassword', "HOST": 'host', "PORT": '', "OPTIONS": {"driver": "ODBC Driver 17 for SQL Server", "Trusted_Connection":'yes'}, }, } and with this setting, I keep getting the error message: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'myusername'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0); I've also tried using sql_server.pyodbc as the engine but also got the same error message. I was just wondering if there's anything else I would need to do for me to be able to connect my app to the database or if there's anything I would need to change in my current setting? -
Why django template not render tag after include tag
i consider that why template not render tag after {% include %}. when i put some tag like something in front of include tag, it work. But it not work if i try to put behind the include tag. :( in index.html <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'styles/main.css' %}" /> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"> </script> </head> <body> <div class="d-flex"> {% include 'navbar.html' %} <div class="content"> <div class="header"> {% include 'header.html' %} </div> <div> {% block subHeader %} {% endblock %} </div> <div> {% block list %} {% endblock %} </div> </div> </div> </body> </html> in list.html <table class="table"> <thead> <tr> <th scope="col">Cardinal Number</th> <th scope="col">ID</th> <th scope="col">Name</th> <th scope="col">Category</th> <th scope="col">Cost</th> <th scope="col">Note</th> <th scope="col">Image</th> <th scope="col">Action</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <th scope="row">2</th> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <th scope="row">3</th> <td colspan="2">Larry the Bird</td> <td>@twitter</td> </tr> </tbody> </table> in products.html {% extends 'index.html' %} {% block subHeader %} {% include 'components/subHeader.html' with url="api/add-product" name="product" selectName="product-category" %} {% endblock subHeader%} {% block list %} {% include 'components/list.html' %} {% endblock content%} although i put whatever after include … -
I need help adding word counter on the input text on a flask paraphraser app
I've gotten hold of an open source paraphraser project written in python and flask and need help in adding some functionality to it. I am totally new to the field so please overlook if i say something stupid, i was downvoted on the same question before. I've tried to look for a solution elsewhere on the web but couldn't find anything that helped. When i test the app on the local server, it shows a simple paraphrasing app with input and output boxes. It paraphrases the text but doesn't highlight the specific words and sentences that it rephrases in the output box. I wanna know adding what piece of code in the app file would achieve that. Additionally, i also want to add a word counter on the input text. The corresponding code for the template file would be a bonus, thanks! -
Django taggit query error: must be "model_name" instance
I have a very simple Photo class which uses django_taggit class Photo(models.Model): ... some other fields tags = TaggableManager(blank=True) Oddly enough, even simple query like this: blue_tag = Tag.objects.get(name='blue') q1 = Photo.objects.filter(tags=blue_tag) some_tags = Tag.objects.filter(name__icontains='b') q1 = Photo.objects.filter(tags__in=some_tags) will result in the following error.... Cannot query "blue": Must be "Photo" instance. Which is odd...given the fact that I'm passing Tag objects... -
Understanding Ubuntu storage
I have host with Ubunbu instance and in it I have docker containers with django project, postgres, cronjob and nginx. I'm checking the host disk with df -h and the output is this: Filesystem Size Used Avail Use% Mounted on udev 3.8G 0 3.8G 0% /dev tmpfs 777M 1.5M 776M 1% /run /dev/sda1 150G 42G 102G 30% / tmpfs 3.8G 0 3.8G 0% /dev/shm tmpfs 5.0M 0 5.0M 0% /run/lock tmpfs 3.8G 0 3.8G 0% /sys/fs/cgroup /dev/sda15 253M 1.1M 252M 1% /boot/efi overlay 150G 42G 102G 30% /var/lib/docker/overlay2/b4e1380fce967b0a51e9264582b5aca1ef489e7df77e15e7d44527d20c639e48/merged overlay 150G 42G 102G 30% /var/lib/docker/overlay2/108849a926d5a23bea24c0e9192d92e80db4257733948c4378546e9a466c1416/merged overlay 150G 42G 102G 30% /var/lib/docker/overlay2/e1840145e9fc846d78a661ea87044c4e5f30c12eadd0bf9a3eb6c7645f93f0ad/merged overlay 150G 42G 102G 30% /var/lib/docker/overlay2/aa03a83c65275cfc7b8909246937930046f6b8c7b8b20868f996804fcd282611/merged overlay 150G 42G 102G 30% /var/lib/docker/overlay2/e9fae8ab52b956cda4b9c5e14a21ee1976e9f684ead3134dae20d6c7b1df4f39/merged tmpfs 777M 0 777M 0% /run/user/0 When I export my data into csv, the csv file is not larger than 300MB. Can someone explain why I have 42G and what are those /var/lib/docker/overlay2/* files? -
Python Django {% if usuario.username == user %} not work :(
I need some help. I want to list all user avoid the login user. if I print user= juan if I print usuario.username=juan There have the same string {% if usuario.username == user %} Nothing {% else %} <tr><td> {{usuario.username}} <img src="{% static 'assets/img/icono_writeMSJ.png' %}" height="30px"> </td> </tr> {% endif %} if i change for example {% if usuario.username == 'juan' %} Nothing {% else %} <tr><td> {{usuario.username}} <img src="{% static 'assets/img/icono_writeMSJ.png' %}" height="30px"> </td> </tr> {% endif %} this work fine, why?? :( -
Selfjoin in Django to get list of combinations and their number
unfortunately I am missing the right idea right now, so I am trying my first post here: My model: class MyModel(models.Model): interesting_value = PositiveIntegerField() other_value2 = PositiveIntegerField() other_value3 = PositiveIntegerField() ... Now I want to do something like this in django: with query as (select interesting_value, other_value2, other_value3 from mymodel) select q1.interesting_value, q2.interesting_value, count(*) AS cnt from query q1 inner join query q2 on q1.other_value2 = q2.other_value2 and q1.other_value3 = q2.other_value3 and q1.interesting_value <> q2.interesting_value and q1.interesting_value < q2.interesting_value group by q1.interesting_value, q2.interesting_value; To get such an result which finds the number of pairs under the given conditions: q1.interesting_value, q2.interesting_value, cnt 1,4,2 1,9,3 1,38,1 1,100,1 How could I realize this selfjoin in Django without using pure SQL in my app? To get a idea of the question I want to answer, this example: How often is the combination of two of exams (=interesting_value) taken by one student (=other_value2) in one semester (=other_value3)? I would be really thankful for a little hint to the solution! Jan -
Combine Comodo SSL certificate
I have a Django website running Nginx on DigitalOcean. Now I have a certificate from Comodo. I have 4 files. AAACertificateServices.crt SectigoRSADomainValidationSecureServerCA.crt USERTrustRSAAAACA.crt mydomain.crt How do I combine these files and what do I need to do next? Because I get the error message: [emerg] 113128#113128: SSL_CTX_use_PrivateKey("/var/www/ssl/mydomain.key") failed (SSL: error:05800074:x509 certificate routines::key values mismatch) -
Function mixing up values of different model (within similar named fields)
Here is my search function def search(request): query = request.GET['query'] allPoststit = List.objects.filter(title__icontains=query) allPostscont = List.objects.filter(content__icontains=query) allPostsl = allPoststit.union(allPostscont) allPoststitm = MusicList.objects.filter(title__icontains=query) allPostscontm = MusicList.objects.filter(content__icontains=query) allPostsm = allPoststitm.union(allPostscontm) allPoststitb = BookList.objects.filter(title__icontains=query) allPostscontb = BookList.objects.filter(content__icontains=query) allPostsb = allPoststitb.union(allPostscontb) allPosts2 = allPostsl.union(allPostsm) allPosts = allPosts2.union(allPostsb) params = {'allPosts' : allPosts, 'query':query} return render(request, 'app/search.html', params) when from template im calling {% for tag in i.genre.all %} <div class="Genre"> <small>{{ tag }}</small> </div> {% empty %} No tags! {% endfor %} Its mixing up values within different models or returning empty. Any idea why is this happening? -
Trying to get API working on Django app I'm making whilst following a tutorial
Errors Recieved Hi, thanks for reading. So I'm following a tutorial from codewithmosh and I'm currently building the django app. Everything was going smooth until trying to get the API to work on it. The first thing I had to change was the 'from django.middleware.csrf import _sanitize_token' in the authentication file. After getting rid of that error I started getting the errors as shown in the attached picture. I am absolutely stumped. Any light that can be shone on my issue would be much appreciated. -
python test coverage cannot omit env/venv folder and throwing ERROR collecting env/Lib error
I have faced this issue when I am trying to test in a Django project from docker. Based on the instructions in the tutorial, I have implemented successfully black test and isort test successfully. However, when it comes t0 Pytest I am facing the aforementioned issue despite the fact that I have specified the exclusion of env files in my setup.cfg file using omit command of pytest-cov tool. Here are is my setup for setup.cfg file: [flake8] max-line-length = 119 exclude = .git,*/migrations/*,*env*,*venv*,__pycache__,*/staticfiles/*,*/mediafiles/* [coverage:run] source = . omit= *apps.py, *settings.py, *urls.py, *wsgi.py, *asgi.py, manage.py, conftest.py, *base.py, *development.py, *production.py, *__init__.py, */migrations/*, *tests/*, */venv/*, [coverage:report] show_missing = True The only variation between the youtube tutorial and my setup is that the Tutor create his virtual env using venv however I used env name. I have tested this but to no avail. Furthermore, pytest.ini file was set up like this: [pytest] DJANGO_SETTINGS_MODULE = real_estate.settings.development python_files = tests.py test_*.py *_tests.py Also, project.toml is set up like this: [tool.black] extend-exclude = ''' /( | env )/ ''' However when I run the test using the command: docker compose exec api pytest -p no:warnings --cov=. I am facing the following errors: ERROR collecting env/Lib/site-packages/social_core/tests/backends/test_twitch.py _ ERROR …