Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NGINX Docker on Server with pre-existing NGINX
I am currently running into an issue with one of my projects that will be running in Docker on my Ubuntu Server with a NGINX docker container to manage the reverse proxy for the Django Project. My issue I am running into is I already have previous Django projects running on that particular Ubuntu server so port 80 is already being used by a NGINX block running on the actual server. Is there a workaround to running my Docker NGINX as well as the Ubuntu NGINX and have my docker image run as a "add on" site because the Django sites hosted there are clients websites, so I would prefer to not interfere with them if I dont have to. My project needs HTTPS because it is serving data to a React-Native app running on Android APK 28 which for some reason has a security rule that blocks non HTTPS connections from happening in the app. If anyone else has run into an issue like this I would gladly appreciate the advice on how to tackle this issue. I have tried running NGINX in Docker with port 81 instead of port 80 and that works perfectly, but I dont think … -
how to save registred users in django
here is my form.py file. from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class register_form(UserCreationForm): first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) class Meta(): model = User fields = ('username','email') here's my models.py file: from django.db import models from django.contrib.auth.models import User # Create your models here. class profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField() bio = models.TextField() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) joined_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username here's views.py file: from django.shortcuts import render,HttpResponseRedirect from .forms import register_form from django.contrib import messages from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from .models import profile # Create your views here. def register(request): if request.method == "post": register = register_form(request.post) if register.is_valid(): register.save() newUser=User(username=request.POST['username'], email=request.POST['email'], password=request.POST['password']) newUser.save() new_profile = profile(user=newUser, first_name=request.POST["first_name"], last_name=request.POST["last_name"]) new_profile.save() return render(request,'users/success.html') else: register = register_form() return render(request,'users/register.html',{"register":register}) here's the urls.py file: from django.urls import path,include from . import views urlpatterns = [ path('register/',views.register,name="register"), ] and here's the register.html file: {% extends 'users/base.html' %} {% load crispy_forms_tags %} <title>register</title> {% block content %} <div class="container-fluid"> <h1>instagram clone</h1> <p>register to view images and videos fo your friends</p> <form method="post"> {% csrf_token %} {{register|crispy}} <input type="submit" value="register"> </form> </div> {% endblock %} the django … -
are there any clever ways to save files with Web socket in Django?
I have built chatting site and I'm thinking that I can add the function of sending files besides message. But it seems that web socket can't send files or images. My solution is that when file is sent, I use api and then fetched messages and files are reordered by timestamp. But if there are better ways to achieve this, I really want to know. So, my question is Is it possible to send files by web socket and get them by WebsocketConsumer? Is there any ways to combine those two processes? (ex. you send provisional link of files and store them as FileField? ) model from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Contact(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='contact_user') friends = models.ManyToManyField('self', blank=True, related_name='friends') def __str__(self): return self.user.name class Message(models.Model): contact = models.ForeignKey(Contact, related_name='message', on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.contact.user.name class File(models.Model): contact = models.ForeignKey(Contact, related_name='file', on_delete=models.CASCADE) file = models.FileField() timestamp = models.DateTimeField(auto_now_add=True) class Chat(models.Model): participants = models.ManyToManyField(Contact, related_name='chats') messages = models.ManyToManyField(Message, blank=True) files = models.ManyToManyField(File, blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) def last_30_messages(self): return self.messages.order_by('-timestamp').all()[:30] def __str__(self): return "{}".format(self.pk) I don't know what information is needed to figure this out, … -
Django migrations for docker container
I have been trying to resolve an issue i am having currently, but i have not found any adequate solution neither here or elsewhere, so i was hoping someone here might have an answer. I have gotten to a point where i know what the problem is but not how to resolve it. Basically i have a website running django/postgres/nginx, it runs smoothly and i can make new models and migrate them, but if i try to add a field to the model: from django.db import models class project(models.Model): project_name = models.CharField(max_length=50) author = models.CharField(max_length=30, blank=True, null=True) date_created = models.DateField() #Added in second round of migrations #Description = models.CharField(max_length=150,blank=True, null=True) What i would normally do is initially build and spin up my container sudo docker-compose -f docker-compose.yml up --build And within my entrypoint file i run makemigrations and migrate. The first round it works well, but if i add the Description field to my model, spin down and rebuild the container to allow the new field to be included in my container, the new container is build without the initial migration, and isntead with a new migration. This results in any previous postgres tables not getting the new field added … -
How to add a field to an existing model
I would like to extend and override the fields existing in the User model, which is found in "django.contrib.auth.models" (The model is already created). I first attempted to create a Foreign-Key and a One-to-One relationship between the User model, and a Client model (in which I added the extra fields), but I don't think it is good practice. How could I directly add and override fields within the User model and not have to create another class model to extend it. from django.contrib.auth.models import User class Clients(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) #client = models.OneToOneField(User, on_delete=models.CASCADE) cell = models.PositiveIntegerField (blank=False) address = models.CharField(default = "Sandton, JHB", blank = False, max_length=132) -
Using django template variables in a JavaScript file
I want to use the template variables in javascript file which is linked to the template. For eg. <!-- The template --> <h1>{{ user.username }}</h1> <script src="{% static 'profile_page/js/index.js' %}"></script> // The script file (a different file) console.log('{{ user.username }}'); -
Django registration profile
I am new in django. I would like to create registration profile. I found some code but it doesn´t work for me. When I want to makemigrations I always get this error AttributeError: Manager isn't available; 'auth.User' has been swapped for 'user.User' I read that I could fix it with User = get_user_model() but it looks it is doesn´t work for me. My models.py import random from django.contrib.auth import get_user_model from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver User = get_user_model() def code_generator(length=5): numbers = '0123456789' return ''.join(random.choice(numbers) for _ in range(length)) class RegistrationProfile(models.Model): code = models.CharField(default=code_generator, max_length=5) user = models.OneToOneField(to=User, on_delete=models.CASCADE, related_name='registration_profile', primary_key=True) @receiver(post_save, sender=User) def create_registration_profile(sender, instance, **kwargs): profile, created = RegistrationProfile.objects.get_or_create(user=instance) if created: profile.save() serializer.py from rest_framework import serializers from rest_framework.validators import UniqueValidator from django.contrib.auth.password_validation import validate_password from .models import User class RegisterSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField(write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('username', 'password', 'password2', 'email', 'first_name', 'last_name') extra_kwargs = { 'first_name': {'required': True}, 'last_name': {'required': True} } def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError({"password": "Password fields didn't match."}) return attrs def create(self, validated_data): user = User.objects.create( username=validated_data['username'], … -
Is there a way to check client in Django server without user authentication?
So I'm trying to build a Django application which provides each user with some contents but only limited to three times each day. For sake of convenience, I'm not thinking of creating/using any pre-existing user model or authentication. But since I have to limit the number of contents shown to each user, I have to tell if the current request is from the same person or not. I can think of enabling this in the front-end using local storage, cookie, etc. (Neglecting security issue or others, since this is just a toy project.) But I'm wondering if there is a way to do this in the back-end without using user authentication. Any ideas? Thank you very much in advance :) -
Static css in Django works unstable
I have css with following content in ecommerce/ecommerse/static/scc folder: body {background: #68951c;} h1 {color: #000000;} When i want to change the color of background, it changes in PyCharm, but it isn't changes on the web page even when i change a color in BOTH 1) ecommerce/static/scc and 2) ecommerce/ecommerse/static/scc manually. Even though command "python manage.py collectstatic" had run and server had re-run it is needlessly. Only one effect - when I ctrl+X following string in html page: <link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}"> then background evaporates. And when i insert the upper markup and refresh page, it appears again (upper markup contained in , in it is not working for some reason) -
Serve Voice files in Django
I want to serve voice files in the Django app and let users play and have all features like youtube. Voice files are in large size, and the client should not wait for all file to play, and they can move in all voice time and play any part they want -
How to check validation on two fields in a form?
Need to add an image to the form either by entering a link to the image, or upload a file from your computer. If no options were entered when the form was submitted, or both options were entered, an error message should be displayed. And after successful loading, you should get to the image page. models.py: class Picture(models.Model): url = models.URLField(blank=True, verbose_name='Ссылка на изображение') image = models.ImageField(upload_to='pictures/%Y/%m/%d', width_field='image_width', height_field='image_height', blank=True, verbose_name='Изображение') image_width = models.IntegerField(default=0, blank=True, verbose_name='Ширина изображения') image_height = models.IntegerField(default=0, blank=True, verbose_name='Высота изображения') is_active = models.BooleanField(default=True, verbose_name='Актуальность изображения') created = models.DateField(blank=True, null=True, default=timezone.now, verbose_name='Дата создания записи') updated = models.DateField(blank=True, null=True, default=timezone.now, verbose_name='Дата ред-ия записи') views.py: def add_picture(request): picture = Picture.objects.filter(is_active=True) if request.method == 'POST': form = PictureCreateForm(data=request.POST, files=request.FILES) if form.is_valid(): form.save() return render(request, 'add_picture.html', locals()) else: messages.error(request, 'Ошибка, проверьте данные') else: form = PictureCreateForm() return render(request, 'add_picture.html', locals()) forms.py: class PictureCreateForm(forms.ModelForm): class Meta: model = Picture fields = ('url', 'image') urls.py: urlpatterns = [ path('', views.home, name='home'), path('add_picture/', views.add_picture, name='add_picture'), path('picture_detail/<int:id>/', views.picture_detail, name='picture_detail'), ] -
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", …