Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Steck overflow - How to search and learn about the specific topics in stack overflow
how to search and how to set the preferences for the topics to search and learn about in stack overflow. In this I have learning more. Is there any way to set the preferences for Python, Django, Angular, Javascript and Typescript -
Refused to execute script because its MIME type ('text/html') is not executable AJAX DJANGO
I have this Django app that's working fine. But I keep getting this error in console: Refused to execute script from 'http://localhost:8000/live/detect/static/JS/livedetect.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. I tried answers from stack, but I cant find out what is wrong!! Here's the script file function fetchData(){ csrfToken = $('#MainCard').data("token"); $.ajax({ url: document.URL, async: true, dataType: 'json', data:{ csrfmiddlewaretoken: csrfToken, }, type: 'post', success: function(responce){ $('#ExtractedText').text(responce["text"]); } }); } $(document).ready(function(){ setInterval(fetchData, 1000); }); -
Django serializer return OrderdDict instead of JSON
I am creating a Django Rest API using django-rest-framework. I am using a JSONField to store JSON data in mongo collection. Everything is working fine but when I am fetching the record, I am getting an OrderdDict instead of json. Here is my Model - from django.contrib.auth.models import AbstractBaseUser from django.db import models from djongo import models class Content(models.Model): id = models.BigAutoField(primary_key=True,auto_created = True, serialize = False) slides = models.JSONField(blank = True, default=[]) and the response I am getting - [ { "id": 2, "slides": "OrderedDict([('id', '1'), ('name', 'Creator 1')])" } ] but I expect a response like [ { "id": 2, "slides": [ { "id":1, "name":"Creator 1" } ] } ] View file - class ContentList(ListAPIView): serializer_class = ContentSerializer def get_queryset(self): limit = self.request.query_params.get('limit') if limit: pagination.PageNumberPagination.page_size = limit queryset = Content.objects.all().order_by('-id') return queryset I tried using encoder and decoder but getting error - slides = models.JSONField(blank = True, encoder= None, decoder=None, default=[]) TypeError: __init__() got an unexpected keyword argument 'encoder' The Django version is 3.0. How can I do this? I am new to python and started learning recently and stuck here for last 2 days. Tried a lot of solution but not working. -
why the form not save in django?
I have a formset and I am trying to save it back. But, when I try to check if employ_academic_forms.is_valid() and save, validation always fails even if nothing in the formset has been changed. I am displaying already existing data using formset and trying to edit it. I don't know where I am going wrong. Can someone please help? view: def employedit(request, pk, id): employ_academic = EmployAcademicInfo.objects.filter(employ_id=pk) employ_academic_forms = EmployAcademicUpdateFormSet(queryset=employ_academic) if request.method == 'POST': employ_academic_forms = EmployAcademicUpdateFormSet(request.POST, queryset=employ_academic) if employ_academic_forms.is_valid(): user_obj = User.objects.get(id=pk) name = employ_basic_forms.cleaned_data['name'] email = employ_basic_forms.cleaned_data['email'] user_obj.username=email user_obj.first_name=name user_obj.email=email user_obj.save() instances = employ_academic_forms.save(commit=False) print(instances) for instance in instances: instance.employ_id = user_obj instance.save() return redirect('employ-list') context = { 'employ_academic_forms':employ_academic_forms, } return render(request, 'admins/employ/edit_employ.html', context) form: EmployAcademicUpdateFormSet = modelformset_factory( EmployAcademicInfo, exclude = ['employ_id'], extra=0, labels = { 'degree': 'Enter Employ Degree', 'last_passing_institution_name': 'Enter Employ Passing Institution', 'last_passing_year': 'Enter Employ Passing Year', }, widgets = { 'degree' : forms.Select(attrs={'class':'form-control form-control-lg', 'placeholder':'Enter degree'}), 'last_passing_institution_name' : forms.TextInput(attrs={'class':'form-control form-control-lg', 'placeholder':'Enter institution name'}), 'last_passing_year' : forms.DateInput(attrs={'class':'form-control form-control-lg', 'type':'date'}), }, ) Html: {% extends 'base/base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <div class="card"> <form class="form-horizontal" action="" method="post"> {% csrf_token %} <div class="card-body"> <div class="card-body"> <div class="form-horizontal"> {{ employAcademicFormSet.management_form … -
Docker and Django. django.db.utils.OperationalError: could not connect to server
I can't find solution, please help! I have Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 RUN mkdir /app WORKDIR /app RUN pip install Django \ && pip install psycopg2 \ && pip install jinja2 \ && pip install Pillow COPY . /app/ And docker-compose.yaml version: "3" services: db: image: postgres environment: - POSTGRES_DB=folivora - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - 5432:5432 site: image: folivora:latest command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/app depends_on: - db ports: - 8000:8000 And settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'folivora', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } And ERROR when run "docker-compose up" site_1 | django.db.utils.OperationalError: could not connect to server: Connection refused site_1 | Is the server running on host "db" (192.168.224.2) and accepting site_1 | TCP/IP connections on port 5432? When I edit docker-compose.yaml, change string command to: command: bash -c "python manage.py runserver 0.0.0.0:8000" all is fine. So, migration line broke my code, but i don't know why. I try to create empty django project to check the same config. On first "docker-compose up", all started and working fine, but from second start, all is broke again with the same error. Over … -
I want to load another view file after the url / but receiving an error saying page not found
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/music/2/ Using the URLconf defined in Analytic_practice.urls, Django tried these URL patterns, in this order: admin/ music/ [name='index'] music/ (?P<album_id>[0-9]+)/ [name='detail'] The current path, music/2/, didn't match any of these. Here is my code: **music.urls.py file: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('(?P<album_id>[0-9]+)/', views.detail, name='detail'), ]** **views.py from django.http import HttpResponse # noinspection PyUnusedLocal def index(request): return HttpResponse("<h1>This will be a list of all Albums</h1>") # noinspection PyUnusedLocal def detail(request, album_id): return HttpResponse("<h2>Details for Album id: " + str(album_id) + "</h2>")** **Analytic_practice.urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('music/', include('music.urls')), ]** -
Could not parse the remainder: '"base.html"' from '"base.html"'
I have searched everywhere can't seem to find what's wrong with this code. < html> <head><meta charset="utf-8"> <title></title> </head> <body> <p> {% extends &quot;base.html&quot; %} {% load static %} {% block title %} About {% endblock %} {% block content %} </p> <header>{% block nav %} {% include &#39;nav.html&#39; %} {% endblock nav %}</header> It keeps throwing this error Could not parse the remainder: '"base.html"' from '"base.html"' At times it work, some other time, it does not. What could be wrong? -
The current path, catalog/, didn't match any of these(Django)
in my django project when i make the basic project skeleton and try to run it, when i enter http://127.0.0.1:8000/ in my browser it jumps to url: http://127.0.0.1:8000/catalog/ which causes an error that 'The current path, catalog/, didn't match any of these. can anybody help me with this problem?? -
How to add a field many times in Django admin panel
what is the best way to add a field many times in Django admin panel i mean how i can add many names in admin panel i have this code in models.py : from django.db import models class Android(models.Model): name = models.CharField(max_length=50,default="") def __str__(self): return self.name any help -
SQL - which index will speed up the COUNT() query
I have a very simple Postgres database that looks like that (it's defined in Django but this doesn't matter): class Country: id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # Not important # name = models.TextField(nullable=False) class City: id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # name = models.TextField(nullable=False) country = models.ForeignKey(Country) class Street: id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # name = models.TextField(nullable=False) city = models.ForeignKey(City) # Just some boolean field is_big = models.BooleanField(nullable=False) I want to query the number of "big" streets in a country. This is done like that: SELECT COUNT(*) FROM Street INNER JOIN City ON Street.city_id = City.id WHERE Street.is_big = true AND City.country_id = 'xxxxxxx'::uuid There are a total of around ~20 countries, ~5000 cities and ~2 million streets in the database, which is not a lot, yet this query can take sometimes 1-2 seconds. What index should I add to make this query fast? -
Cannot change email subject prefix from [example.com] in production
I was able to change it in development, however, I am not able to change it in production for some reason. I did both: set ACCOUNT_EMAIL_SUBJECT_PREFIX = "[MyApp] " set the site's name to 'MyApp' (I even deleted the existing Site object and created a new one). What could I be missing? -
Applying highlighting effect to text(Django)
I am writing a custom template filter that highlights the keyword put into the search engine in the search results page, just like in Google search results. According to The other answer, the working code is below. custom.py from django import template from django.utils.safestring import mark_safe from django.utils.html import conditional_escape from django.template.defaultfilters import stringfilter register = template.Library() @register.filter(needs_autoescape=True) @stringfilter def highlight(value, search_term, autoescape=True): return mark_safe(value.replace(search_term, "<span class='highlight'>%s</span>" % search_term)) But I don't know how to apply this code to my django app. import this custom.py to template html file? Do I need to change views.py? Please teach me how to carry out this code. -
How to use a field from a user defined table type for a stored procedure in Django?
I have a stored procedure in which @productId is INT, and @subProductID is coming from a user defined table type. Now, I want to run the stored procedure on the basis of that @subProductID and get values for my function. How to do that? If I try hard coding subproductID as int or string, it gives an error. -
TypeError: expected str, bytes or os.PathLike object, not ImageFieldFile When load keras
**What is the problem when am trying to upload image from post man to django so than i can predict using keras i got above error, trying to say TypeError: expected str, bytes or os.PathLike object, not ImageFieldFile When load keras ** tf.compat.v1.disable_eager_execution() with graph.as_default(): # load model at very first with keras.utils.CustomObjectScope( {'relu6': keras.layers.ReLU(6.), 'DepthwiseConv2D': keras.layers.DepthwiseConv2D}): model = load_model('agrolite_modelV1.h5') # call model to predict an image def api(full_path): data = image.load_img(full_path, target_size=(224, 224, 3)) data = np.expand_dims(data, axis=0) data = data * 1.0 / 255 with graph.as_default(): set_session(sess) predicted = model.predict(data) return predicted @api_view(['POST', ]) def check_disease(request): if request.method == 'POST': try: file = request.FILES['file'] indices = { 0: 'Maize_Cercospora_leaf_spot', 1: 'Maize_Common_Rust', } result = api(file) predicted_class = np.asscalar(np.argmax(result, axis=1)) accuracy = round(result[0][predicted_class] * 100, 2) label = indices[predicted_class] data = { 'label': label, 'accuracy': accuracy } # return Response(data, status=status.HTTP_200_OK) except KeyError: raise ParseError('Request has no resource file attached') return Response(status.HTTP_400_BAD_REQUEST) -
Inlineformset with crispy forms - display labels once only
I have an inline formset being displayed with crispy forms. It works just fine, but I get the labels displayed above each row. I'd prefer them once, at the top of the table of fields, but not quite sure how to achieve this. I have a layout object defined, where I've tried to turn off the labels to start with, but I guess helper objects don't work this way ... class Formset(LayoutObject): template = "missions/formset.html" def __init__(self, formset_name_in_context, template=None): self.formset_name_in_context = formset_name_in_context self.fields = [] if template: self.template = template self.helper = FormHelper() self.helper.form_show_labels = False def render(self, form, form_style, context, template_pack=TEMPLATE_PACK): formset = context[self.formset_name_in_context] return render_to_string(self.template, {"formset": formset})class Formset(LayoutObject): template = "missions/formset.html" In the main form this is used as follows: self.helper.layout = Layout( < snipped the main form parts as not relevant to the question > Div( Fieldset( _("Invitees"), Field("allow_invitees_to_add_others", css_class="col-md-12"), Formset("invitees"), ), ), ) ) And in my formset.html <table> {{ formset.management_form|crispy }} {% for form in formset.forms %} <tr class="{% cycle 'row1' 'row2' %} formset_row-{{ formset.prefix }}"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} … -
Django Rest Framework - Getting serialized nested aggregated and grouped data
I have Django models: class Client(models.Model): name = models.CharField() class Office(models.Model): name = models.CharField() class HolidayOffer(models.Model): name = models.CharField() class Booking(models.Model): holiday_offer = models.ForeignKey(HolidayOffer, null=True) office = models.ForeignKey(Office, null=True) client = models.ForeignKey(Client, null=True) start_date = models.DateField() end_date = models.DateField() I would like to get as django-rest-framework API JSON response similar to the example below. It's single office example, but please mark [] so that there is a list of offices with list of clients, each with their bookings inside (and yes, same client could be listed at multiple offices): { "offices": [ { "name": "New York Office", "clients": [ { "name": "Client A", "bookings": [ { "holiday_offer": { "name": "Cyprus - Exclusive Vacation f> } "start_date": "20180608", "end_date": "20180615" } ] } ] } ] } -
Include (inherit) only specific block of template
My project has two apps (for now),table and menu. Each app has a template and both templates extends a base.html template at the project root. table_view.html {% extends "base.html" %} {% load static %} {% block title %}Table Mgt{% endblock %} {% block content %} <link href="{% static "css/table.css" %}" rel="stylesheet" /> ...some elements here... {% endblock %} {% block sidebar %} <a href="#"> <button class="sidebar_button check_in">Check In</button> </a> <a href="#"> <button class="sidebar_button check_out">Check Out</button> </a> {% endblock %} menu_view.html {% extends "base.html" %} {% load static %} {% block title %}Menu{% endblock %} {% block content %} <link href="{% static "css/menu.css" %}" rel="stylesheet"/> {% block sidebar %} {% include 'table/table_view.html' %} {% endblock %} base.html {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/base.css" %}" rel="stylesheet" /> </head> <body> <div id="header"> ...some elements here... </div> <div id="sidebar"> {% block sidebar %} {% endblock %} </div> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> In menu_view.html, I am trying to include the block sidebar only. However, the entire table_view.html is actually embedded. How do I include only a specific block from specific template? -
How do I implement a five star rating in django without causing issues to other form fields?
Background I'm currently working on a restaurant review site and I'm struggling with how I could display a five star rating to the comment form in a class based DetailView page. As this is a fairly common question I have already tried out several alternative solutions from other stackoverflow questions but unfortunately it's not working as I expected it to. The other questions I find mostly use function based view, which isn't really helping me at the moment. In an ideal world I would like to display my comment form in the restaurant detail page. I initially tried this path a couple of weeks back and hasn't tried this again. I'm not sure how I should set up my class based RestaurantDetail view for that purpose. Any suggestions? As I couldn't get the RestaurantDetail page to send comments with the CommentForm earlier I instead directed the user to a new page based on a function based view "addcomment". This page works, however I can't get the appearence correct with the five star rating. Sidenotes I plan to display the location of the restaurant on a django-leaflet map and therefore I'm using geojson for the point_dataset function in the RestaurantDetailView. The … -
Is it possible to merge data to the end of a file while uploading it?
There's some files that are all part of one big file I want to download them one by one and upload them to user-client with one post request. for example the original file is 1 GB I split it into 10 files with 100 MB size I want to send the post request with first file then add the second one to the end of file. at the end user sould get the original 1 GB file. -
Select particular instance of a model with Foreign Key to another model
I have these models class Review(models.Model): # SET_NULL ensures that when a company is deleted, their reviews remains company = models.ForeignKey(Company, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) # SET_NULL ensures that when a user is deleted, their reviews get deleted too review_text = models.TextField(max_length=500, verbose_name='Your Review: (Maximum of 200 Words)') rating = Int_max.IntegerRangeField(min_value=1, max_value=5) date_added = models.DateField('Review Date', auto_now_add=True) def __str__(self): return self.review_text class Response(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) review = models.ForeignKey(Review, on_delete=models.CASCADE) response = models.TextField(max_length=200, verbose_name='Your Response') date_added = models.DateField('Response Date', auto_now_add=True) def __str__(self): return self.response class ResponseReply(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) response = models.ForeignKey(Response, on_delete=models.CASCADE) review = models.ForeignKey(Review, on_delete=models.CASCADE) reply = models.TextField(max_length=200, verbose_name="Your Reply") date_added = models.DateField('Response Date', auto_now_add=True) def __str__(self): return self.reply How to I select ResponseReply belonging to a particular response which also has a foreign key to a particular review. My view rather returns a list instead of an object of the Review Model since there are more than one review. Below is my view: def profile_company(request): print(request.user) company = get_object_or_404(Company, user=request.user) review = get_object_or_404(Review, company=company) responses = get_list_or_404(Response, review=review) response = get_object_or_404(Response, review=review) responses = get_list_or_404(Response, review=review) reply = get_object_or_404(Response, response=response) company_reviews = company.review_set.all() total_reviews = len(company_reviews) print(company.average_rating) form = ResponseForm() if request.method … -
Please tell me any way to view Django website on android
I am developing a django framework based website using python and i want to test it on an android device , the tutorials on youutube to launch via computer seems not to work for me so please tell me any way to launch or see website on my android mobile -
Django NOT NULL constraint failed on migration
I've recently encountered the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: new__blog_law.definitions Here is the code in the migrations: https://pastebin.com/hkzeNsgD Here is the models code: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from ckeditor.fields import RichTextField from tinymce.models import HTMLField class Law(models.Model): identifier = models.CharField(max_length=15) title = models.CharField(max_length=100) description = models.TextField(max_length=400, null=True) definitions = models.TextField() content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) writer = models.CharField(max_length=100) signed = models.DateField() proposed = models.DateField() author = models.ForeignKey(User, on_delete=models.CASCADE) is_repealed = models.BooleanField() is_amendment = models.BooleanField() law_amended = models.TextField(blank=True) has_amendments = models.BooleanField() amendments = models.TextField(blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('law-detail', kwargs={'pk': self.pk}) class AssemblyPerson(models.Model): name = models.CharField(max_length=15) description = models.CharField(max_length=100) committees = models.TextField(max_length=400) content = HTMLField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) party = models.CharField(max_length=100) start_term = models.DateField() end_term = models.DateField() portrait = models.ImageField(default="default.jpg", upload_to="profile_pics") author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('assembly-detail', kwargs={'pk': self.pk}) class ExecutiveOffice(models.Model): name = models.CharField(max_length=15) logo = models.ImageField(default="default.jpg", upload_to="profile_pics") content = HTMLField(blank=True, null=True) documents = models.TextField() organizational_structure = models.ImageField(default="default.jpg", upload_to="profile_pics") director_name = models.CharField(max_length=15) director_desc = models.CharField(max_length=200) director_portrait = models.ImageField(default="default.jpg", upload_to="profile_pics") author = models.ForeignKey(User, on_delete=models.CASCADE) director_start_term = models.DateField() def __str__(self): return self.name What did I do wrong? It … -
Why model formset don't save in django
When i save formset it don't save and it return same page. But i don't find my problem. Please help me for find the problem view: def employedit(request, pk, id): employ_academic_forms = EmployAcademicUpdateFormSet(queryset=employ_academic) if request.method == 'POST': employ_academic_forms = EmployAcademicUpdateFormSet(request.POST, queryset=employ_academic) if employ_academic_forms.is_valid(): user_obj = User.objects.get(id=pk) name = employ_basic_forms.cleaned_data['name'] email = employ_basic_forms.cleaned_data['email'] user_obj.username=email user_obj.first_name=name user_obj.email=email user_obj.save() instances = employ_academic_forms.save(commit=False) print(instances) for instance in instances: instance.employ_id = user_obj instance.save() return redirect('employ-list') context = { 'employ_academic_forms':employ_academic_forms, } return render(request, 'admins/employ/edit_employ.html', context) -
Design a Blog Administration System [closed]
The Blog must allow the user to host articles and allow comments from readersThe Index page of the blog must contain a list of all articles, the dates on which the articles were published and hyperlinks to themEvery article has a dedicated webpage which consists of the title, author, publication date,a comments section and a form for readers to submit commentsReaders must be able to enter comments and view their submitted comments instantlyAll articles must contain a title, an excerpt, author, body and a publication dateAll comments must contain the name of the commenter and the comment textQ2: Create a REST API that fetches all comments, the author of the comments and the article on which the comment is made -
Which Module I use for making a Register api Django REST?
I have to make a Register api through Django REST. and I couldn't find any module for doing this. Can anyone Help me.