Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter Django model based on its JSON field
I have the following model: class SavedVariant(models.Model): variant_id = models.TextField(db_index=True) saved_variant_json = JSONField(default=dict) saved_variant_json has a field called transcripts and what I want is to introduce a query Q2() to add it to exiting query Q1() to filter for the content of the transcripts field. Basically what I am trying to avoid is the conversion of the QuerySet into list, parsing json, doing comparisons, etc. Is it possible to do at all? I have initial filtering done with SavedVariant.objects.filter(Q1) and I want to do smth like SavedVariant.objects.filter(Q1).filter(Q2) (or combine both queries: Q3 = Q1 & Q2 using just one filter). If I get a list of SavedVariantmodels, then I would face the issue of rewriting many functions downstream which I don't want to do. -
Why would Submit button stop working by changing from {{ form|crispy }} to listing fields using |as_crispy_field?
I am creating a django app and using crispy forms. The app was working fine and I decided I wanted to change the layout of certain pages. For example, instead of the page listing city, state, and zip on separate lines, I wanted them horizontally side-by-side. I read about how to do this using |as_crispy_field. The only change I made was in my template. I replaced... {{ form|crispy }} with {{ form.company|as_crispy_field }} {{ form.address|as_crispy_field }} {{ form.address2|as_crispy_field }} <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.city|as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> {{ form.state|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ form.zip|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.metro_area|as_crispy_field }} </div> <div class="form-group col-md-5 mb-0 ml-5"> {{ form.phone|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.candidate_pros_and_cons|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.benefits|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-3 mb-0"> {{ form.fee_percentage|as_crispy_field }} </div> <div class="form-group col-md-9 mb-0"> {{ form.fee_structure|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.website|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.linkedin|as_crispy_field }} </div> </div> {{ form.industry|as_crispy_field }} {{ form.notes|as_crispy_field }} This, including my submit button to Post, is contained within the … -
Django filter: different results in filtering between SQLite and PostgreSQL
I have a relatively simple query running on a database table; the filter checks the value of 2 date fields and returns a queryset. The fields checked are authored_report_received and subbed_complete. If authored_report_received has a date set AND subbed_complete has no date set, then a result will be returned. If both these fields have a date set then no results are returned. (A simple calculation for the 'days outstanding' between any result returned and the current date is then made.) This works absolutely fine running locally on a SQLite database but when I upload to heroku to be used with a PostgreSQL database, the filter does not seem to work in that it seems to ignore any date value in the subbed_complete field. I do not understand why not. Is there a difference between the way SQLite and PostgreSQL handles the filters? I can't find any docs which indicate this. # views.py class EpgReportSubeditListView(LoginRequiredMixin, EpgUserPassesTestMixin, ListView): """EPG-only: create a list view of reports currently being subedited """ model = Report template_name = 'tracker/epg_report_subedit.html' context_object_name = 'report_subedit' ordering = ['subeditor'] def get_queryset(self): today = datetime.now().date() out = [] for obj in (self.model.objects.filter(subbed_complete__isnull=True) and self.model.objects.filter(authored_report_received__isnull=False)): setattr(obj, 'days_diff', (today - obj.authored_report_received).days) out.append(obj) return … -
Django loaddata error with oracle CLOB fields/
I have a django project with an oracle backend where I am trying to migrate existing data to a new server. I normally use Postgresql and have limited knowledge of oracle quirks. I've exported the data using python manage.py dumpdata > allmydata.json without a problem. When I go to load the data using python manage.py loaddata allmydata.json I get the following error. ORA-24816: Expanded non LONG bind data supplied after actual LONG or LOB column About half of data loads before I hit this error. My understanding is that all of my LOB columns should be the end of the sql query. My question is how do I make this happen both for loadingdata and for normal operations? Is there a way to force the Django ORM to construct a query in a specific manner? If I change the order of field definitions in the model will that do? The database I am loading into is clean, so I can drop everything if needed. -
Why Django from in Invalid?
I create a django form. I am also inserting the valid values in the form field but still getting form not valid error. I used the same code yesterday and it was working fine, but I don't know why its giving the not valid error, What might be the reason for this? Here is My Code: View.py from django.shortcuts import render,redirect from django.views.generic import View,TemplateView from .forms import Registration_Form from .models import User_Registration from django.contrib import messages # Create your views here. class MainPageView(TemplateView): template_name='main.html' class LoginView(TemplateView): template_name='login.html' def RegistrationView(request): form=Registration_Form() if request.method=='POST': print(request.POST) if form.is_valid(): form.save() print("Valid") return redirect('login_view') else: print("Not Valid") # messages.error(request,"Form is Invalid!") return redirect('registration_view') else: return render(request,'registration.html',{'form':form}) # template_name='registration.html' forms.py from django import forms from .models import User_Registration class Registration_Form(forms.ModelForm): class Meta: model=User_Registration fields=('company_name','username','password','email') widgets={ 'company_name':forms.TextInput(attrs={'class':'form-control input-sm'}), 'username':forms.TextInput(attrs={'class':'form-control'}), 'password':forms.PasswordInput(attrs={'class':'form-control'}), 'email':forms.EmailInput(attrs={'class':'form-control'}), } registration.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> <div class="form-group"> <br><br><br> <h2 style="padding-left: 480px;">Registration Form</h2> <br> <form method="POST" action=""> {{form.as_p}} {% csrf_token %} <input type="submit" value="Submit"> </form> </div> </body> </html> -
"Can't find camera" on local machine triggered from OpenCV
[ WARN:0] global /tmp/pip-req-build-6179nsls/opencv/modules/videoio/src/cap_v4l.cpp (880) open VIDEOIO(V4L2): can't find camera device I'am getting this error while trying to access my webcam I've also tried parameters 0 and -1 in the method cv2.VideoCapture() method as they seem to work in some cases. Is there any way to access the webcam? -
How to import django template library globally?
I have a main template main.html from which I extend from, I want to load the i18m library on it or globally to evade using {% load i18n %} everywhere. How i could do that? -
Can I get AdminEmailHandler to give me a traceback for logging.error level?
I have my Django instance configured with "mail_admins": { "level": "ERROR", "class": "django.utils.log.AdminEmailHandler", }, When I get logging.error() messages, I don't know where they were generated and would like to in order to possibly change their level to squelch noise. Adding include_html=True did not add a stack trace. I've looked through AdminEmailHandler and I haven't found an obvious way to hook this capability in. -
How to run Django FSM first project
I have below django-program--- walk.py from django.db import models from django_fsm import transition, FSMIntegerField from django_fsm import FSMField, transition import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") import django django.setup() from django.core.management import call_command class Order(models.Model): STATUS_GO = 0 STATUS_COME =1 STATUS_CHOICES = ( (STATUS_GO, 'GO'), (STATUS_COME,'come') ) product = models.CharField(max_length=200) status = FSMIntegerField(choices=STATUS_CHOICES, default=STATUS_GO, protected=True) @transition(field=status, source=[STATUS_GO], target=STATUS_COME) def walk(self): print("Target moved") Above code is available in c:\Hello folder. I have referred few blogs & link for creating new django project. so in cmd window, dragged to above folder by "cd c:\Hello" & executed: django-admin startproject mysite And moved walk.py into mysite folder And the directory as : Hello/ mysite/ manage.py walk.py mysite/ __init__.py settings.py urls.py wsgi.py And Later executed: python manage.py migrate python manage.py runserver Post which i have been stuck now & confused above two steps is required for my project. Do python manage.py startapp polls is mandate to run now ? If so, what to edit in polls/models.py file ?? Later what do i need to mention in INSTALLED_APPS = [] ??? And keep moving further, where do i place my project walk.py in above directory ? Now when i run the walk.py , i could see below issue now: … -
DRF How to retrieve auth user info?
Now I can just get info by id. -> user/{id} I want to retrieve self auth user and get his information by default like user My view class UserInfoViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet): permission_classes = (IsAuthenticated,) serializer_class = serializers.UserFollowersSerializer def get_queryset(self): return User.objects.filter(privacy__is_public=True) -
view User model under Teacher model in admin page which has one to one relation with User in Django
Here is models.py file. here Teacher has a foreign key relation with User. from django.db import models from django.contrib.auth.models import User from django.db import models from django.conf import settings from django.utils.text import slugify from django.urls import reverse # Create your models here. import misaka from departments.models import Department teacher_rank = [ ("Lecturer", "Lecturer"), ("Assistant professor", "Assistant professor"), ("Associate professor", "Associate professor"), ("Professor", "Professor"), ("Professor emeritus", "Professor emeritus"), ] class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) department = models.ForeignKey(Department,blank=False, related_name="teachers", on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='teachers/profile_pics', blank=True) Teacher_ID = models.CharField(max_length=20, unique=True, blank=False) portfolio_site = models.URLField(blank=True) academic_rank = models.CharField(blank=False, max_length=100, choices=teacher_rank) teacher_slug = models.SlugField(allow_unicode=True, unique=True) def __str__(self): return self.user.username def save(self, *args, **kwargs): self.teacher_slug = slugify(self.user.username) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("teachers:teacher_detail", kwargs={"department_slug":self.department.department_slug, "teacher_slug":self.teacher_slug}) class Meta: ordering = ["Teacher_ID"] unique_together = ["Teacher_ID", "department"] Here the details of teacher model is viewed under User model in admin page of django. admin.py file from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User # Register your models here. from .models import Teacher class TeacherInline(admin.StackedInline): model = Teacher can_delete = False verbose_name_plural = "teacher" fk_name = 'user' class TeacherAdmin(UserAdmin): inlines = (TeacherInline, ) def get_inline_instances(self, request, obj=None): if not obj: return list() return super(TeacherAdmin, self).get_inline_instances(request, obj) … -
how to use google login link to my login page using django-allauth?
I have created a project which is working nicely. I have a login page, signup page and profile page as myspace. I just want to add an additional funtionality to my login page which is a user can login using google, fb, or instagram. but when i added the django-allauth to my project. it overwrite the existing login page. I just want to add an icon of google login. and not the whole page how i can do so. -
New line not rendering from template tag in HTML
I have a set of information to be rendered on my webpage using django template tags. {% for product in sales %} <div> <span>Customer:{{product.to_user}}</span><br> <span>{{product.time}}</span><br> <p class="message">{{product.message}}</p> </div> {% endfor %} The {{product.message}} template tag contains information separated by new line('\n'). But, newlines are not rendered in HTML, the information is displayed in a single line omitting to obey '\n'. I tried capturing the information from the <p> tag and replacing \n, with <br>, and again setting the text in the same <p> tag. But it doesn't seem to work. This was my approach, as stated above. $(document).ready(function(){ let renderedText = $(".message").text() //alert(renderedText) final_txt = renderedText.replace(/\n/g,"<br>") $(".message").val(final_txt) }) What changes or addition should I make, in order to get this working? Thanks in advance. -
DRF Set base case for RecursiveSerializer
Currently i'm trying to understand how to make a tree representation of a self referentiated model, but im failing to grasp how this recursion works. Currently I have 5 users and my output is as follows: { "user": "user_1", "sponsor": null, "reply_set": [ { "user": "user_2", "sponsor": 1, "reply_set": [ { "user": "user_3", "sponsor": 2, "reply_set": [ { "user": "user_4", "sponsor": 3, "reply_set": [ { "user": "user_5", "sponsor": 4, "reply_set": [] } ] } ] } ] } ] }, ... But I would like to set a limit to the recursion, giving me a tree with with the relations between the user_1 and user_4 only (between only 4 users). { "user": "user_1", "sponsor": null, "reply_set": [ { "user": "user_2", "sponsor": 1, "reply_set": [ { "user": "user_3", "sponsor": 2, "reply_set": [ { "user": "user_4", "sponsor": 3, "reply_set": [ ] } ] } ] } ] }, In the case above, the user_5 still exists and have the user_4 as it's parent, but I do not want to show him in the user_1 tree. Only the relationships between 4 users. My model # models.py class SponsorTree(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) sponsor = models.ForeignKey('self', related_name='reply_set', null=True, on_delete=models.SET_NULL) points = models.DecimalField(default=0, max_digits=900, … -
Creating a folder automatically in Django
So I am trying to create a folder automatically for each user in Django, once they sign up. What I tried: #Creating a folder automatically for each user def folder_path(instance, filename): return "user_{0}/MyFolder/{1}".format(instance.user.id, filename) # Create your models here. class MyModel(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, default= None) user_folder = models.FileField(upload_to= folder_path, default= None) views.py myfolder = MyModel(user_folder= '/path/to/folder/') I also tried: #Creating a folder automatically for each user def folder_path(instance, filename): user = instance.user.username basename, file_extension = filename.split(".") new_filename = "%s-%s.%s" %(user, instance.id, file_extension) return "MyFolder/%s/%s" %(user, new_filename) # Create your models here. class MyModel(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, default= None) user_folder = models.FileField(upload_to= folder_path, default= None) views.py myfolder = MyModel(user_folder= '/path/to/folder/') I want to know why its not working. Thanks. -
How to change error response message of TokenObtainPairView?
TokenObtainPairView class is used for token based authentication with jwt token now i am getting error message as when i put wrong login detials for user { "detail" : "No active account found with the given credentials" } i want to change it like { "detail" : "email or password is incorrect!" } -
How to tag current page on navbar list?
I am using Django, so I have header.html that is included on every page. How can I change the header so it recognizes the active page and makes it selected. {% load static %} <header> <div id="header"> <div id="logo"> <div id="logo_text"> <!-- class="logo_colour", allows you to change the colour of the text --> <h1><a href="/home">Priimo<span class="logo_colour">Puit</span></a></h1> <h2>Hea puit!</h2> </div> </div> <div id="menubar"> <ul id="menu"> <!-- put class="selected" in the li tag for the selected page - to highlight which page you're on --> <li class="selected"><a href="/home">Esileht</a></li> <li><a href="/products">Tooted</a></li> <li><a href="/services">Teenused</a></li> <li><a href="/about">Meist</a></li> <li><a href="/contact">Kontakt</a></li> </ul> </div> </div> </header> -
raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'doc' in line csv_file =request.FILES['doc']
I really spent a lot of time trying to solve this problem. Here is my views.py def data_upload(request): template="Try.html" prompt ={} if request.method == "Get": return render (request, template, prompt) if request.method == 'POST': csv_file =request.FILES['doc'] print(csv_file.name) print(csv_file.size) if not csv_file.name.endwith('.csv'): message.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) the error is in the line csv_file =request.FILES['doc'] -
Unable to use logout function in django with react app
I want to logout user from django.auth from react component and I don't know how should i integrate my urls with react app. And i have no problem with login its working correctly. when i login from my login form it also logged in my django/admin, but when i logout from my website it does not log out from my admin panel. Api app urls.py from django.urls import path from backend.api.views import * app_name = 'backend' urlpatterns = [ path('booklist/', api_user_details, name='userdetails'), path('login/', login_auth , name='login'), path('signin/', Signin , name='Signin'), path('usercheck/', checkusername , name='usernamecheck'), path('update/', update , name='update'), path('logout/', logout_view , name='logout') ] Api Views.py from django.contrib.auth import logout def logout_view(request): logout(request) return redirect('login') React app component import React,{useContext} from 'react'; import './profile_name_block.css'; import profileimg from '../../../person.png'; import { UserContext } from '../../../contexts/UserContext'; // import login from '../../../icons/login.png' import logout from '../../../icons/login.png' import profile from '../../../icons/profile.png' import bookico from '../../../icons/books.png' import request from '../../../icons/request.png' const Profiled = () => { // eslint-disable-next-line const [user,setUser]=useContext(UserContext); const Logout = () => { setUser({ logged: false, User_details: {} }) localStorage.clear(); window.location.href='/api/logout'; } const expand = () => { var x = document.getElementById('profile_log'); console.log(x.style.display) if (x.style.display === 'none' || x.style.display === '') { x.style.display … -
Can't pull all static files from heroku using git pull heroku master
So I was using Django admin page from the Heroku server to add some data that includes static pictures, and when I wanted to pull that static pictures to my local project it shows the usual Already up-to-date. message. I have tried cloning the project but still don't get the files that I need. and yes the pictures are there because I can open it from the Django admin page. I know that I was supposed to work locally then push, but it was already done and I want to know is there any solution for this ? -
how to add order by date_created in a django loan history model
class LoanInfoStatusHistory(models.Model): """Model that saves a history of a loan.""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # pylint: disable=invalid-name loan = models.ForeignKey(Loan, on_delete=models.PROTECT) previous_status = models.CharField(choices=Loan.LOAN_STATUS, max_length=20) new_status = models.CharField(choices=Loan.LOAN_STATUS, max_length=20) update_date = models.DateTimeField(auto_now_add=True) def __str__(self): """ Unicode representation for a LoanInfoStatusHistory model. :return: string """ return '{}: {} - {}'.format(self.loan.id, self.previous_status, self.new_status) -
function detailed view is not redirecting to detailview.html page
i am trying to create a detailview in django.. when i am clicking in the listview items.. the url in browser is shoing id .. like http://localhost:8000/blog/2 but it is giving 404 page not found error.. please see.. views.py def detail_view(request, id=None): movie = get_object_or_404(BlogPost, id=id) context = {'BlogPost':BlogPost, } return render(request, 'blog/blogdetail.html', context) urls.py path('list', BlogList.as_view(), name='list'), path('(?P<id>\d+)',detail_view, name='detail') list.html <div class="post-body"> {% for p in post %} <a href="{{ p.id }}"><blockquote>{{p}}</br></br>{{p.Date}}</blockquote> </a> {% endfor %} the blogdetail.html page is in the same directory in which bloglist.html page is.. models.py class BlogPost(models.Model): title = models.CharField(max_length=500) writer = models.CharField(max_length=150,default='my dept') category =models.CharField(max_length=150) image = models.ImageField(upload_to='images') post = models.TextField(max_length=2000) Date = models.DateField( default=datetime.date.today) -
Click button in table and redirect to same page
I have a view: class ProductList(SingleTableView): model = Product template_name = "app/product_list.html" table_class = ProductTable where in every row there is a button that should perform function(): class ButtonColumn(tables2.Column): empty_values = list() def render(self, value, record): return mark_safe(f"""<a href="/link/{record.id}/"><button class="btn btn-info">link</button></a>""") this ButtonColumn provides a button and once it is clicked: path("link/<int:pk>", views.LinkView.as_view(), name="link"), And the corresponding view: class LinkView(TemplateView): model = Product template_name = "app/product_list.html" def get_success_url(self): return reverse_lazy('product-list') def get_context_data(self, **kwargs): context = super(LinkView, self).get_context_data(**kwargs) function[kwargs] # <------------------ context["table"] = Product.objects.all() return(context) My problem is with the Linkview - I want it to perform function with some URL transmitted paramters and return to the former page (app/product_list.html). How can I achieve this? -
How to call shared_task asynchronously
I have such celery-task from celery import shared_task @shared_task def send_to_sap(act_id): act = ActOfWithdrawal.objects.get(pk=act_id) if settings.SYNCHRONIZATION: response = requests.post( settings.PI.API_CREATE, json={} ) And I want to execute it in asynchronous mode from view, and I'm trying to do this like this from tasks import send_to_sap def send_to_sap(request, pk): # some logic... if serializer.is_valid(): serializer.save() send_to_sap.apply_async(kwargs={'act_id': pk}) return Response(status=status.HTTP_200_OK) -
CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed
I recently encountered this error. CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. I had Ubuntu 20x Django 3x Python 3.8 / venv here i am writing how i fixed the error It turns out that Django didn't see my gettext and I had to install it. sudo apt-get install gettext