Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I still get You are seeing this page because DEBUG=True is in your settings file and you have not configured any URLs
thats my app urls from django.urls import path from . import views urlpatterns = [ path('', views.tasklist, name='tasks'), ] thats my projects urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('list.urls')), ] thats views urls from django.shortcuts import render from django.http import HttpResponse def tasklist(request): return HttpResponse('TO DO List') I tried a lot of things but none of them worked -
Django pk for not corresponded user
I got a school and many teachers. While one to many works for the user group I have a staff group which needs to see all teachers corresponding to their school. But while everything is connected via pk, the staff dont see any teacher bc they dont have a pk for that data, how is it possible to have pk data and also display all of it, while editing deleting is possible for staff WITH a pk so that the edited data is correct etc. -
How to use local sqlite on Heroku
I am trying to deploy a Django app on Heroku, but I want to use my local sqlite as the application DB and not postgres. I know that it sounds weird but that's what I need now. I am trying to understand how to not overwrite my DB settings and keep them pointing at my local sqlite and not to Heroku's postgres. Any idea? -
Send email with data of an incomplete Django ModelForm
I have a rather large Django ModelForm on my website. Some of my visitors claim that the form does not work. I assume that they missed a required field, but their browser somehow does not show them which field is missing. Therefore, I want to send an email to myself when users try to submit an incomplete form such that I can better understand what is going on. My idea was: def signup(request): if request.method == "POST": ... if form.is_valid(): # Save content else: # Form not valid but send mail send_mail(...) However, we never get to the else part when we miss a required field of the form as the browser handles this earlier (view jumps to the missing field and no POST request is made). Any ideas? Maybe additional Javascript on the submit button of the form? -
Label on radio select updates wrong object
In my project there is a form which is displayed beneath each object in a list. The objects in this case are ideas. The form is there to enable to user to rank each idea from 1 to 3. The form uses radio buttons with a little label beside it. It goes from "good" "so so" and "bad", where "good" is 1 and so on. Everything works as it should, except that when the label is pressed on any idea instead of the radio button. The first idea in the list is being updated, not the one the user intended to update. This is my form: class IdeaRankForm(forms.ModelForm): CHOICES = [ (1, 'Good'), (2, 'So so'), (3, 'Bad'), ] rank = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect(attrs={'onchange': 'submit();'})) class Meta: model = Idea fields = ['rank', ] I tried both this and this. Essentially the same suggestion but none of the suggested solutions solved my problem. Does anybody know how this can be solved? Is javascript needed in the template to solve this? Or is there any way where the label can be disabled and not being able to be pressed? -
django channel took too long to shut down and was killed
I'm having this error when refreshing or after disconnecting the WebSocket. In my consumer async def connect(self): await self.accept() while True: //some function// async def receive(self, event): print("Receive", event) await self.send({ "type": "websocket.send", "text": "From receive..." }) async def disconnect(self, event): print("Disconnect", event) await self.send({ "type": "websocket.close" }) -
Best framework for CURD operations - Django vs Flask vs FastAPI
Am in the process of building web frame work. The web application should retrieve the data from the database and display. As well as insert/ update process should also be supported from the front end. Am looking for a best python based web frame work, the requirement is pretty simple. Need an assistance to choose the right frame work. Django Flask FastAPI I have gone through all the documentations of these frameworks, each has its own limitations and functionalities. Any assistance will be helpful. -
I want to add range filter in django eg.(100-500)
I've applied django filters on my data but there is a data on which I want to apply range filter like a data between (100-1000). -
How to call call a static function from the same Model in the Model upon initialisation? DJANGO PYTHON
So long story short, I have a Car model and a CarVersion model and I want the user to have the ability to choose from the availble car versions saved in the database, through a html select field. I cannot understand how to dynamically generate the choices field from the CarVersion model. I have the function, but I cannot call it inside the Car model. Here is the code I have so far: class Car(models.Model): choices = get_choices() name = models.CharField(max_length=50, unique=True) version = models.ForeignKey(CarVersion, choices=get_choices(), on_delete=models.RESTRICT) @staticmethod def get_choices(): options = CarVersion.objects.all().values_list("pk", "name") try: if not options: return [(0, "No versions in database. Call your administrator.")] except ProgrammingError: return [(0, "No versions in database. Call your administrator.")] return [(1, "Test")] I want to call the function get_choices in version = models.ForeignKey(CarVersion, choices=get_choices(), on_delete=models.RESTRICT) but I don't know how to do that while the function is declared to the model. If I define it outside of the model, it works, but there must surely be a better way that im missing, rather than cluttering my models.py file with a bunch of model specific functions. P.S.get_choices is not finished but as soon as I can call it, I will deal with … -
Setting a project level django constant
In my application, there is one configuration I am setting in my db (let say buffer_radius) that is not going to change frequently. I want to set one constant BUFFER_RADIUS in Django so that every-time Django restarted/redeployed, the value of this constant set to buffer_radius. I want to do this to minimise db call. -
one-to-one relationship but of multiple types in Django
I'm creating an online shop with Django. I figured since there could be different types of item for sale that share some attributes and fields, I'd better make an Item Model and other models subclass it. So I now have an abstract Item model and some other models like Dress, Pants and shoes. Now I wanna have a new model (e.g. Comment) which should have a relationship with the Item model. But since Item model is abstract I can't do it. Is there way I could have a one to one relationship whose one side could accept different types? Some thing like this: class Comment(models.Model): item = models.ForeignKey(to=[Dress, Pants, Shoes]) -
Djongo DB of MongoDB crashed suddenly in Django
I was using MongoDB as my Backend Database which was working perfectly today until now!. I didn't make any changes, yet suddenly every time i run server, I get this error. can't even debug what's the issue here. I really haven't made any change in Django yet this is happening. please help me figure this out! Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Meraz\anaconda3\lib\site-packages\djongo\sql2mongo\query.py", line 808, in __iter__ yield from iter(self._query) File "C:\Users\Meraz\anaconda3\lib\site-packages\djongo\sql2mongo\query.py", line 166, in __iter__ for doc in cursor: File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\cursor.py", line 1238, in next if len(self.__data) or self._refresh(): File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\cursor.py", line 1130, in _refresh self.__session = self.__collection.database.client._ensure_session() File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\mongo_client.py", line 1935, in _ensure_session return self.__start_session(True, causal_consistency=False) File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\mongo_client.py", line 1883, in __start_session server_session = self._get_server_session() File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\mongo_client.py", line 1921, in _get_server_session return self._topology.get_server_session() File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\topology.py", line 520, in get_server_session session_timeout = self._check_session_support() File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\topology.py", line 504, in _check_session_support self._select_servers_loop( File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\topology.py", line 218, in _select_servers_loop raise ServerSelectionTimeoutError( pymongo.errors.ServerSelectionTimeoutError: ac-qk5nrrk-shard-00-02.bppaqzd.mongodb.net:27017: ,ac-qk5nrrk-shard-00-00.bppaqzd.mongodb.net:27017: ,ac-qk5nrrk-shard-00-01.bppaqzd.mongodb.net:27017: , Timeout: 30s, Topology Description: <TopologyDescription id: 62fd16f8972a661b8168f504, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('ac-qk5nrrk-shard-00-00.bppaqzd.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-qk5nrrk-shard-00-00.bppaqzd.mongodb.net:27017: ')>, <ServerDescription ('ac-qk5nrrk-shard-00-01.bppaqzd.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-qk5nrrk-shard-00-01.bppaqzd.mongodb.net:27017: ')>, <ServerDescription ('ac-qk5nrrk-shard-00-02.bppaqzd.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-qk5nrrk-shard-00-02.bppaqzd.mongodb.net:27017: ')>]> The above exception was the … -
How can I update my data table in page without refreshing page when I do db changes?
[NOTE] I'm really new to web development. I'm trying to figure out how to make things. Sorry about that with basic questions. But I'm totally lost. That's why I'm asking. I'm trying to update my data page without reloading. I have to do this with AJAX, but most of examples about clicking the button and adding or updating the table. I don't want to create button, I want to reload with adding new record in database. I'm using Django, when I add new blog post in admin page for example, I want to see this blog post in my page without refreshing or clicking any button. Do I have to write API for this? How can I write this API for watching db? Do you have any resources with this? Thank you for your answers. -
django 4.1 tutorial how to change the link on the admin page header from http://localhost:8000 to http://localhost:8000/polls/
In the Admin pages of the Polls Tutorial there is a link to "View Site" that has the URL http://localhost:8000/ but it should be http://localhost:8000/polls/ to list the polls in the indexView class. I could not find where to change that View Site link. Right now with the Polls Tutorial done and all working except this last little bit I want to get it done to use as a reference. http://localhost:8000 now gives... Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: polls/ admin/ The empty path didn’t match any of these. -
How to create an Excel sheet using xlwt in django
I want to create an excel file like below.But I do not know , how to implement it.Excel sheet contains headers,sub headers and sub-sub headers. Actually the excel sheet is generated based on the from date and to date.If there is three months between from date and to date,these three months should be shown as columns in the excel sheet. from_date = request.POST.get('f_date') to_date = request.POST.get('t_date') file_name = "Report" content_disposition = 'attachment; filename="' + file_name + '.xlsx"' title = str(file_name) + " {} TO {}".format(from_date, to_date) header = ['Plant Locality', 'Plant', 'Product', 'UOM', 'Previous Year FTP', 'Previous Year YTP'] Can anyone suggest a solution to create this excel sheet using xlwt? -
Django OneToOneField - Add to parent or Child?
What is the proper way to add a OneToOneField in Django? Does it go in the parent class or child class? The official docs don't really explain this. Which way works better with the built-in admin interface? Does it matter? Is there a convention? What is the "correct" way? class Client(models.Model): name = models.CharField(max_length=30) portfolio = models.OneToOneField(to="Portfolio", null=True, on_delete=models.CASCADE) class Portfolio(models.Model): ... portfolio fields ... or class Client(models.Model): name = models.CharField(max_length=30) class Portfolio(models.Model): client = models.OneToOneField(to="Client", null=True, on_delete=models.CASCADE) ... portfolio fields ... I see most examples add it to the child, but it seems adding it to the parent works better with the admin interfaces and makes more sense logically. -
Updating Django ORM with filter is updating unexpected fields
I have a very simple DjangoRestFramework api_view where i am grabbing an id and filtering a queryset by that id and a start date greater than today. My Model is pretty simple, it has a patient (FK), is_cancelled (boolean), start (Datetime) and end (Datetime). The issue is that when i run the below update, it is setting the start date to the date and time that i run this view. @api_view(['POST']) def BookingCancelAppointmentsView(request): if request.method == 'POST': patient_id = request.data today = date.today() bookings = Booking.objects.filter(patient=patient_id, start__gte=today).update(is_cancelled=True) return Response({'message': 'Appointments cancelled'}) so for example, if find an entry that is greater than today for that patient_id, it does update the "is_cancelled" field for the correct record but it is setting the Start datetime from whatever datetime i had in there originally to the date.today() value even though i am only updating the "is_cancelled" field. Does anyone have any idea why it would touch the "start" field at all and how i might get around this issue? Software Versions: Python Version: 3.10.5 Django Version: 3.2.15 Django Rest Framework Version: 3.13.1 -
use postman to test websocket showing 403
I wrote a demo like channels' document(https://channels.readthedocs.io/en/stable/tutorial/index.html).But when I used postman to test websocket, it showed Error: Unexpected server response: 403. I just wrote an adress, someother should I have to set? -
How to visualize MySQL data with python web development modules
I have a requirement to visualize Linux servers patching status. So I added the patching status into MYSQL but still I want to visualize those data on web using python. I want to visualize the data on the web page from MySQL table using python web development I am trying to provide visibility to everyone in the project can find the details simply accessing the website. -
Python/Django f-strings interpreting a string as input
Running out of ideas where to look. I am trying to set up a string that can be edited outside my code and stored by the user and have that string feed into an f-string inside my code. Example: Take the following value that is stored in database CharField: Hello {user}! How are you? I want to grab that and feed it into Python to treat as the content of an f-string such that: >>> user = 'Bob' >>> stringFromOutside = 'Hello {user}! How are you?' >>> print(f'{stringFromOutside}') Hello {user}! How are you? prints "Hello Bob! How are you?" I oversimplified for the example, because that's the core of where I'm lost. I have tried nesting the {stringFromOutside} in a second f-string, but that doesn't work. I have also tried double {{user}} inside the template file, but that did not work. Use Case in case I'm just being obtuse and doing the whole thing wrong I have an application that I want to expose to the administrator the ability to write templates and save them in the database. The templates need to be able to pull from several different objects and all the properties of those objects, so it would … -
Django DeleteView success_url to previous/different page
I have these url patterns: app_name = "posts" urlpatterns = [ path('global/', PostListView.as_view(), name='global-list'), path('personal/', PersonalPostListView.as_view(), name='personal-list'), path('<int:pk>/', PostDetailView.as_view(), name='detail'), path('<int:pk>/delete/', PostDeleteView.as_view(), name='delete'), ] Inside each of the templates of PostListView, PersonalPostListView, and PostDetailView is a delete option like this: <a href="{% url 'posts:delete' object.id %}">Delete</a> What I want to happen is after deleting the object, it will redirect to the last page where the delete link was clicked (except for detail view). Thus, there are 3 possible cases as follows: Case 1: PostListView template -> click delete -> PostDeleteView confirm delete template -> back to PostListView template Case 2: PersonalPostListView template -> click delete -> PostDeleteView confirm delete template -> back to PersonalPostListView template Case 3 (the exception): PostDetailView template -> click delete -> PostDeleteView confirm delete template -> back to PostListView template This is my attempt so far: class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post def get_success_url(self): return self.request.META.get('HTTP_REFERER') However, clicking delete from the PostListView returns posts/15/delete/ which should just be posts/global/. Moreover, it should return posts/personal/ if deleted from PersonalPostListView template and (the exception) posts/global/ if deleted from PostDetailView template. An alternative I've thought is to assign different DeleteViews (with different success_url) for each template. However, this … -
django web project - connected with https. Forbidden (403) CSRF verification failed
There was no problem when connecting to the http server. If you log in from the web server after connecting to https, the following error works: In login.html {% csrf_token %} is written Forbidden (403) CSRF verification failed. Request aborted. More information is available with DEBUG=True. Is there any way to enable this when DEBUG= False? -
How to render filtered data using django and ajax
I'm very much new to AJAX and JQuery. So, my problem is: I want to show a filtered list of a django model called "Recipe" when a user clicks on a checkbox but I don't know how to pass in the data in ajax so that it reloads it correctly for example: I have a Recipes List in my home page which displays all the recipes and right next to it is a filter sidebar where a user can check multiple checkboxes in multiple categories to filter the data according to the input. But I don't know how to pass the data in the views so that ajax loads it into the page. Any help would be appreciated! Here's my code: views.py # filter recipes def filter_recipes(request): print(request) recipes = Recipe.objects.all() diff = request.GET.getlist("difficulty[]") if len(diff) > 0: filtered = recipes.filter(difficulty__in=diff) print(f"recipes =============== {filtered}" ) ajax = render_to_string("ajax/recipes_list.html", {"data": filtered}) return JsonResponse({"data": ajax}) <!-- JQuery script in landing_page.html--> <script> $(document).ready(function () { $(".ajax-loader").hide(); // start of filter by value $(".form-check-input").on("click", function () { let _filterObj = {}; $(".form-check-input").each(function (index, element) { let _filterValue = $(this).val(); let _filterKey = $(this).data("filter"); _filterObj[_filterKey] = Array.from( document.querySelectorAll( "input[data-filter=" + _filterKey + "]:checked" ) ).map(function … -
Unexpected behavior with Django migrations when trying to leverage MSSQL schemas
I currently maintain a Django project that uses a Postgres database and follows the principles in this article to leverage multiple schemas. This keeps all the tables nice and namespaced. I have a 'core' app, where I have defined a base model that has a couple foreign keys to my custom 'Auth' model. These fields are '_created_by' and '_last_updated_by'. Every model in every other app inherits from this model, and as a result every table in every schema has a foreign key relationship with my custom 'Auth' model. When using Postgres, I can migrate my custom 'Auth' app, and it creates all the necessary tables in the default 'public' schema. And then I can do: python manage.py migrate app --database=app_db for my other apps, and the relevant tables get created in the correct schema. (I have created the schemas beforehand, django does not do that for you) This is perfect. However recently it has become apparent that my life would be easier were we to use MSSQL for the backend. After some work, everything almost works, however when I migrate an app using the above command, it creates duplicate 'Auth' tables in the app schema. So now I have a … -
Hi everyone I'm struggling with a for loop in attempt to make a categories filter (Django - Bootstrap)
Like the title say's I have a problem trying to make a categories filter, already did one for my Blog because only has a couple of categories without subcategories, but this one is different because it has categories and subcategories with one to many fields and already tried multiples approaches but I couldn't make it work. I would be glad if someone lend me a hand. This one was my last attempt, I tried to make it like my other less complex categories filter. Store unique html template. <section class="page-section cta rounded p-6 p-md-5 m-md-4 text-center bg-light"> <div class="container"> <div class="row"> <div class="col-xl-9 text-center mx-auto"> <h2 class="section-heading mb-4"> <span class="section-heading-lower">Horizontal</span> </h2> <div style="padding-bottom: 1%; padding-top: 3%;"> <h4><span class="section-heading-upper">CATEGORIAS: </span></h4> {% for itemWide in itemsWide %} {% for category in itemWide.categories.all %} <a type="button" class="btn btn-dark" href="{% url 'storePacks' %}"> <span class="section-heading-upper" style="font-size:small;">{{category.name}}</span> </a> {% endfor %} {% endfor %} </div> </div> </div> </div> </section> Store model class ItemCategory(models.Model): name = models.CharField(max_length=50) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now_add=True) class Meta: verbose_name = 'itemCategory' verbose_name_plural = 'itemsCategories' def __str__(self): return self.name class SubCategoryVert(models.Model): parentCategory = models.ForeignKey(ItemCategory, on_delete=models.CASCADE) name = models.CharField(max_length=50) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now_add=True) class Meta: verbose_name = 'SubCategoryVert' verbose_name_plural …