Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model Admin: How to auto assign and hide created_by field with current user and display after save?
I am working certain model Accounting which consists of following model attributes. class Accounting(model.Model): booking = models.OneToOneField(Booking, on_delete=models.PROTECT, null=True) description = models.CharField(max_length=100, validators=[]) created_by = models.ForeignKey(User, on_delete=models.PROTECT) bus_company = models.ForeignKey(BusCompany, models.PROTECT) in admin.py I have done so far @admin.register(Accounting) class AccountingAdmin(ModelAdmin): list_display =( 'bus_company', 'description ', 'bus_company ', ) Now when I use Django admin for adding Accounting. I want to hide created_by and want to set the current logged in user as the created_by. Currently it is superuser so after adding of data The created_by fields also gets update and displayed how can I do this? -
I am getting this operational error while making my web app
I am currently learning Python from a course Python by code with Mosh. In his course he has explained to build a web app using Django. While I was running my app on web server, I got an error "OPERATIONALERROR" and now I am stuck in it. A picture of error I am receiving: -
How to overwrite Django app to Pythonanywhere?
After the second time deploying the Django app to Pythonanywhere, (I re-edited and overwritten in VS code and did git push) I got the following error. WARNING: Package(s) not found: django Traceback (most recent call last): File "/home/hogehohe/.local/bin/pa_autoconfigure_django.py", line 47, in <module> main(arguments['<git-repo-url>'], arguments['--domain'], arguments['--python'], nuke=arguments.get('--nuke')) File "/home/hogehohe/.local/bin/pa_autoconfigure_django.py", line 36, in main project.update_settings_file() File "/home/hogehohe/.local/lib/python3.6/site-packages/pythonanywhere/django_project.py", line 74, in update_settings_file new_django = version.parse(self.virtualenv.get_version("django")) >= version.parse("3.1") File "/home/hogehohe/.local/lib/python3.6/site-packages/pythonanywhere/virtualenvs.py", line 32, in get_version output = subprocess.check_output(commands).decode() File "/usr/lib/python3.6/subprocess.py", line 356, in check_output **kwargs).stdout File "/usr/lib/python3.6/subprocess.py", line 438, in run output=stdout, stderr=stderr) subprocess.CalledProcessError: Command '['/home/hogehohe/.virtualenvs/hogehohe.pythonanywhere.com/bin/pip', 'show', 'django']' returned non-zero exit status 1. The command is $ pa_autoconfigure_django.py https://github.com/[user_name]/[project_name].git --nuke The first deployment succeeded but the second one is not. I don't know the cause and how to overwrite it... -
This version of djongo does not support indexes on embedded fields
raise NotSupportedError(djongo.exceptions.NotSupportedError: This version of djongo does not support indexes on embedded fields from djongo import models class MetaData(models.Model): date = models.DateTimeField(auto_now=True) class Meta: abstract = True class Posts(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True, blank=True) content = models.TextField(blank=True) meta_data = models.EmbeddedField(model_container=MetaData) def __str__(self): return self.title class Meta: db_table= 'post' ordering = ['title'] -
Search Query Exact Match in ListView, Redirect to DetailView - Django
Using a ListView to display search results from a user query. How can I add a redirect if the item they search for has an exact match, to that specific DetailView? class WikiSearchView(ListView): template_name = "encyclopedia/wiki_search.html" model = Entry paginate_by = 25 context_object_name = "searchResults" def get_queryset(self): search = self.request.GET.get('q') object_list = Entry.objects.filter(Q(title__icontains=search)) return object_list I tried to add a try/except with Entry.objects.get to look for an exact match and then use a return redirect(xyz), but that didn't work. -
How to send video stream from node.js to django server?
My requirements is to use django as server and node.js for live video calling. I have seen this question but don't know how to accomplish it to reach my requirements? Currently, i have this below code - frontend script --> const socket = io('/') const videoGrid = document.getElementById('video-grid') const myPeer = new Peer() // const myPeer = new Peer(undefined, { // host: '/', // port: '3001' // }) const myVideo = document.createElement('video') myVideo.muted = true const peers = {} navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(stream => { addVideoStream(myVideo, stream) myPeer.on('call', call => { call.answer(stream) const video = document.createElement('video') call.on('stream', userVideoStream => { addVideoStream(video, userVideoStream) }) }) socket.on('user-connected', userId => { connectToNewUser(userId, stream) }) }) socket.on('user-disconnected', userId => { if (peers[userId]) peers[userId].close() }) myPeer.on('open', id => { socket.emit('join-room', ROOM_ID, id) }) function connectToNewUser(userId, stream) { const call = myPeer.call(userId, stream) const video = document.createElement('video') call.on('stream', userVideoStream => { addVideoStream(video, userVideoStream) }) call.on('close', () => { video.remove() }) peers[userId] = call } function addVideoStream(video, stream) { video.srcObject = stream video.addEventListener('loadedmetadata', () => { video.play() }) videoGrid.append(video) } backend in javascript(server.js) --> const express = require('express') const app = express() const server = require('http').Server(app) const io = require('socket.io')(server) const { v4: uuidV4 } … -
How can i use jsonfield in F expression?
i have jsonfield in model,and i want to run this query: Notification.objects.filter(Q(data__payload__request_visit_time__gte=(timezone.now() - timedelta(minutes=1) * ((1 + F("data__payload__visit_duration_plan")) * 15)).isoformat())) but jsonfield do not work in F expression. -
Payment gateway integration for sending an amount
I need your suggestion to integrate a payment gateway in my app. The situation is - Customer will create a booking. Driver will accept the booking. After successful delivery customer will pay online. The amount will go to app owner. Automatically, after deducting the commission amount to go from app owner to driver account So, here, I am getting two types of payment process - receiving payment sending payment I can implement option 1(receiving payment) part normally with payment gateway integration. But, my problem is with option 2(sending payment). Can we do it with payment gateway? If yes then give me some ideas. what should i search for or may be some service name... Any help would be appreciated.. Thanks.. (Note-paypal/stripe does not support the currency I am looking for). -
Django All-Auth not redirecting to LOGIN_URL
I have all-auth setup and working, however I cannot get the LOGIN_URL to work and redirect to '/accounts/login/' as the default view by overriding the all-auth login template. settings.py LOGIN_URL = '/accounts/login/' If I go to localhost/accounts/login, I can get the page fine, however I am not able to get the above working in having it be the default location when localhost is visited. I may be misunderstanding the docs and how it is supposed to be working. Any help is appreciated. -
Update and Create multiple new objects DRF
I'm trying to retrieve multiple objects, update and create new objects on updation, I'm able to do it on single object, how to do the same for multiple objects. Sample Payload: { "data": [ { "employee": 296, "emp_name": "C", "position": "ZZ", "shift": 2, "punch_date": "2020-12-22", "actual_clock_in_datetime": "2020-12-22T12:14:09Z", "actual_clock_out_datetime": null, "supervisor": 319, "work_location": 47, "costing_type": "direct non-manuals", "emp_status": "active", "is_selected": true }, { "employee": 293, "emp_name": "B", "position": "YY", "shift": 2, "punch_date": "2020-12-22", "actual_clock_in_datetime": "2020-12-22T12:15:09Z", "actual_clock_out_datetime": null, "supervisor": 319, "work_location": 47, "costing_type": "direct non-manuals", "emp_status": "active", "is_selected": true } ] } class PunchRawDataProcessSerializer(serializers.ModelSerializer): is_selected = serializers.NullBooleanField() class Meta: model = PunchRawDataProcesses fields = ['employee','emp_name','position','shift','punch_date','actual_clock_in_datetime', 'actual_clock_out_datetime','supervisor','work_location','costing_type','emp_status','is_selected'] def update(self, instance, validated_data): instance.work_location = validated_data['work_location'] instance.supervisor = validated_data['supervisor'] instance.is_selected = validated_data['is_selected'] instance.pk = None instance.save() return instance I tried using -
Django Group by Month and count distinct users for each month
I am trying to get count of distinct users in each month FieldOpsBooking.objects.using( 'analytics').filter(**filter_query).annotate(transacting_users=Count( 'vehicle_owner_organization_id', distinct=True),month=TruncMonth('pick_up_at')) I am new to annotate and aggregate and after searching through SO I seem to find this Django: Group by date (day, month, year). But I need to provide values to annotate on which it groups by and then the result is not the same as required. Any help is appreciated. -
django subquery without using group by
class Config(models.Model): id = models.IntegerField(max_length=20, primary_key=True) appid = models.IntegerField(max_length=20) status = models.IntegerField(max_length=2) user_id = models.ForeignKey(User) name = models.IntegerField(max_length=10,null=False,default='0') path = models.CharField(max_length=500,null=False,default='') create_time = models.DateTimeField() class User(models.Model): hostip = models.IntegerField(max_length=20) I need to know how to write a django subquery. I need equal django query for below MySQL query. select * from ((select A.appid,User.hostip ,A.name,A.path,A.status,A.create_time from Config as A left join User on A.appid = 1255 and User.hostip= '172.16.0.3') as B ) group by B.name order by B.create_time; Kindly let me know.................. -
DJANGO Rest API - Method POST Not Allowed
This is my views.py file. I tried POST on Postman but no luck. I can however, easily add through the API view that Django comes with. What am I missing? I have commented out the permissions for now. from django.contrib.auth.models import User from rest_framework import permissions, renderers, viewsets from rest_framework.decorators import action from rest_framework.response import Response from snippets.models import Snippet from snippets.permissions import IsOwnerOrReadOnly from snippets.serializers import SnippetSerializer, UserSerializer class SnippetViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. Additionally we also provide an extra `highlight` action. """ queryset = Snippet.objects.all() serializer_class = SnippetSerializer # permission_classes = ( # permissions.IsAuthenticatedOrReadOnly, # IsOwnerOrReadOnly, ) @action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer]) def highlight(self, request, *args, **kwargs): snippet = self.get_object() return Response(snippet.highlighted) def perform_create(self, serializer): serializer.save(owner=self.request.user) class UserViewSet(viewsets.ReadOnlyModelViewSet): """ This viewset automatically provides `list` and `detail` actions. """ queryset = User.objects.all() serializer_class = UserSerializer -
Index.js file error Warning: to load an ES module, set "type: "module" in the package.json file
I am working on django-rest-framework site and keep getting and error with the index.js file. I've tried adding the .mjs file extension and changing package.json but nothing has fixed this error. VS code gives me the error of 'App is declared but its value is never read ts(6133). I run the python manage.py runserver and then the npm dev server command and I do not have any errors yet I am still not able to get the site to render some of the values in the console properly. I am new to programming so please forgive my ignorance as I pretend to know something about what I am talking about here. Here is my index.js file import App from "./components/App"; This is the App.js file import React, { Component } from "react"; import { render } from "react-dom"; import HomePage from "./HomePage"; export default class App extends Component { constructor(props) { super(props); } render() { return ( <div> <HomePage /> </div> ); } } const appDiv = document.getElementById("app"); render(<App />, appDiv); package.json file { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack --mode development --watch", "build": "webpack --mode production" }, "keywords": [], "author": "", "license": "ISC", … -
ERROR: ServiceError - Failed to deploy application. on elastic beanstalk django
erorrs while deploying my application version is created in applications version list but not deployed to environment. -
Django pass list of tuples as url parameter
type = [('name1', 'value1'), ('name2', 'value2'), ('name3', 'value')] want to pass above list through url as queryparams. Can not parse it for searching. It returns as string. -
How can I make sms web service on python to send sms to every where?
I want to make a sms service(sms API) on python I don't how can I make this to send sms to every where? -
CloudFoundry: SFTP connection breaks with 'paramiko.ssh_exception.SSHException: Error reading SSH protocol banner'
I have a Django application deployed on CloudFoundry. I am trying to access an SFTP server using pysftp, but I am getting an exception. Below is the screenshot. Surprisingly, this connection was working couple of days back and I am unsure as what must have gone wrong. I am able to connect to the same SFTP instance using pysftp on my local development machine and another application that is deployed on AWS. What could possibly be going wrong here? -
Django filtering ManyToMany Field
i have these models on my Django Project class CarBundle(PolymorphicModel): name = models.CharField(_('Bundle Name'), max_length=255) car = models.ManyToManyField( 'cars.car', verbose_name=_('Car'), related_name='car_bundle', ) class Car(TimeStampedModel): name = models.CharField(_('Car Name'), max_length=50) manager = models.ForeignKey( 'cars.Manager', verbose_name=_('Car Manager'), related_name='cars', on_delete=models.CASCADE ) class Manager(models.Model): name = models.CharField(_('Name'), max_length=50) from CarBundle objects im trying to filter by Manager name, how do i do that? i tried adding manager_name on the response, but i get django.core.exceptions.FieldError: Cannot resolve keyword 'manager_name' into field. i also tried this (getting error though) CarBundle.objects.filter(car__manager__name__contains='john doe') Am i missing something? -
How to send a list of numbers / strings with scrapyd to a spider when using scrapyd.schedule
I'm trying to start my scrapy bot from a Django application and I need to pass in a list of strings and also a list of numbers that the bot requires to function. This is my code in the views.py of my Django application: task = scrapyd.schedule('default', 'arc', settings=settings, numIds=numIds, formOp=formOp) numId is the list of the numbers I need to pass and fromOp is the list of strings I need to pass. I tried extracting them in the scrapy spider file using: kwargs.get('numIds') kwargs.get('formOp') for some reason, it only gives me the first number/string in the list even if I try and send a JSON object. is there a way to pass the entire list through scrapyd? -
Django REST Framework - Django capitalized in `pip3 list`
I'm building an API using Django REST Framework. I'm getting a ModuleNotFoundError: No module named 'django' error when I try to test python3 manage.py. I've been going through the long list of issues it could be (reinstall django, need to add an __init__.py in the root, etc) and someone recommended checking my modules list with pip3 list. Here's what I see: Package Version ------------------- ------- asgiref 3.3.1 dj-database-url 0.5.0 Django 3.1.4 django-filter 2.4.0 django-heroku 0.3.1 djangorestframework 3.12.2 gunicorn 20.0.4 Is there a reason why Django's capitalized? Could that be why it isn't finding it in manage.py? If so, how do I go about fixing it? -
Django - Create a way for a user to upload an image, and display the image on website (Beginner help)
I'm new to Django and would like to create a way for a user to upload a photo to a post, when they are creating the post. Then that photo would also display on the post's individual page. I've been following this very closely: https://djangocentral.com/uploading-images-with-django/ But I cannot seem to get it to work. There isn't an error, but no image displays on either page. On the listing page if I click 'upload' nothing happens. The page stays the same. On the create page to create a listing, I haven't figured out yet how to get the html to work also. Would it be better to put the code for uploading an image, into the function for creating a post? I'm not sure if that might be the issue. Any help is appreciated! views.py for uploading the image: def image_upload_view(request): """Process images uploaded by users""" if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() # Get the current instance object to display in the template img_obj = form.instance return render(request, 'index.html', {'form': form, 'img_obj': img_obj}) else: form = ImageForm() return render(request, 'index.html', {'form': form}) urls.py path('upload/', views.image_upload_view), models.py class Image(models.Model): class Image(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='images') … -
I'm getting a ImproperlyConfigured error when I run my code
It says that my CreateView is missing a queryset, but I think it doesn't need one. So the form won't appear on the page. In my previous projects it doesn't need a get_queryset function. I tried to find code with the similar error but the cause of those problems where misspells and other syntax error. I am using django 3.1.4 [This is the error][1] Here is my views.py: class AboutView(TemplateView): template_name = "about.html" class PostListView(ListView): model = Post def get_queryset(self): return Post.objects.filter(publish_date__lte=timezone.now()).order_by('-publish_date') class PostDetailView(DetailView): model = Post class PostCreateView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'blogapp/post_detail.html' model = Post form_class = PostForm def get_queryset(self): class PostUpdateView(LoginRequiredMixin, UpdateView): login_url = '/login/' redirect_field_name = 'blogapp/post_detail.html' model = Post form_class = PostForm class PostDeleteView(LoginRequiredMixin, DeleteView): model = Post success_url = reverse_lazy('post_list') class DraftListView(LoginRequiredMixin, ListView): login_url = '/login/' redirect_field_name = 'blog/post_list.html' model = Post def get_queryset(self): return Post.objects.filter(publish_date__isnull=True).order_by('create_date') I need urgent help! -
Spyne + Django return Array (json) when same tag have more than one child return only the last
using Spyne + Django return Array (json) when same tag have more than one child return only the last child. example: @ rpc(String, String, _returns=Array(Data_obtenerAccion)) def obtenerAccion(ctx, ORIGEN_ACCION, CODIGO_ACCION): '''same query to get participants and contruct json to response, i dont put the example query becasue also with only json dont work.''' res = [] res.append( { "participantes":{ "participante":{ "name": "Jose" }, "participante":{ "name": "Jose" } } } ) return res How i can return this as complete children?. -
404 Error with Django URL even though it is included in url patterns
Here's the error I'm getting: Page not found (404) Request Method: GET Request URL: http://localhost:8000/bet/4/update Using the URLconf defined in chessbet.urls, Django tried these URL patterns, in this order: admin/ [name='bet-home'] bet/int:pk [name='bet-detail'] bet/int:pk/update/> [name='bet-update'] about/ [name='bet-about'] bet/new/ [name='bet-create'] register/ [name='register'] login/ [name='login'] logout/ [name='logout'] yourprofile/ [name='yourprofile'] ^media/(?P.*)$ The current path, bet/4/update, didn't match any of these. Now from what I see the current path is equivalent to the path I laid out for bet-update. What am I doing wrong here? Here is my urls.py: urlpatterns = [ path('', BetListView.as_view(), name = "bet-home"), path("bet/<int:pk>", BetDetailView.as_view(), name="bet-detail"), path("bet/<int:pk>/update/>", BetUpdateView.as_view(), name="bet-update"), path('about/', views.about, name = "bet-about"), path("bet/new/", BetCreateView.as_view(), name="bet-create") ] Bet detail which does something very similar works fine but bet update does not. Any help would be much appreciated.