Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I change the value of a Django Model field via a template function based view in django
I have a django function based view, inside it a I have a checklist of checkmarks and some text, when I tap one I want the database to update, how do I accomplish this? Note that I don't have made any efforts yet to change the value and I hope someone here can help me with that! @login_required def detailStudyplanPage(request,pk): username = request.user tks = Task.objects.filter(studyplan__id=pk) object = get_object_or_404(Studyplan,pk=pk) return render(request, 'detailStudyplan.html',{'object':object, 'MyName': username, 'tasks': tks}) class Checker(models.Model): name = models.CharField(max_length=100) checked = models.BooleanField(default=False) sender = models.ForeignKey(UserProfile, blank=True, on_delete=models.CASCADE, related_name="person_who_checks_checker") canview = models.ManyToManyField(UserProfile, blank=True, related_name="can_view_checker") <div> <div class="progress"> <div class="progress-bar bg-success" style="width:42%;"></div> </div> <div class="d-flex justify-content-between text-small"> <div class="d-flex align-items-center"> <i class="material-icons">playlist_add_check</i> <span>3/7</span> </div> <span>Ska vara färdig {{task.deadline}}</span> </div> </div> -
'ManagementForm data is missing or has been tampered with' Django
I have created a formset for users to add and remove forms as necessary using Django's empty_form and jQuery. However, when the form is submitted I am being thrown a validation error. I have initialized the ManagementForm, so I am not sure as to what the issue is. Any help would be greatly appreciated. views.py def presales(request): PresalesFormSet = formset_factory(PresalesForm, extra=1, can_delete=True) if request.method == 'POST': presales_formset = PresalesFormSet(request.POST) if presales_formset.is_valid(): selected_opportunity = request.POST.get('selected_opportunity') for presales_form in presales_formset: task_description = request.POST.get('task_description') hours = request.POST.get('hours') obj = Presales() obj.opportunity = selected_opportunity obj.taskDescription = task_description obj.hours = hours obj.save() else: presales_form = PresalesForm() presales_formset = PresalesFormSet() context = {'presales_formset': presales_formset, 'presales_form': presales_form, 'my_opportunities': my_opportunities} return render(request, 'website/presales.html', context) template.html {{ presales_formset.management_form }} <form action="{% url 'presales' %}" class="presales_formset" data-total-url="{% url 'presales_total' %}" id="presalesForm" method="post" name="presalesForm"> <div class="field"> <label class="label is-large">High Level Task List</label> </div> {% csrf_token %} {% for presales_form in presales_formset.forms %} {{ presales_form.field_errors }} {{ presales_form.errors }} </form> {% endfor %} <div id="empty_form" style="display: none;"> {{ presales_formset.empty_form }} <form action="{% url 'presales' %}" class="presales_formset" data-total-url="{% url 'presales_total' %}" id="emptyPresalesForm" method="post" name="presalesForm"> {% csrf_token %} </form> </div> forms.py # special field names TOTAL_FORM_COUNT = 'TOTAL_FORMS' INITIAL_FORM_COUNT = 'INITIAL_FORMS' MIN_NUM_FORM_COUNT = 'MIN_NUM_FORMS' … -
How to implement a customized HTML template for user signup form in Django?
Goal is to implement a customized HTML template, that I've already created, for user signup form in Django. I've looked at {{ form.as_p }} and crispy forms, but these options do not seem to allow me to space different fields at different lengths in the html. Such that First Name field and Last Name field are on row 1, email address completely takes up row two, and the two password fields are on the same row. -
django return querylist instead of one item query
I am querying in django models with filter but Instead of finding list of query I want django to return one query product = Product.objects.filter(slug=slug) it return <QuerySet [<Product: Product object (2)>]> instead I want something like this <Product: Product object (2)> so I can access fields of that objects like product.price -
Django Admin shows my foreignkey to intermediary model as a text input
In my models.py I have a intermediary model for a ManyToMany relation between model A and B. And MyModel has a ForeignKey to that intermediary model. When I register MyModel in admin.py the foreignKey shows as a text input: I don't understand why it doesn't show the default foreignKey widget. This is my models.py: # This is a intermediary model from another relations class InterModel(models.Model): a = ... b = ... class MyModel(models.Model): psv = models.ForeignKey('InterModel', related_name='mymodels') In my admin.py: admin.site.register(models.MyModel) I use Django 1.7 Thank you! -
Date error in publishing a post on django-app?
I'm making a django blog app in which a user can create a post and then publish it. But I'm not getting the exact date when the post was published it is showing a different date. I'm publishing the post on 3-september and date I see is 9 september. However the time is correct but date is not Here's my models.py file from django.db import models from django.urls import reverse from django.utils import timezone from django.contrib.auth.models import User from datetime import datetime, timedelta from PIL import Image class Post(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() create_date = models.DateTimeField(auto_now_add=True) published_date = models.DateTimeField(blank=True) objects = models.Manager() comments = models.Manager() def publish(self): self.published_date = timezone.now() self.save() def approve_comments(self): return self.comments.filter(approved_comment=True) def get_absolute_url(self): return reverse('blogapp:post_detail',kwargs={'pk':self.pk}) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey('blogapp.Post', related_name='comments', on_delete=models.CASCADE) author = models.CharField(max_length=100) text = models.TextField(max_length=264) created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def get_absolute_url(self): return reverse('blogapp:post_list') def __str__(self): return self.text Here's my settings.py file import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') MEDIA_DIR = os.path.join(BASE_DIR,'myblog/media') SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'blogapp.apps.BlogappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] … -
Django "models1.foreignkey" must be a "models2" instance
Cannot assign "<QuerySet [<authentifier: authentifier object (1)>]>": "Resasalle.authentifier" must be a "authentifier" instance. models.py : class authentifier(models.Model): matricule =models.CharField(max_length=254, blank=True, null=True) password = models.CharField(max_length=254, blank=True, null=True) nom =models.CharField(max_length=254, blank=True, null=True) prenom=models.CharField(max_length=254, blank=True, null=True) statut = models.CharField(max_length=254, blank=True, null=True) class Resasalle(models.Model): idrs = models.AutoField(primary_key=True) nomsalle = models.CharField(max_length=254, blank=True, null=True) motifresa = models.CharField(max_length=254, blank=True, null=True) datedebut = models.DateField(blank=True, null=True) heuredebut = models.TimeField(blank=True, null=True) heurefin = models.TimeField(blank=True, null=True) authentifier = models.ForeignKey(authentifier,on_delete=models.CASCADE , default="") views.py : def reserversalle(request , id): form= ReserverSalle(request.POST or None) object = models.authentifier.objects.filter(id=id) print(object) if form.is_valid(): print("gooddd") reserver = models.Resasalle() reserver.nomsalle = form.cleaned_data['nomsalle'] reserver.motifresa = form.cleaned_data['motifresa'] reserver.datedebut = form.cleaned_data['datedebut'] reserver.heuredebut = form.cleaned_data['heuredebut'] reserver.heurefin = form.cleaned_data['heurefin'] reserver.authentifier = object reserver.save() context= { 'form' : form , } return render(request,'registration/reserversalle.html', context) reserversalle.html : resrver salle ! <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="reserver"> </form> hello all i need to save this form at my database but i received this error please if any one know how resolve this i try to add this form at my database -
Django, forcing reload of css/js, and collectstatic
Let's say that I've done a good bit of update to my css files on my dev machine (with my browser set to ignore the cache, no always seeing updates right away). In this question and other places, I've seen the approach of adding a version number to the links: <script src="/mystyles.css?version=4"></script>, which is fine, but on the dev machine, I get an error in the console, and the file isn't found: GET http://127.0.0.1:8000/path/mystyles.css%3Fversion%3D2 net::ERR_ABORTED 404 (Not Found) I've read that perhaps collectstatic will fix it on the dev side, but there's an ominous-looking warning: You have requested to collect static files at the destination location as specified in your settings: /patttthhhhh/static This will overwrite existing files! Are you sure you want to do this? What will happen when I run collectstatic? Where will it get files from to overwrite those? -
How to connect a completed Vue.js app (frontend) to Django (backend)
I'm currently doing a school project that tasks us to create a functioning web application (with database) for our university. Our application is an intranet-based activities logging system. During our first term, we finished our frontend via Vue.js / Vuetify. It has complete routers (and multiple pages), functioning buttons and data-tables (and fake authentication). Now, we need to connect it to the backend. We chose python django REST API as our research found that it would be faster to implement (our deadline is in 2 weeks tops). My question is how to (or if it's possible) to connect our vue.js application to django so that it can fetch login authentication and database queries to our SQL (postgreSQL). We were using the Vue CLI during the building of our frontend. Thank you! -
How to use django channels to stream a script output in real-time?
I am using django to run a python script. Ideally, I would like to redirect the shell output to a webpage and I am using django-channels to this aim. I am trying to call a view that runs the script asynchronously (using Celery) and then returns an HttpResponse to an html page. On this html page a javascript code opens a websocket and waits for messages to come from the script task. Currently the script runs properly in background and the websocket connection is established. I cannot see the output on the webpage, though. views.py: def main_view(request): res = script_task.delay() client = redis.Redis(host="localhost", port=6379, db=0) return render(request, 'run_channels.html') tasks.py: @shared_task def macch_main_chan(): layer = get_channel_layer() async_to_sync(layer.send)('out', {'message': 'test'}) print('Done!') return HttpResponse() routing.py: from . import consumers from django.urls import path websocket_urlpatterns = [ path('ws/outputmacch/', consumers.PushNotification, name='out'), ] consumers.py: class PushNotification(WebsocketConsumer): http_user = True def connect(self, **kwargs): self.accept() def receive(self, text, **kwargs): async_to_sync(self.channel_layer.send)( "out", { "text": text, }, ) def disconnect(self, message, **kwargs): pass run_channels.html: <html> <head> <meta charset="utf-8"/> <title>Run</title> </head> <body> <textarea id="log" cols="100" rows="20"></textarea> </body> <script> var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/outputmacch/'); chatSocket.onmessage = function(e) { console.log(e) var data = JSON.parse(e.data); var message = data['message']; … -
Django Alter commandline filter to use in project
So since i've been trying to learn django there is one thing that confuses me more than anything else, and that is getting something that works in the django shell into a format that works in models.py of views.py. So here is an example from the Documentation: >>> Entry.objects.all().filter(pub_date__year=2006) So I can work with the shell, there are loads of examples everywhere, what never seems to be covered is how you then put this in your code if you want to filter for other years for example. Can someone explain this or point me at documentation that explains this, as I've not found it in the django docs. -
Integrating a teradata database with django models framework
We have an external teradata reporting database which we want to create a frontend for generating and querying using django. I've gotten relatively far on just using a direct ODBC connection to the DB and running queries and displaying them on the website, but the further I get into it the more evident it is becoming that I really need to be using the django models framework. My question is does anyone have any experience or insight in how to integrate a teradata database into a django web app? For instance, I am displaying data using django-tables2 as it allows the tables to be generated not only using a queryset, but also a list of dictionaries which works great for me. Now I have come to adding filtering using django-filters package, and it seems it can only be done using an queryset object and nothing else. Would be grateful for any advice you may have to offer! -
Custom dropdown for Foreignkey
Python 3.6 ; Django 2.2 In the django-admin add or change object forms we have dropdown fields for ForeignKeys; This is well, but when you try to search an input from this dropdown we have to press keys very fast to not loose previous input; For example having: class PC: ..... location = models.ForeignKey('Locations', on_delete=models.PROTECT) we get in add/change form: where for search in this dropdown is needed to type fast '1-9-07', (if not fast you will get search from beginning for each character) So the question is: There is any way in django-admin to get this search delay more than 1 second for example to set it for 5 seconds interval between any input? Or to get something like this: So the search input will not be reset, until you not reset it manually. (this example is not from django) -
DRF: Aggregate similar entries name
I want to aggregate fields that has same name. I want to add their cost and their average percent. I've seen examples of aggregation but I don't see examples that aggrregate same entries with same fields and aggregate one of their fields. In this example, I want to get the total_cost and average_pct of entries that have the same project name. Suppose: # models.py class Project(models.Model): project = models.CharField(max_length=200) subproject = models.CharField(max_length=200) physical_pct = models.FloatField() cost = models.FloatField() # serializers.py class ProjectSerializer(serializers.ModelSerializer): total_cost = serializers.SerializerMethodField() average_pct = serializers.SerializerMethodField() class Meta: model = Project fields = '__all__' # views.py class ProjectsViewSet(viewsets.ModelViewSet): serializer_class = ProjectSerializer def get_queryset(self): financial_report = Project.objects.all() return financial_report If I have 3 entries: [ { "project": "Project-X", "subproject": "Subproject-1", "physical_pct": 58, "cost": 1000.00 }, { "project": "Project-X", "subproject": "Subproject-2", "physical_pct": 100, "cost": 2000.00 }, { "project": "Project-Y", "subproject": "Subproject-1", "physical_pct": 73, "cost": 560.00 } ] My desired output: [ { "project": "Project-X", "average_pct": 79, "total_cost": 3000.00 }, { "project": "Project-Y", "average_pct": 73, "total_cost": 560.00 } ] I am not sure where to begin. I want to place it on the serializers rather than getting querysets on the viewsets since I would be adding filters on them on the … -
How to generate a custom link in Wagtail using Wagtail hooks
So I want to add a extra link in the Wagtail admin. I am following the docs (Register Admin Menu Item Hook) and using this hook to contruct a new menu item. They use this hook for adding menu items: @hooks.register('register_admin_menu_item') def register_edit_menu_item(): return MenuItem('Edit profile', 'edit_link', classnames='icon icon-folder-inverse', order=10000) This should become a link which starts editing a page that is owned by the current logged in user. In a template I use this code to create a direct link to edit the profile of a user: {% with request.user.owned_pages.all as pages %} {% if pages.exists %} {% for p in pages %} {% if p.get_parent.id == 17 %} <a class="list-group-item" href="/dashboard/pages/{{ p.id }}/edit/"><i class="fe-icon-edit mr-1 text-muted"></i>Edit profile</a> {% endif %} {% endfor %} {% endif %} {% endwith %} This is working just fine, it links directly to the page that it is supposed to link to. However how do I implement a condition like this where I generate the menu link based on the current logged in user? I would think something like: if request.user.owned_pages.exists(): for p in request.user.owned_pages.all(): if p.get_parent.id == 17: edit_link = "/dashboard/pages/" + p.id + "/edit/" But how can I implement something like … -
The HTML file changed on server is not reflected
Deployed django project using DigitalOcean. After confirming with the server IP address, the site was displayed. However, there is a part that I want to modify, and the template folder of django is HTML I edited some. And even after checking nginx after reloading, it was not reflected. However, the cause is unknown because of the first deployment. I would like to ask about this cause. Does that mean that the displayed HTML is not a template folder display? I would like to know how to fix it. -
subtracting total budget with total expense
models.py class Add(models.Model): budget = models.IntegerField(blank=True, null=True) date = models.DateTimeField(auto_now=False, auto_now_add=False, blank=True) expense = models.IntegerField(default=0) Views.py def home_page(request): bud = Add.objects.aggregate(Sum('budget')) exp = Add.objects.aggregate(Sum('expense')) context = {'bud':bud, 'exp':exp,'budexp':budexp} return render(request, 'home.html', context,) I want to subtract total of bud and total of exp (bud - exp) how could i do this. -
django redirect is applied to all projects directly
I was studying mozilla django tutorial and in between that I came across one point where I have to redirect the url ' ' to '/catalog/' with permanent = True. Now I have one new project (another project in different directory ) with django-admin and gave the command of manage.py runserver (notice I haven't made any changes in this project) the url '' is automatically being redirect to '/catalog/' in chrome it works fine in opera mini though. -
super of equal methods in classes with multiple inheritance
I have a class that inherits from two others and I want to get the return of the method called "render" that both have this method -
Value is not being parsed to function view
I'm following this example in django docs: from django.urls import path from . import views urlpatterns = [ path('articles/2003/', views.special_case_2003), path('articles/<int:year>/', views.year_archive), path('articles/<int:year>/<int:month>/', views.month_archive), path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail), ] I've got this dynamic url pattern: path('interface/<str:name>/<str:issue>/', interface, name='interface'), Passing value like this: {% for issue in issues %} <a href="{% url 'interface' name=project.key issue=issue.key %}">{{ issue.name }}</a> {% endfor %} Function-based view is instructed to accept both argument with None by default: def interface(request, name=None, issue=None): print(name, issue) By doing the above I can see that name is being parsed but issue isn't and consequently results in error. I checked and issue.key in the anchor tag holds correct value. What can I do ? -
Django - possible to retry any DB operation on failure?
We are having issues recently with our prod servers connecting to Oracle. Intermittently we are getting "DatabaseError: ORA-12502: TNS:listener received no CONNECT_DATA from client". This issue is completely random and goes away in a second by itself and it's not a Django problem, can replicate it with SQLPlus from the servers. We opened ticket with Oracle support but in the meantime i'm wondering if it's possible to simply retry any DB-related operation when it fails. The problem is that i can't use try/catch blocks in the code to handle this since this can happen on ANY DB interaction in the entire codebase. I have to do this at a lower level so that i do it only once. Is there any way to install an error handler or something like that directly on django.db.backends.oracle level so that it will cover all the codebase? Basically, all i want to do is this: try: execute_sql() catch: if code == ORA-12502: sleep 1 second #re-try the same operation exexute_sql() Is this even possible or I'm out of luck? Thanks! -
WSGI/Nginx/Internal server error arises when I deactivate virtual environment (no python application found)
I'm stuck with this error. -— no python application found, check your startup logs for errors —- Internal server error. Whenever I'm in virtual environment all works fine but If I deactivate virtualenv I'm constantly getting this error each time when I send a GET query to my webpage. So because of this problem Im getting this error in supervisor mode. I have tested this outside of supervisor mode using this command: uwsgi —ini my_site_uwsgi.ini And like I said before It works fine when I'm in virtualenv and It raises error listed above error when I deactivate virtualenv. #codepaint_news_uwsgi.ini [uwsgi] chdir = /home/django/codepaint module = codepaint.wsgi home = /home/django/venv master = true processes = 10 socket = /home/django/codepaint/uwsgi_nginx.sock chmod-socket = 666 vacuum = true env = DEBUG_MODE=False _____________________________________ #wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "codepaint.settings") application = get_wsgi_application() ______________________________________ Internal server error. -— no python application found, check your startup logs for errors —- -
After upgrade django to 2.2, Unit tests fail because django no creating database tables
After upgrade successfully my project from Django 1.8 to Django 2.2.4, running the tests failing because Django does not create the database tables. after debugging the Django db/backends its look like the connection got created, but the tables aren't. my suspicious is that I didn't configure correctly something in the test_settings configuration file although I copied from my production setting file everything except the database configuration that I remain the SQLite in the test setting file database configuration: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test_database' } } INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'my_app', 'mptt', 'corsheaders', # audit app 'easyaudit', 'kronos', 'django.contrib.admin', ] The traceback that I'm getting (here it's, for example, the auth_user, but it reproduce for all the tables the same): Traceback (most recent call last): File "C:\Users\owner\Desktop\workspace\my_project\MyProject\services\tests\test_logging.py", line 33, in setUpClass cls.user = User.objects.get_or_create(username='logging_test_user', password='test_password') File "C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\models\query.py", line 538, in get_or_create return self.get(**kwargs), False File "C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\models\query.py", line 402, in get num = len(clone) File "C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\models\query.py", line 256, in __len__ self._fetch_all() File "C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\models\query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\models\query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File … -
Bootstrap Search Box uses the wrong url
This my first post in stackoverflow and I am pretty new to Bootstrap and Django and probably it is a silly thing but I could not find the solution. SearchBox on Bootstrap navbar does not go to the correct url. I am trying to add a search engine by using ListView on my test project. If I use the simple html search form, it works, it uses correct url (http://127.0.0.1:8000/crmapp/search/?q=SearchedText) and brings the results from database. However, if I use the searchbox which is on my NavBar (Bootstrap4), it does not go to the correct url and does not bring anything. On my browser I see that it is going to http://127.0.0.1:8000/?q=SearchedText. Other links on my navbar are working fine. I dont know if it is related but If I extend the ListView templates to base.html, they don't show even simple html. When I remove {% extends 'base.html' %}, the page diplays the content fine. **base.html** <!--Navbar Starts Here--> <nav class="navbar navbar-expand-lg navbar-light bg-light mb-4"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'home' %}">Home <span class="sr-only">(current)</span></a> </li> <li … -
Django authentication on IIS
I have a Django application deployed in IIS 8. And I cannot login to Django Admin (http://mysite/Admin). The Admin login comes up and says: InterfaceError at /admin/login/ ('28000', "[28000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed for user '*******'. (18456) (SQLDriverConnect); Has anyone come across this and figured out a way around it?. by the way this authentication works well in the dev environment.