Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DjangoCMS TypeError: from_db_value() missing 1 required positional argument: 'context' after upgrade to 3.7.2 w/ Django 3.0.1
I had a working DjangoCMS application running DjangoCMS 3.7.1 and Django 2.2, however after I just bumped the DjangoCMS version to 3.7.2 and with it, Django to 3.0.1, I am now getting a render error on a page that I have a simple list view. The site will load my custom account login page just fine, but once logged in, the listview breaks and displays this error: Traceback django.request ERROR 2020-04-26 21:15:16,809 log 461 140647593613056 Internal Server Error: /en/ Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/usr/local/lib/python3.8/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/usr/local/lib/python3.8/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/usr/local/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/usr/local/lib/python3.8/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "/usr/local/lib/python3.8/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/usr/local/lib/python3.8/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 903, … -
how do i get the id immediately after inserting the data?
I hope the title is enough to understand what my problem is, I have this code in my views.py enroll = StudentsEnrollmentRecord( Student_Users=student,Old_Student=old,New_Student=new, Payment_Type=payment,ESC_Student=esc,Last_School_Attended=last,Address_OF_School_Attended=add, Education_Levels=educationlevel,School_Year=schoolyear,Courses=course,strands=strands,Student_Types=stype,GWA=gwa ) enroll.save() studentenrolment = StudentsEnrollmentRecord.objects.filter(Student_Users=enroll) return render(request, "print.html", {"studentenrolment":studentenrolment}) This is the error i get -
I do not get show data in the datatable angular 2.x
well, I make a web app with django and angular, the API is good but I'm newbie with angular and I don't understand that I'm wrong. import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class ListarPersonasService { public personas:any = null; constructor(private http: HttpClient) { } public obtenerPersonas() { const url = 'http://127.0.0.1:8000/api/v1.0/abogado/personas'; return this.http.get(url).subscribe( res => { this.personas = res; console.log(res); } ); } } this is my service, on the component the service to make the request is called and store the result in the variable datasource import { Component, OnInit } from '@angular/core'; import { ListarPersonasService } from "../servicios/listar-personas.service"; @Component({ selector: 'app-listar-personas', templateUrl: './listar-personas.component.html', styleUrls: ['./listar-personas.component.css'] }) export class ListarPersonasComponent implements OnInit { displayedColumns: string[] = ['documento','nombre', 'apellido']; dataSource : any; constructor(private listar:ListarPersonasService) { } ngOnInit() { this.dataSource = this.listar.obtenerPersonas() } } and here this html. <table mat-table [dataSource]="persona" class="mat-elevation-z8"> <ng-container matColumnDef="documento"> <th mat-header-cell *matHeaderCellDef>documento</th> <td mat-cell *matCellDef="let element">{{element.documento}}</td> </ng-container> <ng-container matColumnDef="nombre"> <th mat-header-cell *matHeaderCellDef> Nombre</th> <td mat-cell *matCellDef="let element"> {{element.nombre}}</td> </ng-container> <ng-container matColumnDef="apellido"> <th mat-header-cell *matHeaderCellDef> Apellido</th> <td mat-cell *matCellDef="let element"> {{element.apellido}}</td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table> here is the … -
I want to ignore all the locale files in venv and compile others
I am making a locale directory to store the translations in it but I have venv which contains so many locale files.. I want to ignore them and only compile the ones I have made. I already have written in the setting LOCALE_PATHS = ( os.path.join(BASE_DIR, 'Medical_Healthcare_System/locale'),) but when I use compile messages command it compiles only the venventer image description here -
Environ variables in .env file in Django and docker
Hi I'm using Docker to build a Django web application for production via Docker-Compose and it uses the .env.prod file for the environmental variables. The docker-compose file works fine and deploys to a server with no issues via CI/CD on GitLab. I was hoping to use the same kind of structure but just have a .env.dev file so I don't have to modify the settings file in any way. The problem I'm having is I can't find how to set environment variables from an external file in development mode. The only workaround I can see is having a local_settings.py file which I was hoping to avoid. Example of what I'm trying to achieve below in the settings.py file. DEBUG = int(os.environ.get("DEBUG", default=0)) with a .env.dev file. DEBUG=1 DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 149.28.188.180 [::1] Thanks in advance. I'm sure I'm missing something easy. -
Create Django HTML Button that will Change BooleanField in Model
I am a beginner with Django and am hoping to get pointed in the right direction. I am building a webapp that has job postings on it, and I would like to have an "Accept this job" button on each job description page that will change a BooleanField I defined in the model to True. This way, no other users may be able to take on the job. Are there any suggestions? My database is SQLite. -
Django search view not generating html page I set
I am having trouble getting my search form to work in Django. When I search anything in the search bar I have set, I get an html page that just has the words Search on it. It's not the html page I set, though. My search template is in my projects templates directory. I am trying to search through my blog posts, and have attached my views and urls code. This portion of my base template is within a navbar I grabbed from a sample Bootstrap blog template. This is the sample template. I've changed some things within my form. base.html ... <form class="form-inline my-2 my-lg-0" action="{% url 'search' %}" method="GET"> <input class="form-control mr-sm-2" type="search" name="q" placeholder="Search blog posts..."> <button class="btn my-2 my-sm-0" type="submit">Search</button> </form> ... Nothing within my blocks shows up when I view it. The tags <p>TEST</p> and <p>Is this working?</p> are not showing up. Neither is the block for the jumbo_content. I have set those correctly in my base.html, because they work with my other pages. It's just the search page it doesn't work on. search.html {% extends "base.html" %} {% load static %} {% block jumbo_content %} <h1 class="display-4">Search Results</h1> {% endblock %} {% block page_content … -
PostgreSQL text search in Django not working as expected
I am implementing a search function for my API to return the object's properties when requested. So far I have tried to use Full Text Search which is usable but it has these annoying things: words have to be spelled correctly for the results to be returned and partial search, for example "appl" instead of "apple", won't work. I have also tried Trigram Similarity but it failed for long sentences. How do I implement a search function that is both accurate and fuzzy in Django? This works This won't work This is my views.py from django.shortcuts import render from rest_framework.response import Response from rest_framework import status from rest_framework.decorators import api_view from .models import Object_Locations from .serializers import Object_LocationsSerializer from django.contrib.postgres.search import SearchVector, SearchQuery def index(request): return render(request, 'main/base.html', {}) @api_view(['GET',]) def LocationsList(request): if request.method == 'GET': vector = SearchVector('name', 'desc', 'catergory') query = request.GET.get('search') if query: locations = Object_Locations.objects.annotate(search=vector,).filter(search=SearchQuery(query)) else: locations = Object_Locations.objects.all() serializer = Object_LocationsSerializer(locations, many=True) return Response(serializer.data) -
Does it possible that transaction.atomic does not work as expected?
This is a DRF API View for entry like. When someone like a entry, i will insert a like record into table entry_like, and plus by 1 to field likes_num in another table entry. But, something went wrong that some of the count of entry_like records corresponding to one entry is less than the field likes_num in table entry. I do not know why it does not work as expected even the post method is with decorator transaction.atomic on. Are there some cases that the decorator transaction.atomic does not run as expected? -
Is there any way to style the field alerts in Django?
I'm working on the style of my website and I'd like to style this part of the form: I tried with field.errors but that's not it. Any ideas? -
Is there an alternative for django admin for Postgres + Hasura?
I was wondering if there are any tools for auto generated content management systems that built on top of postgres/hasura -
Django form, display through field in a form
I have 3 models, shown below. I want to display a form where i can create a navMenu with posts and then select the position of those posts, I can bring in the post to a form but I don't know how to add the through field post_postiton into the form, any help would be very much appreciated -
Django views.py to call python script to open PDF
Target: I want to develop web app automation tool with Django framework for PDF data extraction. It is not like converting entire data of PDF file, It is like specified field in PDF. Specified field can be specified with mouse clicks. Automation script should perform opening PDF files continuously in the folder and extract specified field. Actions completed I have completed python script to open PDF file, and extracting particular field with mouse listener activity and convert it to image and convert to text. Question Can someone confirm whether i can use above python script in django also. I mean whether mouse listener libraries will work in django. It is kind of desktop automation to be called by web application. please confirm whether this is possible. #opening pdf file. can be changed to open list of PDF files in folder def openFile (): os.system("start " + 'AF0002345_Copy.pdf') # i have extracted image from pdf with help of mouse listener activity # below function to convert image to text def ocr_core(filename): pytesseract.pytesseract.tesseract_cmd = r'C:\Users\150629\AppData\Local\Tesseract-OCR\tesseract.exe' text = pytesseract.image_to_string(Image.open(filename)) return text -
How can I fix "ERROR: Command errored out with exit status 1:" when trying to install django-visits
I am trying to install django-visits, but anytime I run the "pip install django-visits" command, I get the following error: ERROR: Command errored out with exit status 1: command: 'c:\users\samuel\appdata\local\programs\python\python37\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Samuel\\AppData\\Local\\Temp\\pip-insta ll-8t2j3cs9\\distribute\\setup.py'"'"'; __file__='"'"'C:\\Users\\Samuel\\AppData\\Local\\Temp\\pip-install-8t2j3cs9\\distribute\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__fi le__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3c s9\distribute\pip-egg-info' cwd: C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\ Complete output (15 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\setuptools\__init__.py", line 2, in <module> from setuptools.extension import Extension, Library File "C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\setuptools\extension.py", line 5, in <module> from setuptools.dist import _get_unpatched File "C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\setuptools\dist.py", line 7, in <module> from setuptools.command.install import install File "C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\setuptools\command\__init__.py", line 8, in <module> from setuptools.command import install_scripts File "C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\setuptools\command\install_scripts.py", line 3, in <module> from pkg_resources import Distribution, PathMetadata, ensure_directory File "C:\Users\Samuel\AppData\Local\Temp\pip-install-8t2j3cs9\distribute\pkg_resources.py", line 1518, in <module> register_loader_type(importlib_bootstrap.SourceFileLoader, DefaultProvider) AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.``` How can I fix it? -
change image index using jQuery
I have a list of images rendered from Django as follows: <div class="gallery"> <div class="slider-info"> <span class= "pagenum"> <span class="range"> <span id="currentIndex" class="currentIndex"> 1 </span> - <span id="totalCount" class="totalCount"> {{ item.images_cars_trucks_set.all|length }} </span> </span> </span> </div> <!-- images --> <span class="result-image-act"> <span class="img-group"> {% for image in item.images_cars_trucks_set.all %} {% if image.car_images_exists %} {% if forloop.counter == 1 %} <img src="{{image.car_images.url}}" class="active" id="{{image.id}}"> {% else %} <img src="{{image.car_images.url}}" id="{{image.id}}" class=""> {% endif%} {% endif %} {% empty %} <img src="{% static 'towns/images/list_page/no_image_available.png' %}" class="active" id="{{image.id}}"> {% endfor %} </span> <!--slide images --> <div class="swipe-wrap"> <div class="swipe-wrap-lef"> <span class="move" > <div class="swipe-prev"> <p>&lt;</p> </div> </span> </div> <div class="swipe-wrap-rig"> <span class="move" > <div class="swipe-next"> <p>&gt;</p> </div> </span> </div> </div> </span> </div> I have a jQuery script to change the displayed image when mouse hover on specific one as follows: <script type="text/javascript"> $(document).ready(function(){ $('.thumb-nails img').each(function(){ $(this).mouseover(function(){ $(".thumb-nails img").removeClass('img-border active'); $(this).addClass('img-border active'); var current_img = $(this).attr('id'); var image_displayed = $(this).attr('src'); $(".result-image-act img.active").removeClass('active'); $(".result-image-act img[id="+current_img+"]").addClass('active'); $('.result-image-act img.active').attr('src', image_displayed); }); }); }); The question is: How can I add to the Jquery script to indicate the image index number. I though to add number 1 to the first image and then replace each image ID with … -
How to add a value to an existing model record with the use of Django Forms?
I'm trying to make a form that adds points to a user's account. This form chooses which user and it should add it based on the value added. I don't know what I did wrong. No hints in the terminal to show what I did wrong. I just doesn't submit. The only indication that I screwed up is it shows that !form.is_valid based on the error message that I set. Here is my forms.py: class addpointForm(forms.ModelForm): add_point_field = forms.IntegerField(widget=forms.NumberInput) class Meta: model = Points fields = ['user'] Here is my views.py: def pointform(request): if request.method=='POST': form = addpointForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user messages.success(request, 'Success! Points has been added!') instance.points += addpointForm.add_point_field instance.save() else: messages.error(request, 'Oh no! Points has an error!') form = addpointForm() return render (request,'users/addpoints.html',{'form':form}) I just some help to point me in the right direction. Any help is appreciated thank you. -
Two foreign keys, only one can be not null at a time
I have a database table with two foreign keys pointing to two different tables. The business logic requires an "either or" relationship; only one foreign key can be NOT NULL at any given time. Here are the four possible states the foreign keys can hold based on the business logic: NULL, NULL - okay number, NULL - okay NULL, number - okay number, number - invalid business logic I'm using Django, and I know I can write some onSave() checks that will handle this, but that feels hackish. Is there a better method to deal with this business logic? -
Django AUTH_USER_MODEL refers to model '%s' that has not been installed
I've got the following models: from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from django.conf import settings class User(AbstractUser): username = models.CharField(blank=True, null=True) email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] def __str__(self): return "{}".format(self.email) class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile') dob = models.DateField() phone = models.CharField(max_length=15) active = models.BooleanField(default=True) receive_newsletter = models.BooleanField(default=False, blank=True) So I have overwritten the default AUTH_USER_MODEL in settings.py to be: AUTH_USER_MODEL = 'myapp.User' but I'm getting the following error when running migrations: "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'kofiapi.User' that has not been installed My project's structure is as follows: myapp api users - models.py myproject settings.py I have tried the following variations yet all failed: AUTH_USER_MODEL = 'myapp.api.users.User' AUTH_USER_MODEL = 'myapp.users.User' AUTH_USER_MODEL = 'myapp.api.User' AUTH_USER_MODEL = 'myapp.User' Any indication of what am I doing wrong? -
After updating the post, I want the user to be redirected to the post (Django - Python)
I want the user to be able to update existing posts. When the user clicks Update, then Post, they get an error message saying there is no URL to direct to. But the post does get updated on the backend. I thought the line return reverse('article_detail', kwargs={'slug': self.slug}) would redirect them back to their original post. class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now()) author = models.ForeignKey(User, on_delete=models.CASCADE) url= models.SlugField(max_length=500, blank=True) #url= models.SlugField(max_length=500, unique=True, blank=True) def save(self, *args, **kwargs): self.url= slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', kwargs={'slug': self.slug}) Here is the table schema. sqlite> .schema blog_post CREATE TABLE IF NOT EXISTS "blog_post" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(100) NOT NULL, "content" text NOT NULL, "url" varchar(500) NOT NULL, "author_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED, "date_posted" datetime NOT NULL); CREATE INDEX "blog_post_url_5af1045a" ON "blog_post" ("url"); CREATE INDEX "blog_post_author_id_dd7a8485" ON "blog_post" ("author_id"); sqlite> -
what i need to do for loading static
Hey everybody i have a problem with this code which i try to run on local host server , in this situation im followin an online project over youtube and he is trying to make an online resume, at the start we tried to make a simple home template which i stock in it so if u can help me to fix the problem in which cause to rise this error 'Static' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz and this the code itself: {% load Static %} <link href="{% static '/css/main.css' %}" rel= "stylesheet" type="text/css"> <h3> Hello world! <h3> <img src="{% static 'images/me.profile.jpg'%}" this is the setting.py by the way: STATIC_URL = '/static/' MEDIA_URL = '/Images/' STATIC_DIRS= [ os.path.join(BASE_DIR, 'static') ] -
I'm pulling a dictionary from an API call, when I pull URL information it quotes and brackets around them
I'm sure this will be an easy one for you guys, but I can't figure it out. I'm pulling the website information using a call in my Django template. All the information is getting pulled, but when I pull the website it has quotes and brackets around it like '[https://xxxxx.org]' obviously when I create the {{ web.site }} tag around it, it can't browse to the site. Is there a quick way to strip off all the extra '[]' around the URL? -
What is the most efficient way to make Post previews on Django?
I am making a Blog where I want for the home page to show only the first 100 characters of each post. My point is to make better use of space. If a person want to read a post, that person can just click to read it. I have some ideas on how to do it, but I think they won`t work or are inefficient: To create a subclass on blog models.py where I would inherit the Post class, save the first hundred characters of each content to a list and make a loop to save each list on the database; To place a instruction on blog views.py 'FirstPageView' class where it would only exhibit the first hundred characters. The 'Post' and 'FirstPageView' mentioned classes are as follows: on 'blog/views.py': from django.views.generic import ListView class FirstPageView(ListView): model = Post template_name = 'Blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 6 on 'blog/models.py': from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, models.SET_NULL, blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) So what would be … -
Do I have to use Redux with React for authentication?
This may be a stupid question. So, I am using Django for my backend and React for my frontend. The goal is to only show the objects that belong to the user that is making the request. Since Django takes care of authentication, do I need to use Redux, or any other framework for that matter, for authentication? Couldn't I just do something like: request.user.something.objects.all() on my backend when I receive the Axios request from my frontend? Do Axios request even provide the user? -
Can id field in django models be the same with two app instances running?
I don't understand well, how does django's autofield work... If I will run two app instances using gunicorn, will it be possible that my models get same autofield id? I have a model Message and I want to check it's instance's id, but I want to be absolutly sure, that the ids are unique and are going by adding order. -
How to store images like Images API
Hi this my model for create simple member already searched for several places and until now I haven't figured out how I can store the directory of my image next to my image field. class Member(models.Model): with open(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+'/api/data/states.json') as s: states_json = json.load(s) STATES = [(str(state["nome"]), str(state["sigla"])) for state in states_json] name = models.CharField(max_length=100, null=True, blank=True, verbose_name='Nome') image = models.ForeignKey( "wagtailimages.Image", blank=False, null=True, related_name="+", on_delete=models.SET_NULL, verbose_name='Imagem do membro', ) role = models.CharField(max_length=35, null=True, blank=True, verbose_name='Cargo') city = models.CharField(max_length=30, null=True, blank=True, verbose_name='Cidade') state = models.CharField( verbose_name='Estado', max_length=19, choices=STATES, default=('SP'), ) created = models.DateField(default=timezone.now, verbose_name='Atualizado') modified = models.DateField(default=timezone.now, verbose_name='Modificado') panels = [ FieldPanel("name"), ImageChooserPanel("image"), FieldPanel("role"), FieldPanel("city"), FieldPanel("state"), FieldPanel("created"), FieldPanel("modified"), ] def __str__(self): return self.name class Meta: verbose_name = 'Membro' verbose_name_plural = 'Membros' This work normally but how to store image informations like Wagtail Images API? Example: "detail_url": "http://localhost/api/v2/images/2/", "download_url": "/media/original_images/l8GlI3V.jpg" This my JSON from API [ { "id": 6, "name": "Gabriel", "role": "Desenvolvedor", "image": 4, "city": "Itapetininga", "state": "São Paulo", "created": "2020-04-26", "modified": "2020-04-26" } ] Thanks for help!!!