Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get and assign elements in variables from a Nested List in Python
i'm working with a nested list in python like this list[[a,b,c,d,e],[a,b,c,d,e]] every element is composed ever of 5 parts, the content of the list can change in amounts of elements it can be from 1 to 10 elements max. Here came the difficult for me, cause I need to assign any part of every element into one individual variable, and when the element end, move to the next element,but before move send variables to one function that insert data in the oracle database. It is a part of a function in python django web app. The idea is to separate the data received in form a list after that send it to a stored procedure. This is part of the code. enter code here acomp = '' acomp = request.POST.getlist("acomp") split_strings = [] #Here divide the list in 5 parameters that are the rows of the table in #oracle n = 5 for index in range(0, len(acomp), n): #Creamos una lista anidada para dividir los datos de los acompañantes por cada uno split_strings.append(acomp[index : index + n]) #ow I can seperate the data assign every element into a variable and send it to the function that will insert it in … -
how to show images from serializers list in django using jquery ajax
I want to show image from serializers list view using jquery . I wanted to show all the tweets using ajax but i have no idea how to show image using jquery ajax models.py class Tweet(models.Model): content = models.CharField(max_length=140) author = models.ForeignKey(User,on_delete=models.CASCADE) Image = models.FileField(upload_to="images/",blank=True) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) serializers.py class TweetModelSerializers(serializers.ModelSerializer): author = UserDisplaySerializer() class Meta: model = Tweet fields = ['content','author','Image'] views.py class TweetListAPIView(generics.ListAPIView): serializer_class = TweetModelSerializers def get_queryset(self,*args,**kwargs): qs = Tweet.objects.all().order_by("-timestamp") print(self.request.GET) query = self.request.GET.get("q", None) if query is not None: qs = qs.filter( Q(content__icontains=query) | Q(user__username__icontains=query) ) return qs jquery $.ajax({ url:"/api/tweet", method:"GET", success: function(data){ //console.log(data) $.each(data,function(key,value){ //console.log(key) console.log(value.Image) var tweetContent = value.content; var tweetUser = value.author; var tweetImage = value.Image; $("#tweet-container").append( "<div class=\"media\"><div class=\"media-body\">" + tweetContent + "<br/> via " + tweetUser.username + " | " + "<a href='#'>View</a>"+"<br>" + tweetImage + "</div></div><hr/>" ) }) }, error:function(data){ console.log("error") } }) this method doesnot show the image. It only show the name of the images like http://127.0.0.1:8000/img/images/FB_IMG_1538467390993.jpg . How can i show the images in jquery ? -
Django actual value in choice field form
I have models like this: class Projects(models.Model): project = models.CharField(max_length=150, blank=True, null=True) def __str__(self): return self.project class Profile(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) project = models.ForeignKey(Projects, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.user.username I also made a form in which I want to change current Project assigned Profile: class ProjectForm(ModelForm): class Meta: model = Profile fields = [ 'project' ] My view looks like this: def change_project(request, user): user = User.objects.filter(username=user)[:1].get() profile = Profile.objects.get(user=user) form = ProjectForm(request.POST, instance=profile) if request.method == 'POST': if form.is_valid(): form.save() context = {'form': form} return render(request, 'datafiller/change_project.html', context) I can change the project using this form, but every time I want to do it again the form looks like this How can I show in the form the current project instead of "------"? -
How to create a custom templatetag in my django project
I have been trying create a custom templatetag in my project , but it does not work This is my structured project : I created a folder in my index directory called templatetags > __init__.py , extras.py , inside extras file this: from django import template register = template.Library() def cut(value): return value.replace("no", 'yes') Template : {% load poll_extras %} but I got this -
CSS inheritance in Django templates
I want to split my CSS to multiple files to match with each template and app. But the following problem keeps me baffled. In the base.css of my base.html template, I have an element class button declared as following: .button { ... } So, all buttons should follow this css. In an app called table, in a template table_view.html that extends base.html {% extends "base.html" %} {% load static %} {% block content %} <link href="{% static 'css/table.css' %}" rel="stylesheet" /> ... <button class="btn-avail table">Table</button> ... {% endblock %} I have a different format for class btn-avail in table.css. But I could not get it to load and override the base format. If I change the class name to button (of base.css), then it reflects the base format. Or if I place btn-avail in the base.css, then its format is correctly reflected. In my settings.py, here is my static directory: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') What am I doing wrong? Thanks. -
Hi All! I'm getting a "Bad Request (404)" error after deploying a Django app to Heroku
This is my first question on Stackoverflow so please bare with me. I've been trying to deploy a Django app to Heroku using AWS S3 as the place for my media storage. I've gone through what's neccesseryto get everything up and running (see settings.py code below) but can't figure out why I keep hitting the "Bad Request (404)" error page. Here's part of my heroku logs --tail traceback. I originally thought the issue was with Gunicorn but all seems to be fine there. If you need to see the rest please let me know as SO wont allow me to post the full traceback. 2020-10-30T18:20:28.057488+00:00 heroku[router]: at=info method=GET path="/" host=fryed-project.herokuapp.com request_id=8daaabd0-3f8d-4f87-847e-25291d4372fc fwd="176.26.119.21" dyno=web.1 connect=1ms service=193ms status=400 bytes=476 protocol=https 2020-10-30T18:20:28.058801+00:00 app[web.1]: 10.12.135.75 - - [30/Oct/2020:18:20:28 +0000] "GET / HTTP/1.1" 400 143 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36" 2020-10-30T18:20:28.352784+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=fryed-project.herokuapp.com request_id=bc9d6397-6f63-4be7-a19f-826165de2cf6 fwd="176.26.119.21" dyno=web.1 connect=0ms service=127ms status=400 bytes=476 protocol=https 2020-10-30T18:20:28.353864+00:00 app[web.1]: 10.12.135.75 - - [30/Oct/2020:18:20:28 +0000] "GET /favicon.ico HTTP/1.1" 400 143 "https://fryed-project.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36" 2020-10-30T18:20:42.832461+00:00 heroku[router]: at=info method=GET path="/" host=fryed-project.herokuapp.com request_id=34319de1-399e-4c72-91b4-c9c3a173c0f7 fwd="176.26.119.21" dyno=web.1 connect=0ms service=18ms status=400 bytes=476 protocol=https 2020-10-30T18:20:42.833907+00:00 app[web.1]: 10.12.135.75 - … -
Populate another input field based on another field using ajax, Django
I am trying to populate one input field based on another field. I am using raw SQL query instead of ORM. My views : def myview(request): form=searchform(request.POST) conn = cx_Oracle.connect("xyz","abcde","TESTDB",encoding="UTF-8") rows=[] if request.method=='POST': empno = form['empno'].value() try: cursor = conn.cursor() sql_query=""" select empno,emp_name from tb_ps_emp_info where empno= :emp_no_insert and status=:status """ emp_no_insert=empno status_="W" data = { "emp_no_insert": emp_no_insert, "status": status_, } cursor.execute(sql_query,data) columns = [col[0] for col in cursor.description] cursor.rowfactory = lambda *args: dict(zip(columns, args)) rows = cursor.fetchall() finally: conn.close() for row in rows: employee_name=row['EMP_NAME'] context={ "rows":rows, "form":form, "employee_name":employee_name, } return render(request,"test.html", context) @csrf_exempt def ajaxviews(request): empno = request.POST.get("empno") conn = cx_Oracle.connect("xyz","abcde","TESTDB",encoding="UTF-8") cursor = conn.cursor() sql_query=""" select empno,emp_name from tb_ps_emp_info where empno= :emp_no_insert and status=:status """ emp_no_insert=empno status_="W" data = { "emp_no_insert": emp_no_insert, "status": status_, } cursor.execute(sql_query,data) columns = [col[0] for col in cursor.description] cursor.rowfactory = lambda *args: dict(zip(columns, args)) rows = cursor.fetchall() print(rows) context={ "rows":rows, } return HttpResponse(context) Urls: urlpatterns = [ path('admin/', admin.site.urls), path('test/',views.myview,name="test"), path('test_ajax/',views.ajaxviews,name="test_ajax"), ] forms: class searchform(forms.Form): empno=forms.CharField(label="empno", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) empname=forms.CharField(label="empname", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) HTML: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="" method="POST"> {% csrf_token %} <p><label for="id_empno">empno:</label> <input type="text" name="empno" class="form-control" maxlength="50" required="" id="id_empno"></p> <input type="Submit" name="submit" value="Submit"> </form> <p><label … -
Django 3: How to pass 'rows' into the html template?
I'm building a Crud table template as the user has many many tables to update and I'm having trouble passing on the records to the template. Here is my view: def crud_table(request): user = request.user org = Organization.objects.filter(user=user) active_project = Project.objects.filter(organization=org[0], is_active=True)[0] assets = Asset.objects.filter(project=active_project) context_lbls = {'name': 'Name', 'asset_id': 'Asset ID', 'det_curve': "Deterioration Curve", 'class': 'Class', 'surface_type': 'Surface Type', 'Age': 'Age', 'AADT': 'AADT', 'AADTT': 'AADT', 'route': 'Bus Route', 'truck_route': 'Truck Route', 'Length': 'Asset Length', 'HCI': 'HCI' } context_data = {'name': Asset.objects.filter(project=active_project), 'asset_id': assets.asset_id, 'det_curve': assets.det_curve.name, 'class': assets.func_class.name, 'surface_type': assets.surface_type.name, 'Age': assets.age, 'AADT': assets.aadt, 'AADTT': assets.aadtt, 'route': assets.is_bus_route, 'truck_route': assets.is_truck_route, 'Length': assets.length, 'HCI': assets.hci } context = {'labels': context_lbls, 'records': context_data} And here is my template: <thead> <tr> <th> <span class="custom-checkbox"> <input type="checkbox" id="selectAll"> <label for="selectAll"></label> </span> </th> {% for l in labels %} <th>{{l}}</th> {% endfor %} </tr> </thead> <tbody> <tr> <td> <span class="custom-checkbox"> <input type="checkbox" id="checkbox1" name="options[]" value="1"> <label for="checkbox1"></label> </span> </td> {{ records }} {% for r in records %} <td>{{r}}</td> {% endfor %} </tr> </tbody> My context_data is obviously incorrect, I'm just not sure how to pass the information to the template. I'm doing all of this to avoid having to create multiple HTML files and … -
Django: Sum of annotated field
I have the following two models: class ProductionSet(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) line = models.ForeignKey(Line, on_delete=models.CASCADE) class ProductionSetEntry(models.Model): productionset = models.ForeignKey( ProductionSet, on_delete=models.CASCADE, related_name="set" ) audited_at = models.DateTimeField( verbose_name=_("Audited at"), null=True, blank=True ) What I want to achieve is a result set grouped for each line with two counts: an entries total count and a count for fully audited sets. Sample result: <QuerySet [{'line': 1, 'sum_fully_audited': 0, 'total': 43}, {'line': 2, 'sum_fully_audited': 0, 'total': 51}, {'line': 3, 'sum_fully_audited': 2, 'total': 4}]> I'm able to add the fully_audited to each row before grouping by: ProductionSet.objects.annotate( audited=Count("set", filter=Q(set__audited_at__isnull=False)), ).annotate( fully_audited=Case( When(audited=Count("set"), then=1), default=0, output_field=IntegerField(), ) ) Following query: ProductionSet.objects.annotate( audited=Count("set", filter=Q(set__audited_at__isnull=False)), ).annotate( fully_audited=Case( When(audited=Count("set"), then=1), default=0, output_field=IntegerField(), ) ).values( "line", "fully_audited" ).annotate( total=Count("id", distinct=True), sum_fully_audited=Sum("fully_audited"), ).order_by( "line" ) raises django.core.exceptions.FieldError: Cannot compute Sum('fully_audited'): 'fully_audited' is an aggregate while ProductionSet.objects.annotate( audited=Count("set", filter=Q(set__audited_at__isnull=False)), ).annotate( fully_audited=Case( When(audited=Count("set"), then=1), default=0, output_field=IntegerField(), ) ).values( "line", "fully_audited" ).annotate( total=Count("id", distinct=True), ).order_by( "line" ) results in <QuerySet [{'line': 1, 'fully_audited': 0, 'total': 43}, {'line': 3, 'fully_audi... which looks good so far but obviously has no sum_fully_audited yet. -
How to integrate Opencv in Django rest frame
I have a simple opencv file that converts frames to video. I fetch video from Django db and convert to frame. Now my question is how can I save the converted frames in the directory where my video is.? I get this error when I try to use the uoload_to function as a save path in the video_to_frame function cv2.imwrite(os.path.join(upload_to,'new_image'+str(i)+'.jpg'),frame) TypeError: expected str, bytes or os.PathLike object, not function Upload directory def upload_to(instance, filename): base, extension = os.path.splitext(filename.lower()) return f"SmatCrow/{instance.id}/{filename}" Model.py from .utils import video_to_frame class MyVideo(models.Model): name= models.CharField(max_length=500) date = models.DateTimeField(auto_now_add=True) videofile= models.FileField(upload_to=upload_to) def __str__(self): return self.name + ": " + str(self.videofile) def save(self, *args, **kwargs): super(MyVideo, self).save(*args, **kwargs) tfile = tempfile.NamedTemporaryFile(delete=False) tfile.write(self.videofile.read()) vid = video_to_frame((tfile.name)) Opencv def video_to_frame(video): today = date.today() d = today.strftime("%b-%d-%Y") cap= cv2.VideoCapture(video) i=1 while(cap.isOpened()): ret, frame = cap.read() if ret == False: break if i%10 == 0: cv2.imwrite(os.path.join(upload_to,'new_image'+str(i)+'.jpg'),frame) i+=1 cap.release() cv2.destroyAllWindows() -
Ignoring a Django signal with a test mock
I have a function setup to hook the pre_delete on a model and I want to ignore this during testing using unittest.mock.patch, but this only works when I use the signal name from Django or if I disconnect it by dispatch_uid. The prototype looks like: @receiver(pre_delete, sender=MyModel, dispatch_uid="pre_delete_my_model") def pre_delete_my_model(sender, instance, *args, **kwargs): ... in my tests this works: @patch("django.db.models.signals.pre_delete") def test_something_that_triggers_pre_delete(self, pre_delete_mock): ... but I'd like something that's a bit more explicit, eg. @patch("my_app.signals.pre_delete_my_model") def test_something_that_triggers_pre_delete(self, pre_delete_mock): ... this doesn't work though, I assume because that's not the signal that's being raised, it's just set up to receive it. I have found a way that works using pre_delete.disconnect(...), but I'm an annoying person that doesn't like the way that looks with those calls spread around my tests. Is there a way to do this so that it can use something specific to the model or the handler in the decorator? -
Displaying tabular data using columnar with python
I have the structure as follows. I show it as a table with the columnar library. It works just fine. But because the incoming json data is "dict", it does not show it as a single line. How can I show the above json data in single print (table) print screen? from time import sleep from django.views.decorators.http import require_POST import json from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import django_filters.rest_framework import requests from columnar import columnar from tabulate import tabulate @require_POST @csrf_exempt def webhook(request): while True: get_active_position() return HttpResponse(request, content_type='application/json') def get_active_position(): print("get_active position") data = "{'symbol': 'BCHUSDT', 'positionAmt': '0.001', 'entryPrice': '266.85000', 'markPrice': '259.99000000', 'unRealizedProfit': '-0.00686000', 'liquidationPrice': '0', 'leverage': '20', 'maxNotionalValue': '250000', 'marginType': 'cross', 'isolatedMargin': '0.00000000', 'isAutoAddMargin': 'false', 'positionSide': 'LONG'} {'symbol': 'ETHUSDT', 'positionAmt': '0.001', 'entryPrice': '385.88000', 'markPrice': '381.85854735', 'unRealizedProfit': '-0.00402145', 'liquidationPrice': '0', 'leverage': '10', 'maxNotionalValue': '2000000', 'marginType': 'cross', 'isolatedMargin': '0.00000000', 'isAutoAddMargin': 'false', 'positionSide': 'LONG'} " for sym in data: if sym['positionAmt'][:1] == "-" and sym['positionAmt'] <= str("0.00000"): headers = ["Symbol", "EntryPrice", "positionSize", "Side"] symbols = [ [sym['symbol'], sym['entrypPrice']] ] table = columnar(symbols, headers=headers) print(table) # Long position elif sym['positionAmt'] >= str("0.00000"): headers = ["Symbol", "EntryPrice", "positionSize", "Side"] symbols = [ [sym['symbol'], sym['entrypPrice']] ] table = columnar(symbols, headers=headers) print(table) return … -
ImportError: attempted relative import with no known parent package while running code
Code: from django.shortcuts import render, redirect from django.views.generic import TemplateView, ListView, CreateView from django.core.files.storage import FileSystemStorage from django.urls import reverse_lazy from .forms import BookForm from .models import Book from django.db import models On running code i am getting this error **Output: ** Traceback (most recent call last): File "/media/programmer/New Volume/Projects/TradeCred/backend.py", line 6, in <module> from .forms import BookForm ImportError: attempted relative import with no known parent package -
How to make no-reply@company.com in Django
i have a problem, when i sent email, my host user email is the sender, i want no-reply@company.com is the sender if customer see the email, #views.py email_body = 'Hallo '+user.username + 'Silahkan login akun anda, dan print surat yang anda ajukan' email_subject = 'Pengajuan Surat Diterima' email = EmailMessage( email_subject, email_body, 'Kecamatan Bintan Utara <noreply@kantorkecamatanbintanutara.com>', [user.profile.email], ) email.send(fail_silently=False) context = { 'form3':form3, 'form4':form4, 'code':code } #setting.py EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = 'akuntest1291@gmail.com' EMAIL_HOST_PASSWORD = 'krnhbjfcczgrfutp' EMAIL_USE_TLS = True EMAIL_PORT = 587 -
Newer Django requires applying migration, what are the changes in database
I'm working on upgrading a legacy project, currently still on Python 2.7.18 as the highest Python-2 before upgrade to 3. After upgrading Django from 1.8.13 to 1.11.29, the project seems to be running OK, but with message saying: ... Performing system checks... System check identified no issues (0 silenced). You have 5 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, authtoken, sites. Run 'python manage.py migrate' to apply them. ... Following the message, I applied the migrations by command python manage.py migrate, and the message disappeared when starting again. The legacy project is already running on an existing database for production, so I'm wondering: What changes did the migrate make into database? Is there some way to compare (MySQL) database before and after applying the migration? I'm new to Python upgrade, so is there any important things to check for this type of migrate upon existing database? Any thoughts will be highly appreciated. More details, if interesting to you: Screenshot of applying migration: " (venv) [appuser@testserver PROJECT]$ python manage.py migrate /data/EBC-dev/venv/lib/python2.7/site-packages/arrow/arrow.py:28: DeprecationWarning: Arrow will drop support for Python 2.7 and 3.5 in the upcoming v1.0.0 release. Please upgrade to Python 3.6+ … -
Django - Adding text from dictionary in a static tag
In Django, I have this line in my HTML file which adds an image using the static tag. However, it seems like {{ dictionary.key }} is not working in this case. <img src="{% static 'Image/Portfolio/{{article.slug_title}}/{{article.imageFile}}.jpg' %}"> Is there any method to solve this problem or it is possible to like with the absolute route? Thank you. -
Problemas para usar el FilteredSelectMultiple de Django
soy algo nuevo con django, y tengo el problema de que cuando utilizo FilteredSelectMultiple de django en mis propias vistas, no se muestra como cuando se asignan permiso en el admin de django, sino mas bien esto:enter image description here En mi Forms.py tengo esto: class GroupForm(forms.ModelForm): permissions = forms.ModelMultipleChoiceField(queryset=Permission.objects.all(), required=True, widget=FilteredSelectMultiple("Permissions", is_stacked=False)) class Media: css = {'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n/',) class Meta: model = Group fields = '__all__' En mi Views.py: class GrupoRegistrar (LoginYSuperStaffMixin, ValidarPermisosMixin, CreateView): model = Group form_class = GroupForm template_name = "Grupos/registrar_grupos.html" permission_required = ('', ) def post(self, request, *args, **kwargs): if request.is_ajax(): form = self.form_class(data= request.POST, files= request.FILES) if form.is_valid(): form.save() mensaje = f'{self.model.__name__} registrado correctamente' error = 'No existen errores' response = JsonResponse({'mensaje': mensaje, 'error': error}) response.status_code = 201 return response else: mensaje = f'{self.model.__name__} no se ha podido registrar!' error = form.errors response = JsonResponse({'mensaje': mensaje, 'error': error}) response.status_code = 400 return response return redirect ('empleado:grupos_inicio') en mi html: <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h2 class="modal-title">Registro de Grupos de permisos</h2> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {{ form.media }} <form id="form_creacion" action="{% url 'empleado:grupo_registro' %}" method="POST"> {% csrf_token %} <div class="modal-body"> <div id="errores"> </div> {{form}} … -
Accessing a public text file by passing a key in Django
I am looking to host a text file that will be publicly accessible on a Django application: http://www.example.com/textfile However, when someone is accessing this text file, they need to to pass an access key, e.g http://www.example.com/textfile?accesskey=123456 The access key is only known to members who are allowed access to this file. The reason for doing it this way is that I have a 3rd party legacy device that can only read text files, and I need to protect the file somehow. Is it possible to run this in Django urls.py? Any help is really appreciated. -
API Django Rest Framework on Cloud Run shutting down
I have implemented an API DRF on Cloud Run. The Dockerfile is the following: # Use the official lightweight Python image. # https://hub.docker.com/_/python FROM python:3.7-slim # Allow statements and log messages to immediately appear in the Cloud Run logs ENV PYTHONUNBUFFERED True # Prevents Python from writing pyc files to disc (equivalent to python -B option) ENV PYTHONDONTWRITEBYTECODE True ARG REQFILE=base.txt ENV REQFILE ${REQFILE} # install dependencies RUN pip install --upgrade pip # Copy application dependency manifests to the container image. # Copying this separately prevents re-running pip install on every code change. COPY requirements/*.txt ./ # Install production dependencies. RUN pip install -r ./${REQFILE} # Copy local code to the container image. ENV APP_HOME /app WORKDIR $APP_HOME COPY . ./ # Run the web service on container startup. Here we use the gunicorn # webserver, with one worker process and 8 threads. # For environments with multiple CPU cores, increase the number of workers # to be equal to the cores available. CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:app It is the same as described in the documentation : https://codelabs.developers.google.com/codelabs/cloud-run-django#6 But since a few days, without any significative change on my code, I have … -
onclick how to toggle button and fa icons?
Here I have a post detail view ,where i want to toggle the color of like button, <li> <button style='margin-top:-20px' class="btn btn-link text-dark p-0 border-0 btn-outline-light" id="like-button" value="{{post.id}}">{% csrf_token %} <i class="fa fa-heart"></i> <span class="" id="like_count">{{post.likes.count}}</span> </button> </li> jscript: $(document).on('click', '#like-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "posts:like" %}', data: { postid: $('#like-button').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { document.getElementById("like_count").innerHTML = json['result'] }, error: function (xhr, errmsg, err) { } }); }) </script> I simply want to change the color of heart icon ; on click heart filled with red color and onclick heart become blank or white. -
Cannot Import Include From Django
After running the command from django.urls import include I get the error freduah@freduah:~/Desktop/DjangoReactTodo/todo$ ./manage.py runserver Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7fd1e13a4a50> Traceback (most recent call last): File "/home/freduah/.local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/freduah/.local/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/home/freduah/.local/lib/python2.7/site-packages/django/urls/resolvers.py", line 256, in check for pattern in self.url_patterns: File "/home/freduah/.local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/freduah/.local/lib/python2.7/site-packages/django/urls/resolvers.py", line 407, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/freduah/.local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/freduah/.local/lib/python2.7/site-packages/django/urls/resolvers.py", line 400, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/freduah/Desktop/DjangoReactTodo/todo/todo/urls.py", line 18, in <module> from django.urls import include ImportError: cannot import name include Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7f2db9839a50> Traceback (most recent call last): File "/home/freduah/.local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/home/freduah/.local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check … -
Report building in Django
I am trying to build a system which will enable my users to create their own reports based on the model of their choosing without me having to code them every time they need updating. In order to do this, I've come up with the following models:- from django.db import models from django.contrib.contenttypes.models import ContentType class ReportField(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) data_method = models.CharField(max_length=100) def get_value_for(self, object): return getattr(object, self.data_method) class Report(models.Model): name = models.CharField(max_length=200) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) data_fields = models.ManyToManyField(ReportField) The idea is that users can create a Report based on the model they're interested in. They can then add any number of ReportFields to that report and, when the report runs, it will call the data_method (the name of a property) on each instance of the model in the db. The bit I'm having trouble with is defining which properties the users can have access to. I need to have a way of creating a load of ReportFields with certain data_methods for each model. But I don't want to create them by hand - I want it to work in a similar way to the way Permissions work in Django, if that's possible, like this:- class MyModel(models.Model): … -
Handling database connection errors / operational error exceptions in Python / Django?
I am running multiple databases and I need to handle this exception. How can I do it either in the view or a more general approach ? I am using PostgreSQL. It's a bit ugly to wrap my whole code like below. import psycopg2 def Main(request): try: myqs = customers.objects.all() except psycopg2.OperationalError as e: print('operational error, handle this') return render(request, 'core/main/main.html', {'qs': myqs}) -
Calling a python function via AJAX in Django
I am sending a request via AJAX upon a button (whose id="transcript") click to trigger a function called transcript. AJAX document.querySelector('#transcript').addEventListener('click', () => { fetch(`transcript/${CNIC}`); views.py def transcript (request, cnic): form = TranscriptForm() return render (request, "certificates/transcripts.html", { "form": form, "cnic": cnic }) The fetch request works fine, but the new page i.e. transcripts.html does not render. I have to manually type the URL to update the view. Why is it happening, can anybody please explain? The output in console: views.js:62 Fetch finished loading: GET "http://127.0.0.1:8000/transcript/1530660001979". -
How create a project in Django path
I would like create my first project in Django. I have installed Python (Version 3.7.2) and Django (Version 3.1.2). In my PC I run a command py -m django startproject mysite, however there is no mysite file in C:\Users\misak\AppData\Local\Programs\Python . The mysite file has been created in C:\Users\misak . How can I create mysite file by default in C:\Users\misak\AppData\Local\Programs\Python , please? Because than I want to run the sever using a command py manage.py runserver, which is not possible now, because of an error "C:\Users\misak\AppData\Local\Programs\Python\Python38\python.exe: can't open file 'manage.py': [Errno 2] No such file or directory" Thanks a lot!