Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Variable Wrapped in Paragraph Tag
I am using django-ckeditor as a WYSIWYG text editor when creating posts. It captures and saves the content and the correct HTML tags without any problem. However, my template renders the variable surrounded by <p> tags, which ruins the RichTextField because <p> tags cannot be nested. As a result, it was showing all of the text (with tags) as a paragraph with no formatting. I realized that this was happening, so I changed the surrounding tags in my template to <div> tags, but when the template is loaded on the browser, it replaces the div tags with paragraph tags again. How can I get rid of the <p> tags so that my text is rendered with the correct formatting? Here is my template: {% extends 'bandwagon/base.html' %} {% block content %} <article class="media content-section"> <img src="{{ post.author.profile.image.url }}" alt="profile photo" class="rounded-circle article-img"> <div class="media-body"> <img src="{{ post.image.url }}" class="post-img"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{ object.author }}</a> <small class="text-muted">{{ object.date_posted | date:'F d, Y'}}</small> {% if object.author == user %} <div> <a href="{% url 'post-update' object.id %}" class="btn btn-outline-secondary btn-sm mt-1 mb-1">Edit</a> <a href="{% url 'post-delete' object.id %}" class="btn btn-outline-danger btn-sm mt-1 mb-1">Delete</a> </div> {% endif %} … -
Visual Studio Code: "ImportError: No module named 'environ'" but django-environ installed
I have this problem repently. When execute the debugger I get this error: ImportError: No module named 'environ' But actually I have installed this module with pip. The version of VSC is 1.38.1 Django 2.2 django-environ installed is 0.4.5 debug config: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", "--noreload" ], "django": true, "pythonPath": "${workspaceFolder}/env3/bin/python3" } ] } Any help? Ideas? Thank you! -
How to send multipart form with a file from node to django
I currently have a setup with a service running on node. This service needs to have some processing done on an audio file, so it creates a read stream of this file and sends it, with some other data, to a python Django API for this processing. My Node service essentially does this: const fs = require('fs'); const FormData = require('form-data'); const fetch = require('node-fetch'); function processFile(filepath){ const form = new FormData(); form.append('some-data', someVar); form.append('audio', fs.createReadStream(filepath)); const response = await fetch('some/url', { method: 'POST', body: form, }) .then(r => { return r.json(); }); } I then have a Django API which receives this request and will run some processing on the given file. However Django can't see the file. On the other hand if I send a file using requests (python) it works fine. What I have found so far is that requests adds a Content-Length header which node-fetch does not. Adding this manually does not solve the problem. node-fetch does add Transfer-Encoding: chunked but I don't think this should be a problem. In all cases there is the Content-Type:multipart/form-data header with a boundary defined. I have previously had this working with Flask, but there is some motivation to move … -
Show icon when boolean field in change_list view of admin with Django-jet
When showing boolean fields, there's no check/uncheck icon as in the default template of Django Admin. my Admin model class UserAdmin(UserAdmin): list_display = ['username', 'last_name', 'first_name', 'active'] search_fields = ['username', 'last_name', 'first_name', 'is_active', 'groups'] -
Is there a Reverse-ForeignKey in django?
Suppose we have the following model, class Child(models.Model): parent = models.ForeignKey(User, related_name='children') birth_date = models.DateField(null=True, blank=True) class User(models.Model): pass given a user, we can find his/her children via user.children.all() Question: How to model the following? Suppose we have a kids birthday party, and each party has one or more children Conceptually birthday-party would have a list of children class BirthdayParty(models.Model): children = models.ListForeignKey(Child, many=True) But, the best we can do with django is using mtm where a table for relation is created? class BirthdayParty(models.Model): children = models.ManyToManyField(parent) -
How to merge multiple models into one dataframe in Django
I am working in Django and my models.py look like this: class Catch(models.Model): specimen_count = models.IntegerField(blank=True, null=True) unweighed_baskets = models.FloatField(blank=True, null=True) catch_weight = models.FloatField(blank=True, null=True) class Specimen(models.Model): catch = models.ForeignKey(Catch, on_delete=models.CASCADE) fish_number = models.IntegerField(blank=True, null=True) class Observation(models.Model): specimen = models.ForeignKey(Specimen, on_delete=models.CASCADE) observation_type = models.ForeignKey(ObservationType) observation_value = models.FloatField(max_length=100) class ObservationType(models.Model): name = models.CharField(max_length=100, unique=True) data_type = models.IntegerField() What is the best way to merge all those models into one big dataframe in my views.py ? I suppose I could transform each of them into dataframes by using Panda and then merge them manually one by one until I get a complete dataframe but this sounds very inefficient. Is there a better way ? -
Anomally increase in records of table: From Order ID 54 to 86?
I've a DjangoApp hosted in Heroku. For a while it worked perfectly. In recent days I saw a strange "user" signup with this email: "accessto@hidebusiness.xyz", name: "Access", lastname: "To". He/She signed up 2 times: first as "accessto2" after with "accessto3". After that my normal record of Order was altered. Before this incident Order.id increased by 1, but around this incident it went from 54 to 86. Why? in Heroku, I'm trying to run a DataClip, but I'm getting: SELECT * FROM Order Error: Dataclip Error ERROR: syntax error at or near "Order" LINE 2: FROM Order ^ What could have happened? How can I debug this? -
import data into sqlite database with foreign key django
I want to import student's name list to database with one foreign key which is the class infomation. Namelist Model.py: name = models.CharField(max_length=100) program = models.CharField(max_length=10) classGrp = models.ForeignKey('GroupInfo', on_delete=models.SET_NULL, null=True) the data in the namelist is like this: id name program classGrp 1 ABHISHEK SINGH CE1 1 GroupInfo Model.py: class GroupInfo(models.Model): classGrp = models.CharField(max_length=10) day = models.CharField(max_length=15) The data in the groupInfo is like this: id classGrp day 1 FEP1 Tues 2 FSP1 Wed When i import the namelist data, eg as below: id name program classGrp 137 Dummy FP 2 It does not store 2, which is the classGrp. When i check the detail of the classGrp at http://127.0.0.1:8000/admin: The classGrp is in dropdownlist displaying the classgr ( FEP1,FSP1) instead of the ID (1,2). VIEW.PY: def import_studName(request): template = "import_stud.html" prompt = { 'order' : 'Kindly ensure that the order of CSV should be id, name, program, year, studType,courseType,nationality,VMSAcc,classGrp' } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'This is not a csv file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): #x = GroupInfo.objects.get(pk=(column[4])) #y = Namelist.objects.get(x=) if column[8] != '': classGrp = GroupInfo.objects.get(pk = … -
How to translate a string from Cyrillic to Latin
I have a Story model. User can enter a title in Russian and I need to save alias, which will take transform from Cyrillic to Latin(not translation). For example, 'привет' will be 'privet', not 'hi'. class Story(models.Model): title = models.CharField(max_length=255) alias = models.CharField(max_length=255, null=True, blank=True) -
Django 2.2 default login url
I want to load the Django builtin login page, but not with the URL http://127.0.0.1:8000/login/, instead of this i am trying to load the login page like this URL http://127.0.0.1:8000/ I have tried : LOGIN_URL ='/login/' - (in settings.py) @login_required()- (in the app view.py) @login_required(login_url='/login/') - (in the app view.py) these both method not helped me, kindly someone help me to sort this out. project url.py urlpatterns = [ path('admin/', admin.site.urls), path('',include('home.urls')), ] project settings.py in the bottom i have included like below LOGIN_URL='/login/' LOGIN_REDIRECT_URL= 'home' LOGOUT_REDIRECT_URL ='home' in my app url # from django.urls import path, include from home.views import HomeView urlpatterns = [ path('',include('django.contrib.auth.urls')), path('home',HomeView, name='home'), ] in app view.py from django.http import HttpResponse from django.shortcuts import render @login_required(login_url='/login/') def HomeView(request): return render(request, "home.html") overall my expectation to load the Django default Login page without passing /login/ or account/login in the url. -
Submit button doesn't work in my django project
The submit button doesn't work Can't save in database {% block content %} <form class="" action="{% url 'post_create_url' %}" method="post"> {% csrf_token %} {% for field in form %} <div class="form-group"> {% if field.errors %} <div class="alert alert-danger"> {{ field.errors }} </div> {% endif %} {{ field.label }} {{ field }} </div> {% endfor %} <button type="submit" class="btn btn-primary">Create Post</button> </form> {% endblock %} -
Django List objects that will be deleted by deleting the current object
In my DeleteView template, I'd like to warn the user that deleting the current object will delete the following objects (since the db schema requires on_delete = models.CASCADE). Here is an example model: class Book(models.Model): course = models.ForeignKey(Course, related_name = 'course_books', on_delete = models.CASCADE, null = True, blank = True) class Exercise(models.Model): book = models.ForeignKey(Book, related_name = 'exercises', on_delete = models.CASCADE, null = True, blank = True) ... class Solution(models.Model): exercise = models.ForeignKey(Exercise, related_name = 'solutions', on_delete = models.CASCADE, null = True, blank = True) So, say the user wants to delete a course, I'd like to warn the user which books, exercises, and solutions will be deleted upon deleting the current book. Something to this effect: WARNING: Deleting course Programming 101 will delete Python Programming for Beginners and Python By Example. It will also delete Excersises 1-5 and solutions 1-10 This will require that I can look at the related field to see if the on_delete is set to CASCADE or not. If it is, I should add it to the list of to_be_deleted objects. I have looked to see if I can check the on_delete attribute of the field: for related_object in the_course._meta.related_objects: dir(related_object.field) But nothing shows up … -
Django authenticate method returns None
I am trying to create a user login. I am registering the user through django's admin page. Username and passwords are entered correctly. Also I have tried adding authentication backends to settings.py I have tried multiple ways but couldn't get it to work. AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) My code looks like below : models.py : class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) views.py: def login(request): if request.method == 'POST': username = request.POST.get('user') password = request.POST.get('pass') user = authenticate(username=username, password=password) ----------> None if user: if user.is_active(): login(request, user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse('Account not active') else: print('Someone tried to login and failed ') print('Username {} and passowrd {}'.format(username, password)) return HttpResponse('Invalid login details supplied!!') else: return render(request,'account/login.html', {}) -
Django & Django ORM: performance improvements to bulk updating records
I'm hoping this will be a really simple question. I just wanted some advise on the bulk updating of records. An example bulk update may go something like this: for user in User.objects.all().iterator(): user.is_active = False user.save() Is there a more efficient way to do this on the database level using the Django ORM? Would the following be more efficient: User.objects.all().update(is_active=False)? -
Why is makedirs() creating an empty file instwad of a folder?
I am creating a Django app and using Python to create an upload folder. For now, I am using static names to test. My function creates an empty file only, not a folder. I have tried both mkdir() and makedirs() with the same result. I am testing on Windows 10. This is in my model: def uploadloc(self, irun): if not os.path.exists('device1'): os.makedirs('device1') return 'device1' iimage = models.ImageField(null=True, default=None, upload_to=uploadloc) I think this should be creating a folder but it is only creating an empty file. irun is currently no used. -
Chart js does not load on page
I have the following Django code, it has a list of cards that are automatically generated and each card should be generated a Chart. However, this chart is being generated only on the first card, not the others. What can I be doing wrong? Check out my code {% extends 'base.html' %} {% load static %} {% block title %} Listagem de Linhas {% endblock title %} {% block content %} <div class="row"> {% for row in list %} <div class="col-xs-6 col-md-4"> <div class="card"> <h5 class="card-header">{{row.description}}</h5> <!--<img class="card-img-top" src="{% static 'img/gauge.png' %}" width="100" height="200" alt="Card image cap">!--> <canvas id="myChart"></canvas> <a href="{% url 'row_details' pk=row.pk %}" class="btn botao-detalhar">Detalhar</a> </div> </div> {% endfor %} </div> {% endblock content %} {% block scripts %} <script> var ctx = document.getElementById('myChart').getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'doughnut', // The data for our dataset data: { labels: ["January", "February", "March", "April", "May"], datasets: [{ label: "My First dataset", backgroundColor: ['rgb(0, 99, 132)', 'green', 'red', 'yellow', 'orange'], borderColor: '#fff', data: [5, 10, 5, 2, 20], }] }, // Configuration options go here options: { circumference: 1 * Math.PI, rotation: 1 * Math.PI, cutoutPercentage: 90 } }); … -
Dynamic year wise data in chart.js
I am using chart.js. And i want to know how can i display dynamic date and data using the following queryset. I am using django 2.2 its i could not find any complete tutorials online. views.py def get(self, request, format=None): qs = Add.objects.annotate( month=TruncYear('date')).values('month').annotate(total_income=Sum('budget'), total_expense=Sum('expense')).order_by('month') labels = ["2019",'2020',] default_items = [100, 200 ], data = { "newlabels": labels, "newdata": default_items, } return Response(data) Template var endpoint = '/api/chart/data/' var labels = [] var defaultData = []; $.ajax({ method: "GET", url: endpoint, success: function(i){ labels = i.newlabels defaultData = i.newdata var ctx = document.getElementById('myChart'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: labels, // CHANGED datasets: [{ label: 'sum', data: defaultData, // CHANGED }] } }) }, -
Django - Get mode from ImageField
I want to find out the mode while saving an image. I have a model something like this: class Model(models.Model): image = models.ImageField() def save(self, *args, **kwargs): self.create_dominant_color() super().save(*args, **kwargs) def create_dominant_color(self): color = get_dominant_color(self.image) self.dominant_color = color that's my get_dominant_color (from https://stackoverflow.com/a/34964548/9878135): def get_dominant_color(image_file): im = Image.new(image_file.mode, (150, 150)) ar = scipy.misc.fromimage(im) shape = ar.shape ar = ar.reshape(scipy.product(shape[:2]), shape[2]) codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS) vecs, dist = scipy.cluster.vq.vq(ar, codes) # assign codes counts, bins = scipy.histogram(vecs, len(codes)) # count occurrences index_max = scipy.argmax(counts) # find most frequent peak = codes[index_max] colour = "#" + ''.join(chr(c) for c in peak).encode('hex') return colour -
Another module not found error for django-docs
I am running a Cookiecutter django app. Now I want to integrate django-docs (https://pypi.org/project/django-docs/). I am fairly sure that I am doing it correctly since I am just copy and pasting from the documentation. After installing it I build my docker image anew and run my server. I get the error: ModuleNotFoundError: No module named 'docs.urls' My process was like this: 1) Add app to base requirements django-docs==0.3.1 # https://github.com/littlepea/django-docs 2) Add it to my apps in my config file ... 'allauth.socialaccount', 'rest_framework', 'docs', .... 3) Rebuild docker image docker-compose -f local.yml build 4) Then I added this to my urls which throws me the error: url(r'^docs/', include('docs.urls')), I also tried path('docs/', include('docs.urls')), Is there anything I am missing? THe other SO questions didn't solve my problem. Thanks for any help! Very much appreciated! -
Django - Get a list of values from another model
I installed a third party app which has basically 5 fields: id, name, state, geocode, geometry. I created a new app which I need to import only the values from the 'name' field from the other model. So I basically did this: from django.db import models from django.contrib.auth.models import User from django.contrib.gis.geos import Point from brasil_municipios.models import Municipio #which is the third party app class Escritorio(models.Model): nomeescritiorio = models.CharField(max_length=255) cidade = models.OneToOneField(Municipio.objects.values_list('name').order_by('name')[0:10], on_delete=models.PROTECT, null=True) And got this error: AssertionError: OneToOneField(<QuerySet [('ABADIA DE GOIÁS',), ('ABADIA DOS DOURADOS',), ('ABADIÂNIA',), ('ABAETETUBA',), ('ABAETÉ',), ('ABAIARA',), ('ABARÉ',), ('ABATIÁ',), ('ABAÍRA',), ('ABDON BATISTA',)]>) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' I already tried others ways to solve the issue, using filter(), get() and etc, but all get the same error in all of them. Any tip will be really helpful. Thanks in advance. -
python lxml throwing key error bool while processing kwargs as dict
I'm trying to chain Django Q() objects with code piece below: excludes = None for val in service_dict.values(): field_filter_name = field_name.format(val) exclude_filter = {field_filter_name + "__isnull": True} if excludes is None: excludes = Q(**exclude_filter) else: excludes |= Q(**exclude_filter) On run time, when code hit to excludes = Q(**exclude_filter) line on first loop, throwing this error: File "/lib/python3.6/site-packages/lxml/builder.py", line 218, in call get(dict)(elem, attrib) File "/lib/python3.6/site-packages/lxml/builder.py", line 205, in add_dict attrib[k] = typemap[type(v)](None, v) KeyError: <class 'bool'> I'm quite certain that the values are string type. But this is working on python shell in the same environment: In [9]: Q(**{"foo__isnull": True}) Out[9]: <Q: (AND: ('foo__isnull', True))> I also tried outside of the environment: >>> a = {'foo': True} >>> def k(foo): ... print(foo) ... >>> k(**a) True On the other hand; that kind of usage of the kwargs are working at any other part of the code. How could this issue be solved? -
Django Form Submit 'null value in column "project_id" violates not-null constraint', but Form is valid
I have a form that is two values, a name and a foreign key reference to a parent id. When I submit the form, it validates and I can see the two values (name and parent id), but upon saving I get a null constraint error. Model: class Product(models.Model): """Product object containing LCI information for contained substances.""" name = models.CharField(null=False, blank=False, max_length=255) stages = models.ManyToManyField('LifeCycleStage') project = models.ForeignKey(Project, on_delete=models.CASCADE) Form: class ProductForm(ModelForm): """ Base form for creating a new product. """ # Product Name name = CharField( max_length=255, widget=TextInput({'class': 'form-control mb-2', 'placeholder': 'Product Name'}), label=_("Product Name"), required=True) project_id = IntegerField( widget=NumberInput({'class': 'form-control mb-2', 'readonly': 'readonly'}), required=True, label=_("Parent Project")) class Meta: """Meta data for Product form.""" model = Product fields = ('name', 'project_id') Post method: @method_decorator(login_required) def post(self, request, *args, **kwargs): """Process the post request with a new Product form filled out.""" form = ProductForm(request.POST) if form.is_valid(): product_obj = form.save(commit=True) return HttpResponseRedirect('/products/create/lifecyclestage?product_id=' + product_obj.id) return render(request, "create.html", {'form': form}) Completed and validated form in the view: Completed and validated form in the view Template error: IntegrityError at /products/create/ null value in column "project_id" violates not-null constraint DETAIL: Failing row contains (4, Test Product, null). Request Method: POST Request URL: http://localhost:58661/products/create/ Django … -
Error setting up gdal in windows 10 for my Django project
I am having problems setting up gdal in a Djnago project.I have django and installed ad my virtual environment activated.I also have gda installed via OSGeo4W.Iam using python version 3.7.2 32 bit and postrges database which have have been correctly configured in may settings.py file but whenever I try to migrate it throws an error. This is my settings file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'blog' ] DATABASES = { 'default' : { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME' : 'location', 'USER' : 'postgres', 'HOST' : 'localhost', 'PASSWORD' : 'bjhbchbcjbhc', 'PORT' : '5432', } } Do I need to add the settings to the system PATH?,or could it be that the I need to` install other packages or it to work -
How to use variables in url mapping / Django
I would like to achieve the following when using my dashboard: 1.) When a user selects a different team in the sidebar, the url should change accordingly. Can this be done using a variable in html href tag (and to call the same views function)? If so, how would I have to adapt the url mapping accordingly? 2.) To each team a team_id is assigned. How can I forward this variable (javascript on 'click') to the according views function to make a specific API call or how could a possible workaround look like? So basically I would like to have the user selecting a team and the dashboard to update accordingly (with the view function to make an API call using the individual team_id to get the correct data in return for rendering). At this stage I am searching for a non Ajax solution with reloading the page (since the URL shall change anyways). the related html ecerpt: <!DOCTYPE html> {% load static %} {% csrf_token %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% static "/styles.css" %}"> <link href="https://fonts.googleapis.com/css?family=Muli&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet"> <link rel="shortcut icon" href="/dasocc_site/dasocc_app/static/images/dasoccfavicon.png"/> <title>DASOCC</title> </head> <body> <div id="outerContainer"> <!-- Sidebar --> <div id="sidebar"> <header> … -
Django Rest framework post ForeignKey
I am using DRF to update data. Its works good, but I am struggling how to update foreign keys. { "name": "Ready Or Not", "releases": [ { "platform": { "name": "test" }, "date": "2019-10-02T11:38:18Z" } ] }, This is a response of my API. But I want to update this 'releases' information as well. To sent I have this. If the 'platform' name doesnt exist it should also create one. How do I do this? headers = { 'Authorization': 'Token ' + ss_token, } data = { 'steam_id': 23, "releases": [ { "platform": { "name": "wanttoupdate" }, "date": "2019-10-02T11:38:18Z" }, ], "website": 'testweb' } source = Source.objects.all().first() url = source.url + str(947) + '/' response = requests.patch(url, headers=headers, data=data) My models: class Game(models.Model): name = models.CharField(max_length=255) class Platform(models.Model): name = models.CharField(max_length=255) class Release(models.Model): platform = models.ForeignKey(Platform, on_delete=models.CASCADE) game = models.ForeignKey(Game, related_name='releases', on_delete=models.CASCADE) date = models.DateTimeField()